babylon.max.js 3.0 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595605966059760598605996060060601606026060360604606056060660607606086060960610606116061260613606146061560616606176061860619606206062160622606236062460625606266062760628606296063060631606326063360634606356063660637606386063960640606416064260643606446064560646606476064860649606506065160652606536065460655606566065760658606596066060661606626066360664606656066660667606686066960670606716067260673606746067560676606776067860679606806068160682606836068460685606866068760688606896069060691606926069360694606956069660697606986069960700607016070260703607046070560706607076070860709607106071160712607136071460715607166071760718607196072060721607226072360724607256072660727607286072960730607316073260733607346073560736607376073860739607406074160742607436074460745607466074760748607496075060751607526075360754607556075660757607586075960760607616076260763607646076560766607676076860769607706077160772607736077460775607766077760778607796078060781607826078360784607856078660787607886078960790607916079260793607946079560796607976079860799608006080160802608036080460805608066080760808608096081060811608126081360814608156081660817608186081960820608216082260823608246082560826608276082860829608306083160832608336083460835608366083760838608396084060841608426084360844608456084660847608486084960850608516085260853608546085560856608576085860859608606086160862608636086460865608666086760868608696087060871608726087360874608756087660877608786087960880608816088260883608846088560886608876088860889608906089160892608936089460895608966089760898608996090060901609026090360904609056090660907609086090960910609116091260913609146091560916609176091860919609206092160922609236092460925609266092760928609296093060931609326093360934609356093660937609386093960940609416094260943609446094560946609476094860949609506095160952609536095460955609566095760958609596096060961609626096360964609656096660967609686096960970609716097260973609746097560976609776097860979609806098160982609836098460985609866098760988609896099060991609926099360994609956099660997609986099961000610016100261003610046100561006610076100861009610106101161012610136101461015610166101761018610196102061021610226102361024610256102661027610286102961030610316103261033610346103561036610376103861039610406104161042610436104461045610466104761048610496105061051610526105361054610556105661057610586105961060610616106261063610646106561066610676106861069610706107161072610736107461075610766107761078610796108061081610826108361084610856108661087610886108961090610916109261093610946109561096610976109861099611006110161102611036110461105611066110761108611096111061111611126111361114611156111661117611186111961120611216112261123611246112561126611276112861129611306113161132611336113461135611366113761138611396114061141611426114361144611456114661147611486114961150611516115261153611546115561156611576115861159611606116161162611636116461165611666116761168611696117061171611726117361174611756117661177611786117961180611816118261183611846118561186611876118861189611906119161192611936119461195611966119761198611996120061201612026120361204612056120661207612086120961210612116121261213612146121561216612176121861219612206122161222612236122461225612266122761228612296123061231612326123361234612356123661237612386123961240612416124261243612446124561246612476124861249612506125161252612536125461255612566125761258612596126061261612626126361264612656126661267612686126961270612716127261273612746127561276612776127861279612806128161282612836128461285612866128761288612896129061291612926129361294612956129661297612986129961300613016130261303613046130561306613076130861309613106131161312613136131461315613166131761318613196132061321613226132361324613256132661327613286132961330613316133261333613346133561336613376133861339613406134161342613436134461345613466134761348613496135061351613526135361354613556135661357613586135961360613616136261363613646136561366613676136861369613706137161372613736137461375613766137761378613796138061381613826138361384613856138661387613886138961390613916139261393613946139561396613976139861399614006140161402614036140461405614066140761408614096141061411614126141361414614156141661417614186141961420614216142261423614246142561426614276142861429614306143161432614336143461435614366143761438614396144061441614426144361444614456144661447614486144961450614516145261453614546145561456614576145861459614606146161462614636146461465614666146761468614696147061471614726147361474614756147661477614786147961480614816148261483614846148561486614876148861489614906149161492614936149461495614966149761498614996150061501615026150361504615056150661507615086150961510615116151261513615146151561516615176151861519615206152161522615236152461525615266152761528615296153061531615326153361534615356153661537615386153961540615416154261543615446154561546615476154861549615506155161552615536155461555615566155761558615596156061561615626156361564615656156661567615686156961570615716157261573615746157561576615776157861579615806158161582615836158461585615866158761588615896159061591615926159361594615956159661597615986159961600616016160261603616046160561606616076160861609616106161161612616136161461615616166161761618616196162061621616226162361624616256162661627616286162961630616316163261633616346163561636616376163861639616406164161642616436164461645616466164761648616496165061651616526165361654616556165661657616586165961660616616166261663616646166561666616676166861669616706167161672616736167461675616766167761678616796168061681616826168361684616856168661687616886168961690616916169261693616946169561696616976169861699617006170161702617036170461705617066170761708617096171061711617126171361714617156171661717617186171961720617216172261723617246172561726617276172861729617306173161732617336173461735617366173761738617396174061741617426174361744617456174661747617486174961750617516175261753617546175561756617576175861759617606176161762617636176461765617666176761768617696177061771617726177361774617756177661777617786177961780617816178261783617846178561786617876178861789617906179161792617936179461795617966179761798617996180061801618026180361804618056180661807618086180961810618116181261813618146181561816618176181861819618206182161822618236182461825618266182761828618296183061831618326183361834618356183661837618386183961840618416184261843618446184561846618476184861849618506185161852618536185461855618566185761858618596186061861618626186361864618656186661867618686186961870618716187261873618746187561876618776187861879618806188161882618836188461885618866188761888618896189061891618926189361894618956189661897618986189961900619016190261903619046190561906619076190861909619106191161912619136191461915619166191761918619196192061921619226192361924619256192661927619286192961930619316193261933619346193561936619376193861939619406194161942619436194461945619466194761948619496195061951619526195361954619556195661957619586195961960619616196261963619646196561966619676196861969619706197161972619736197461975619766197761978619796198061981619826198361984619856198661987619886198961990619916199261993619946199561996619976199861999620006200162002620036200462005620066200762008620096201062011620126201362014620156201662017620186201962020620216202262023620246202562026620276202862029620306203162032620336203462035620366203762038620396204062041620426204362044620456204662047620486204962050620516205262053620546205562056620576205862059620606206162062620636206462065620666206762068620696207062071620726207362074620756207662077620786207962080620816208262083620846208562086620876208862089620906209162092620936209462095620966209762098620996210062101621026210362104621056210662107621086210962110621116211262113621146211562116621176211862119621206212162122621236212462125621266212762128621296213062131621326213362134621356213662137621386213962140621416214262143621446214562146621476214862149621506215162152621536215462155621566215762158621596216062161621626216362164621656216662167621686216962170621716217262173621746217562176621776217862179621806218162182621836218462185621866218762188621896219062191621926219362194621956219662197621986219962200622016220262203622046220562206622076220862209622106221162212622136221462215622166221762218622196222062221622226222362224622256222662227622286222962230622316223262233622346223562236622376223862239622406224162242622436224462245622466224762248622496225062251622526225362254622556225662257622586225962260622616226262263622646226562266622676226862269622706227162272622736227462275622766227762278622796228062281622826228362284622856228662287622886228962290622916229262293622946229562296622976229862299623006230162302623036230462305623066230762308623096231062311623126231362314623156231662317623186231962320623216232262323623246232562326623276232862329623306233162332623336233462335623366233762338623396234062341623426234362344623456234662347623486234962350623516235262353623546235562356623576235862359623606236162362623636236462365623666236762368623696237062371623726237362374623756237662377623786237962380623816238262383623846238562386623876238862389623906239162392623936239462395623966239762398623996240062401624026240362404624056240662407624086240962410624116241262413624146241562416624176241862419624206242162422624236242462425624266242762428624296243062431624326243362434624356243662437624386243962440624416244262443624446244562446624476244862449624506245162452624536245462455624566245762458624596246062461624626246362464624656246662467624686246962470624716247262473624746247562476624776247862479624806248162482624836248462485624866248762488624896249062491624926249362494624956249662497624986249962500625016250262503625046250562506625076250862509625106251162512625136251462515625166251762518625196252062521625226252362524625256252662527625286252962530625316253262533625346253562536625376253862539625406254162542625436254462545625466254762548625496255062551625526255362554625556255662557625586255962560625616256262563625646256562566625676256862569625706257162572625736257462575625766257762578625796258062581625826258362584625856258662587625886258962590625916259262593625946259562596625976259862599626006260162602626036260462605626066260762608626096261062611626126261362614626156261662617626186261962620626216262262623626246262562626626276262862629626306263162632626336263462635626366263762638626396264062641626426264362644626456264662647626486264962650626516265262653626546265562656626576265862659626606266162662626636266462665626666266762668626696267062671626726267362674626756267662677626786267962680626816268262683626846268562686626876268862689626906269162692626936269462695626966269762698626996270062701627026270362704627056270662707627086270962710627116271262713627146271562716627176271862719627206272162722627236272462725627266272762728627296273062731627326273362734627356273662737627386273962740627416274262743627446274562746627476274862749627506275162752627536275462755627566275762758627596276062761627626276362764627656276662767627686276962770627716277262773627746277562776627776277862779627806278162782627836278462785627866278762788627896279062791627926279362794627956279662797627986279962800628016280262803628046280562806628076280862809628106281162812628136281462815628166281762818628196282062821628226282362824628256282662827628286282962830628316283262833628346283562836628376283862839628406284162842628436284462845628466284762848628496285062851628526285362854628556285662857628586285962860628616286262863628646286562866628676286862869628706287162872628736287462875628766287762878628796288062881628826288362884628856288662887628886288962890628916289262893628946289562896628976289862899629006290162902629036290462905629066290762908629096291062911629126291362914629156291662917629186291962920629216292262923629246292562926629276292862929629306293162932629336293462935629366293762938629396294062941629426294362944629456294662947629486294962950629516295262953629546295562956629576295862959629606296162962629636296462965629666296762968629696297062971629726297362974629756297662977629786297962980629816298262983629846298562986629876298862989629906299162992629936299462995629966299762998629996300063001630026300363004630056300663007630086300963010630116301263013630146301563016630176301863019630206302163022630236302463025630266302763028630296303063031630326303363034630356303663037630386303963040630416304263043630446304563046630476304863049630506305163052630536305463055630566305763058630596306063061630626306363064630656306663067630686306963070630716307263073630746307563076630776307863079630806308163082630836308463085630866308763088630896309063091630926309363094630956309663097630986309963100631016310263103631046310563106631076310863109631106311163112631136311463115631166311763118631196312063121631226312363124631256312663127631286312963130631316313263133631346313563136631376313863139631406314163142631436314463145631466314763148631496315063151631526315363154631556315663157631586315963160631616316263163631646316563166
  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 = false;
  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. Engine.prototype.setDitheringState = function (value) {
  7719. if (value) {
  7720. this._gl.enable(this._gl.DITHER);
  7721. }
  7722. else {
  7723. this._gl.disable(this._gl.DITHER);
  7724. }
  7725. };
  7726. /**
  7727. * stop executing a render loop function and remove it from the execution array
  7728. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  7729. */
  7730. Engine.prototype.stopRenderLoop = function (renderFunction) {
  7731. if (!renderFunction) {
  7732. this._activeRenderLoops = [];
  7733. return;
  7734. }
  7735. var index = this._activeRenderLoops.indexOf(renderFunction);
  7736. if (index >= 0) {
  7737. this._activeRenderLoops.splice(index, 1);
  7738. }
  7739. };
  7740. Engine.prototype._renderLoop = function () {
  7741. var shouldRender = true;
  7742. if (!this.renderEvenInBackground && this._windowIsBackground) {
  7743. shouldRender = false;
  7744. }
  7745. if (shouldRender) {
  7746. // Start new frame
  7747. this.beginFrame();
  7748. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  7749. var renderFunction = this._activeRenderLoops[index];
  7750. renderFunction();
  7751. }
  7752. // Present
  7753. this.endFrame();
  7754. }
  7755. if (this._activeRenderLoops.length > 0) {
  7756. // Register new frame
  7757. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, this._vrDisplayEnabled);
  7758. }
  7759. else {
  7760. this._renderingQueueLaunched = false;
  7761. }
  7762. };
  7763. /**
  7764. * Register and execute a render loop. The engine can have more than one render function.
  7765. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  7766. * @example
  7767. * engine.runRenderLoop(function () {
  7768. * scene.render()
  7769. * })
  7770. */
  7771. Engine.prototype.runRenderLoop = function (renderFunction) {
  7772. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  7773. return;
  7774. }
  7775. this._activeRenderLoops.push(renderFunction);
  7776. if (!this._renderingQueueLaunched) {
  7777. this._renderingQueueLaunched = true;
  7778. this._bindedRenderFunction = this._renderLoop.bind(this);
  7779. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  7780. }
  7781. };
  7782. /**
  7783. * Toggle full screen mode.
  7784. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  7785. * @param {any} options - an options object to be sent to the requestFullscreen function
  7786. */
  7787. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  7788. if (this.isFullscreen) {
  7789. BABYLON.Tools.ExitFullscreen();
  7790. }
  7791. else {
  7792. this._pointerLockRequested = requestPointerLock;
  7793. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  7794. }
  7795. };
  7796. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  7797. if (stencil === void 0) { stencil = false; }
  7798. this.applyStates();
  7799. var mode = 0;
  7800. if (backBuffer && color) {
  7801. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  7802. mode |= this._gl.COLOR_BUFFER_BIT;
  7803. }
  7804. if (depth) {
  7805. this._gl.clearDepth(1.0);
  7806. mode |= this._gl.DEPTH_BUFFER_BIT;
  7807. }
  7808. if (stencil) {
  7809. this._gl.clearStencil(0);
  7810. mode |= this._gl.STENCIL_BUFFER_BIT;
  7811. }
  7812. this._gl.clear(mode);
  7813. };
  7814. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  7815. var gl = this._gl;
  7816. // Save state
  7817. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  7818. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  7819. // Change state
  7820. gl.enable(gl.SCISSOR_TEST);
  7821. gl.scissor(x, y, width, height);
  7822. // Clear
  7823. this.clear(clearColor, true, true, true);
  7824. // Restore state
  7825. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  7826. if (curScissor === true) {
  7827. gl.enable(gl.SCISSOR_TEST);
  7828. }
  7829. else {
  7830. gl.disable(gl.SCISSOR_TEST);
  7831. }
  7832. };
  7833. /**
  7834. * Set the WebGL's viewport
  7835. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  7836. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  7837. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  7838. */
  7839. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  7840. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this.getRenderWidth());
  7841. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this.getRenderHeight());
  7842. var x = viewport.x || 0;
  7843. var y = viewport.y || 0;
  7844. this._cachedViewport = viewport;
  7845. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  7846. };
  7847. /**
  7848. * Directly set the WebGL Viewport
  7849. * The x, y, width & height are directly passed to the WebGL call
  7850. * @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.
  7851. */
  7852. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  7853. var currentViewport = this._cachedViewport;
  7854. this._cachedViewport = null;
  7855. this._gl.viewport(x, y, width, height);
  7856. return currentViewport;
  7857. };
  7858. Engine.prototype.beginFrame = function () {
  7859. this._measureFps();
  7860. };
  7861. Engine.prototype.endFrame = function () {
  7862. //force a flush in case we are using a bad OS.
  7863. if (this._badOS) {
  7864. this.flushFramebuffer();
  7865. }
  7866. //submit frame to the vr device, if enabled
  7867. if (this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting) {
  7868. this._vrDisplayEnabled.submitFrame();
  7869. }
  7870. };
  7871. /**
  7872. * resize the view according to the canvas' size.
  7873. * @example
  7874. * window.addEventListener("resize", function () {
  7875. * engine.resize();
  7876. * });
  7877. */
  7878. Engine.prototype.resize = function () {
  7879. // We're not resizing the size of the canvas while in VR mode & presenting
  7880. if (!(this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting)) {
  7881. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  7882. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  7883. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  7884. }
  7885. };
  7886. /**
  7887. * force a specific size of the canvas
  7888. * @param {number} width - the new canvas' width
  7889. * @param {number} height - the new canvas' height
  7890. */
  7891. Engine.prototype.setSize = function (width, height) {
  7892. this._renderingCanvas.width = width;
  7893. this._renderingCanvas.height = height;
  7894. for (var index = 0; index < this.scenes.length; index++) {
  7895. var scene = this.scenes[index];
  7896. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  7897. var cam = scene.cameras[camIndex];
  7898. cam._currentRenderId = 0;
  7899. }
  7900. }
  7901. };
  7902. //WebVR functions
  7903. Engine.prototype.initWebVR = function () {
  7904. if (!this.vrDisplaysPromise) {
  7905. this._getVRDisplays();
  7906. }
  7907. };
  7908. Engine.prototype.enableVR = function (vrDevice) {
  7909. this._vrDisplayEnabled = vrDevice;
  7910. this._vrDisplayEnabled.requestPresent([{ source: this.getRenderingCanvas() }]).then(this._onVRFullScreenTriggered);
  7911. };
  7912. Engine.prototype.disableVR = function () {
  7913. if (this._vrDisplayEnabled) {
  7914. this._vrDisplayEnabled.exitPresent().then(this._onVRFullScreenTriggered);
  7915. }
  7916. };
  7917. Engine.prototype._getVRDisplays = function () {
  7918. var _this = this;
  7919. var getWebVRDevices = function (devices) {
  7920. var size = devices.length;
  7921. var i = 0;
  7922. _this._vrDisplays = devices.filter(function (device) {
  7923. return devices[i] instanceof VRDisplay;
  7924. });
  7925. return _this._vrDisplays;
  7926. };
  7927. //using a key due to typescript
  7928. if (navigator.getVRDisplays) {
  7929. this.vrDisplaysPromise = navigator.getVRDisplays().then(getWebVRDevices);
  7930. }
  7931. };
  7932. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight) {
  7933. this._currentRenderTarget = texture;
  7934. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  7935. var gl = this._gl;
  7936. if (texture.isCube) {
  7937. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  7938. }
  7939. gl.viewport(0, 0, requiredWidth || texture._width, requiredHeight || texture._height);
  7940. this.wipeCaches();
  7941. };
  7942. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  7943. if (this._currentFramebuffer !== framebuffer) {
  7944. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  7945. this._currentFramebuffer = framebuffer;
  7946. }
  7947. };
  7948. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  7949. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  7950. this._currentRenderTarget = null;
  7951. // If MSAA, we need to bitblt back to main texture
  7952. var gl = this._gl;
  7953. if (texture._MSAAFramebuffer) {
  7954. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  7955. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  7956. gl.blitFramebuffer(0, 0, texture._width, texture._height, 0, 0, texture._width, texture._height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  7957. }
  7958. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  7959. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  7960. gl.generateMipmap(gl.TEXTURE_2D);
  7961. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  7962. }
  7963. if (onBeforeUnbind) {
  7964. if (texture._MSAAFramebuffer) {
  7965. // Bind the correct framebuffer
  7966. this.bindUnboundFramebuffer(texture._framebuffer);
  7967. }
  7968. onBeforeUnbind();
  7969. }
  7970. this.bindUnboundFramebuffer(null);
  7971. };
  7972. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  7973. if (texture.generateMipMaps) {
  7974. var gl = this._gl;
  7975. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  7976. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  7977. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  7978. }
  7979. };
  7980. Engine.prototype.flushFramebuffer = function () {
  7981. this._gl.flush();
  7982. };
  7983. Engine.prototype.restoreDefaultFramebuffer = function () {
  7984. this._currentRenderTarget = null;
  7985. this.bindUnboundFramebuffer(null);
  7986. this.setViewport(this._cachedViewport);
  7987. this.wipeCaches();
  7988. };
  7989. // UBOs
  7990. Engine.prototype.createUniformBuffer = function (elements) {
  7991. var ubo = this._gl.createBuffer();
  7992. this.bindUniformBuffer(ubo);
  7993. if (elements instanceof Float32Array) {
  7994. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  7995. }
  7996. else {
  7997. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  7998. }
  7999. this.bindUniformBuffer(null);
  8000. ubo.references = 1;
  8001. return ubo;
  8002. };
  8003. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  8004. var ubo = this._gl.createBuffer();
  8005. this.bindUniformBuffer(ubo);
  8006. if (elements instanceof Float32Array) {
  8007. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  8008. }
  8009. else {
  8010. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  8011. }
  8012. this.bindUniformBuffer(null);
  8013. ubo.references = 1;
  8014. return ubo;
  8015. };
  8016. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  8017. this.bindUniformBuffer(uniformBuffer);
  8018. if (offset === undefined) {
  8019. offset = 0;
  8020. }
  8021. if (count === undefined) {
  8022. if (elements instanceof Float32Array) {
  8023. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  8024. }
  8025. else {
  8026. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  8027. }
  8028. }
  8029. else {
  8030. if (elements instanceof Float32Array) {
  8031. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  8032. }
  8033. else {
  8034. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  8035. }
  8036. }
  8037. this.bindUniformBuffer(null);
  8038. };
  8039. // VBOs
  8040. Engine.prototype._resetVertexBufferBinding = function () {
  8041. this.bindArrayBuffer(null);
  8042. this._cachedVertexBuffers = null;
  8043. };
  8044. Engine.prototype.createVertexBuffer = function (vertices) {
  8045. var vbo = this._gl.createBuffer();
  8046. this.bindArrayBuffer(vbo);
  8047. if (vertices instanceof Float32Array) {
  8048. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  8049. }
  8050. else {
  8051. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  8052. }
  8053. this._resetVertexBufferBinding();
  8054. vbo.references = 1;
  8055. return vbo;
  8056. };
  8057. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  8058. var vbo = this._gl.createBuffer();
  8059. this.bindArrayBuffer(vbo);
  8060. if (vertices instanceof Float32Array) {
  8061. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  8062. }
  8063. else {
  8064. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  8065. }
  8066. this._resetVertexBufferBinding();
  8067. vbo.references = 1;
  8068. return vbo;
  8069. };
  8070. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  8071. this.bindArrayBuffer(vertexBuffer);
  8072. if (offset === undefined) {
  8073. offset = 0;
  8074. }
  8075. if (count === undefined) {
  8076. if (vertices instanceof Float32Array) {
  8077. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  8078. }
  8079. else {
  8080. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  8081. }
  8082. }
  8083. else {
  8084. if (vertices instanceof Float32Array) {
  8085. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  8086. }
  8087. else {
  8088. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  8089. }
  8090. }
  8091. this._resetVertexBufferBinding();
  8092. };
  8093. Engine.prototype._resetIndexBufferBinding = function () {
  8094. this.bindIndexBuffer(null);
  8095. this._cachedIndexBuffer = null;
  8096. };
  8097. Engine.prototype.createIndexBuffer = function (indices) {
  8098. var vbo = this._gl.createBuffer();
  8099. this.bindIndexBuffer(vbo);
  8100. // Check for 32 bits indices
  8101. var arrayBuffer;
  8102. var need32Bits = false;
  8103. if (indices instanceof Uint16Array) {
  8104. arrayBuffer = indices;
  8105. }
  8106. else {
  8107. //check 32 bit support
  8108. if (this._caps.uintIndices) {
  8109. if (indices instanceof Uint32Array) {
  8110. arrayBuffer = indices;
  8111. need32Bits = true;
  8112. }
  8113. else {
  8114. //number[] or Int32Array, check if 32 bit is necessary
  8115. for (var index = 0; index < indices.length; index++) {
  8116. if (indices[index] > 65535) {
  8117. need32Bits = true;
  8118. break;
  8119. }
  8120. }
  8121. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  8122. }
  8123. }
  8124. else {
  8125. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  8126. arrayBuffer = new Uint16Array(indices);
  8127. }
  8128. }
  8129. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  8130. this._resetIndexBufferBinding();
  8131. vbo.references = 1;
  8132. vbo.is32Bits = need32Bits;
  8133. return vbo;
  8134. };
  8135. Engine.prototype.bindArrayBuffer = function (buffer) {
  8136. if (!this._vaoRecordInProgress) {
  8137. this._unBindVertexArrayObject();
  8138. }
  8139. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  8140. };
  8141. Engine.prototype.bindUniformBuffer = function (buffer) {
  8142. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  8143. };
  8144. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  8145. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  8146. };
  8147. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  8148. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  8149. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  8150. };
  8151. ;
  8152. Engine.prototype.bindIndexBuffer = function (buffer) {
  8153. if (!this._vaoRecordInProgress) {
  8154. this._unBindVertexArrayObject();
  8155. }
  8156. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  8157. };
  8158. Engine.prototype.bindBuffer = function (buffer, target) {
  8159. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  8160. this._gl.bindBuffer(target, buffer);
  8161. this._currentBoundBuffer[target] = buffer;
  8162. }
  8163. };
  8164. Engine.prototype.updateArrayBuffer = function (data) {
  8165. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  8166. };
  8167. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  8168. var pointer = this._currentBufferPointers[indx];
  8169. var changed = false;
  8170. if (!pointer) {
  8171. changed = true;
  8172. this._currentBufferPointers[indx] = { indx: indx, size: size, type: type, normalized: normalized, stride: stride, offset: offset, buffer: buffer };
  8173. }
  8174. else {
  8175. if (pointer.buffer !== buffer) {
  8176. pointer.buffer = buffer;
  8177. changed = true;
  8178. }
  8179. if (pointer.size !== size) {
  8180. pointer.size = size;
  8181. changed = true;
  8182. }
  8183. if (pointer.type !== type) {
  8184. pointer.type = type;
  8185. changed = true;
  8186. }
  8187. if (pointer.normalized !== normalized) {
  8188. pointer.normalized = normalized;
  8189. changed = true;
  8190. }
  8191. if (pointer.stride !== stride) {
  8192. pointer.stride = stride;
  8193. changed = true;
  8194. }
  8195. if (pointer.offset !== offset) {
  8196. pointer.offset = offset;
  8197. changed = true;
  8198. }
  8199. }
  8200. if (changed || this._vaoRecordInProgress) {
  8201. this.bindArrayBuffer(buffer);
  8202. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  8203. }
  8204. };
  8205. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  8206. if (indexBuffer == null) {
  8207. return;
  8208. }
  8209. if (this._cachedIndexBuffer !== indexBuffer) {
  8210. this._cachedIndexBuffer = indexBuffer;
  8211. this.bindIndexBuffer(indexBuffer);
  8212. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  8213. }
  8214. };
  8215. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  8216. var attributes = effect.getAttributesNames();
  8217. if (!this._vaoRecordInProgress) {
  8218. this._unBindVertexArrayObject();
  8219. }
  8220. this.unbindAllAttributes();
  8221. for (var index = 0; index < attributes.length; index++) {
  8222. var order = effect.getAttributeLocation(index);
  8223. if (order >= 0) {
  8224. var vertexBuffer = vertexBuffers[attributes[index]];
  8225. if (!vertexBuffer) {
  8226. continue;
  8227. }
  8228. this._gl.enableVertexAttribArray(order);
  8229. if (!this._vaoRecordInProgress) {
  8230. this._vertexAttribArraysEnabled[order] = true;
  8231. }
  8232. var buffer = vertexBuffer.getBuffer();
  8233. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  8234. if (vertexBuffer.getIsInstanced()) {
  8235. this._gl.vertexAttribDivisor(order, 1);
  8236. if (!this._vaoRecordInProgress) {
  8237. this._currentInstanceLocations.push(order);
  8238. this._currentInstanceBuffers.push(buffer);
  8239. }
  8240. }
  8241. }
  8242. }
  8243. };
  8244. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  8245. var vao = this._gl.createVertexArray();
  8246. this._vaoRecordInProgress = true;
  8247. this._gl.bindVertexArray(vao);
  8248. this._mustWipeVertexAttributes = true;
  8249. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  8250. this.bindIndexBuffer(indexBuffer);
  8251. this._vaoRecordInProgress = false;
  8252. this._gl.bindVertexArray(null);
  8253. return vao;
  8254. };
  8255. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  8256. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  8257. this._cachedVertexArrayObject = vertexArrayObject;
  8258. this._gl.bindVertexArray(vertexArrayObject);
  8259. this._cachedVertexBuffers = null;
  8260. this._cachedIndexBuffer = null;
  8261. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  8262. this._mustWipeVertexAttributes = true;
  8263. }
  8264. };
  8265. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  8266. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  8267. this._cachedVertexBuffers = vertexBuffer;
  8268. this._cachedEffectForVertexBuffers = effect;
  8269. var attributesCount = effect.getAttributesCount();
  8270. this._unBindVertexArrayObject();
  8271. this.unbindAllAttributes();
  8272. var offset = 0;
  8273. for (var index = 0; index < attributesCount; index++) {
  8274. if (index < vertexDeclaration.length) {
  8275. var order = effect.getAttributeLocation(index);
  8276. if (order >= 0) {
  8277. this._gl.enableVertexAttribArray(order);
  8278. this._vertexAttribArraysEnabled[order] = true;
  8279. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  8280. }
  8281. offset += vertexDeclaration[index] * 4;
  8282. }
  8283. }
  8284. }
  8285. this._bindIndexBufferWithCache(indexBuffer);
  8286. };
  8287. Engine.prototype._unBindVertexArrayObject = function () {
  8288. if (!this._cachedVertexArrayObject) {
  8289. return;
  8290. }
  8291. this._cachedVertexArrayObject = null;
  8292. this._gl.bindVertexArray(null);
  8293. };
  8294. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  8295. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  8296. this._cachedVertexBuffers = vertexBuffers;
  8297. this._cachedEffectForVertexBuffers = effect;
  8298. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  8299. }
  8300. this._bindIndexBufferWithCache(indexBuffer);
  8301. };
  8302. Engine.prototype.unbindInstanceAttributes = function () {
  8303. var boundBuffer;
  8304. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  8305. var instancesBuffer = this._currentInstanceBuffers[i];
  8306. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  8307. boundBuffer = instancesBuffer;
  8308. this.bindArrayBuffer(instancesBuffer);
  8309. }
  8310. var offsetLocation = this._currentInstanceLocations[i];
  8311. this._gl.vertexAttribDivisor(offsetLocation, 0);
  8312. }
  8313. this._currentInstanceBuffers.length = 0;
  8314. this._currentInstanceLocations.length = 0;
  8315. };
  8316. Engine.prototype.releaseVertexArrayObject = function (vao) {
  8317. this._gl.deleteVertexArray(vao);
  8318. };
  8319. Engine.prototype._releaseBuffer = function (buffer) {
  8320. buffer.references--;
  8321. if (buffer.references === 0) {
  8322. this._gl.deleteBuffer(buffer);
  8323. return true;
  8324. }
  8325. return false;
  8326. };
  8327. Engine.prototype.createInstancesBuffer = function (capacity) {
  8328. var buffer = this._gl.createBuffer();
  8329. buffer.capacity = capacity;
  8330. this.bindArrayBuffer(buffer);
  8331. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  8332. return buffer;
  8333. };
  8334. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  8335. this._gl.deleteBuffer(buffer);
  8336. };
  8337. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  8338. this.bindArrayBuffer(instancesBuffer);
  8339. if (data) {
  8340. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  8341. }
  8342. if (offsetLocations[0].index !== undefined) {
  8343. var stride = 0;
  8344. for (var i = 0; i < offsetLocations.length; i++) {
  8345. var ai = offsetLocations[i];
  8346. stride += ai.attributeSize * 4;
  8347. }
  8348. for (var i = 0; i < offsetLocations.length; i++) {
  8349. var ai = offsetLocations[i];
  8350. if (!this._vertexAttribArraysEnabled[ai.index]) {
  8351. this._gl.enableVertexAttribArray(ai.index);
  8352. this._vertexAttribArraysEnabled[ai.index] = true;
  8353. }
  8354. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  8355. this._gl.vertexAttribDivisor(ai.index, 1);
  8356. this._currentInstanceLocations.push(ai.index);
  8357. this._currentInstanceBuffers.push(instancesBuffer);
  8358. }
  8359. }
  8360. else {
  8361. for (var index = 0; index < 4; index++) {
  8362. var offsetLocation = offsetLocations[index];
  8363. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  8364. this._gl.enableVertexAttribArray(offsetLocation);
  8365. this._vertexAttribArraysEnabled[offsetLocation] = true;
  8366. }
  8367. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  8368. this._gl.vertexAttribDivisor(offsetLocation, 1);
  8369. this._currentInstanceLocations.push(offsetLocation);
  8370. this._currentInstanceBuffers.push(instancesBuffer);
  8371. }
  8372. }
  8373. };
  8374. Engine.prototype.applyStates = function () {
  8375. this._depthCullingState.apply(this._gl);
  8376. this._stencilState.apply(this._gl);
  8377. this._alphaState.apply(this._gl);
  8378. };
  8379. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  8380. // Apply states
  8381. this.applyStates();
  8382. this._drawCalls.addCount(1, false);
  8383. // Render
  8384. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  8385. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  8386. if (instancesCount) {
  8387. this._gl.drawElementsInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  8388. return;
  8389. }
  8390. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  8391. };
  8392. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  8393. // Apply states
  8394. this.applyStates();
  8395. this._drawCalls.addCount(1, false);
  8396. if (instancesCount) {
  8397. this._gl.drawArraysInstanced(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  8398. return;
  8399. }
  8400. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  8401. };
  8402. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  8403. // Apply states
  8404. this.applyStates();
  8405. this._drawCalls.addCount(1, false);
  8406. if (instancesCount) {
  8407. this._gl.drawArraysInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  8408. return;
  8409. }
  8410. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  8411. };
  8412. // Shaders
  8413. Engine.prototype._releaseEffect = function (effect) {
  8414. if (this._compiledEffects[effect._key]) {
  8415. delete this._compiledEffects[effect._key];
  8416. if (effect.getProgram()) {
  8417. this._gl.deleteProgram(effect.getProgram());
  8418. }
  8419. }
  8420. };
  8421. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  8422. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  8423. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  8424. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  8425. if (this._compiledEffects[name]) {
  8426. return this._compiledEffects[name];
  8427. }
  8428. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  8429. effect._key = name;
  8430. this._compiledEffects[name] = effect;
  8431. return effect;
  8432. };
  8433. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  8434. if (uniformsNames === void 0) { uniformsNames = []; }
  8435. if (samplers === void 0) { samplers = []; }
  8436. if (defines === void 0) { defines = ""; }
  8437. return this.createEffect({
  8438. vertex: "particles",
  8439. fragmentElement: fragmentName
  8440. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  8441. };
  8442. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  8443. context = context || this._gl;
  8444. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  8445. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  8446. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  8447. var shaderProgram = context.createProgram();
  8448. context.attachShader(shaderProgram, vertexShader);
  8449. context.attachShader(shaderProgram, fragmentShader);
  8450. context.linkProgram(shaderProgram);
  8451. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  8452. if (!linked) {
  8453. var error = context.getProgramInfoLog(shaderProgram);
  8454. if (error) {
  8455. throw new Error(error);
  8456. }
  8457. }
  8458. context.deleteShader(vertexShader);
  8459. context.deleteShader(fragmentShader);
  8460. return shaderProgram;
  8461. };
  8462. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  8463. var results = [];
  8464. for (var index = 0; index < uniformsNames.length; index++) {
  8465. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  8466. }
  8467. return results;
  8468. };
  8469. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  8470. var results = [];
  8471. for (var index = 0; index < attributesNames.length; index++) {
  8472. try {
  8473. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  8474. }
  8475. catch (e) {
  8476. results.push(-1);
  8477. }
  8478. }
  8479. return results;
  8480. };
  8481. Engine.prototype.enableEffect = function (effect) {
  8482. // Use program
  8483. this.setProgram(effect.getProgram());
  8484. this._currentEffect = effect;
  8485. if (effect.onBind) {
  8486. effect.onBind(effect);
  8487. }
  8488. };
  8489. Engine.prototype.setIntArray = function (uniform, array) {
  8490. if (!uniform)
  8491. return;
  8492. this._gl.uniform1iv(uniform, array);
  8493. };
  8494. Engine.prototype.setIntArray2 = function (uniform, array) {
  8495. if (!uniform || array.length % 2 !== 0)
  8496. return;
  8497. this._gl.uniform2iv(uniform, array);
  8498. };
  8499. Engine.prototype.setIntArray3 = function (uniform, array) {
  8500. if (!uniform || array.length % 3 !== 0)
  8501. return;
  8502. this._gl.uniform3iv(uniform, array);
  8503. };
  8504. Engine.prototype.setIntArray4 = function (uniform, array) {
  8505. if (!uniform || array.length % 4 !== 0)
  8506. return;
  8507. this._gl.uniform4iv(uniform, array);
  8508. };
  8509. Engine.prototype.setFloatArray = function (uniform, array) {
  8510. if (!uniform)
  8511. return;
  8512. this._gl.uniform1fv(uniform, array);
  8513. };
  8514. Engine.prototype.setFloatArray2 = function (uniform, array) {
  8515. if (!uniform || array.length % 2 !== 0)
  8516. return;
  8517. this._gl.uniform2fv(uniform, array);
  8518. };
  8519. Engine.prototype.setFloatArray3 = function (uniform, array) {
  8520. if (!uniform || array.length % 3 !== 0)
  8521. return;
  8522. this._gl.uniform3fv(uniform, array);
  8523. };
  8524. Engine.prototype.setFloatArray4 = function (uniform, array) {
  8525. if (!uniform || array.length % 4 !== 0)
  8526. return;
  8527. this._gl.uniform4fv(uniform, array);
  8528. };
  8529. Engine.prototype.setArray = function (uniform, array) {
  8530. if (!uniform)
  8531. return;
  8532. this._gl.uniform1fv(uniform, array);
  8533. };
  8534. Engine.prototype.setArray2 = function (uniform, array) {
  8535. if (!uniform || array.length % 2 !== 0)
  8536. return;
  8537. this._gl.uniform2fv(uniform, array);
  8538. };
  8539. Engine.prototype.setArray3 = function (uniform, array) {
  8540. if (!uniform || array.length % 3 !== 0)
  8541. return;
  8542. this._gl.uniform3fv(uniform, array);
  8543. };
  8544. Engine.prototype.setArray4 = function (uniform, array) {
  8545. if (!uniform || array.length % 4 !== 0)
  8546. return;
  8547. this._gl.uniform4fv(uniform, array);
  8548. };
  8549. Engine.prototype.setMatrices = function (uniform, matrices) {
  8550. if (!uniform)
  8551. return;
  8552. this._gl.uniformMatrix4fv(uniform, false, matrices);
  8553. };
  8554. Engine.prototype.setMatrix = function (uniform, matrix) {
  8555. if (!uniform)
  8556. return;
  8557. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  8558. };
  8559. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  8560. if (!uniform)
  8561. return;
  8562. this._gl.uniformMatrix3fv(uniform, false, matrix);
  8563. };
  8564. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  8565. if (!uniform)
  8566. return;
  8567. this._gl.uniformMatrix2fv(uniform, false, matrix);
  8568. };
  8569. Engine.prototype.setFloat = function (uniform, value) {
  8570. if (!uniform)
  8571. return;
  8572. this._gl.uniform1f(uniform, value);
  8573. };
  8574. Engine.prototype.setFloat2 = function (uniform, x, y) {
  8575. if (!uniform)
  8576. return;
  8577. this._gl.uniform2f(uniform, x, y);
  8578. };
  8579. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  8580. if (!uniform)
  8581. return;
  8582. this._gl.uniform3f(uniform, x, y, z);
  8583. };
  8584. Engine.prototype.setBool = function (uniform, bool) {
  8585. if (!uniform)
  8586. return;
  8587. this._gl.uniform1i(uniform, bool);
  8588. };
  8589. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  8590. if (!uniform)
  8591. return;
  8592. this._gl.uniform4f(uniform, x, y, z, w);
  8593. };
  8594. Engine.prototype.setColor3 = function (uniform, color3) {
  8595. if (!uniform)
  8596. return;
  8597. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  8598. };
  8599. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  8600. if (!uniform)
  8601. return;
  8602. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  8603. };
  8604. // States
  8605. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  8606. if (zOffset === void 0) { zOffset = 0; }
  8607. if (reverseSide === void 0) { reverseSide = false; }
  8608. // Culling
  8609. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  8610. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  8611. var cullFace = this.cullBackFaces ? showSide : hideSide;
  8612. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  8613. if (culling) {
  8614. this._depthCullingState.cullFace = cullFace;
  8615. this._depthCullingState.cull = true;
  8616. }
  8617. else {
  8618. this._depthCullingState.cull = false;
  8619. }
  8620. }
  8621. // Z offset
  8622. this._depthCullingState.zOffset = zOffset;
  8623. };
  8624. Engine.prototype.setDepthBuffer = function (enable) {
  8625. this._depthCullingState.depthTest = enable;
  8626. };
  8627. Engine.prototype.getDepthWrite = function () {
  8628. return this._depthCullingState.depthMask;
  8629. };
  8630. Engine.prototype.setDepthWrite = function (enable) {
  8631. this._depthCullingState.depthMask = enable;
  8632. };
  8633. Engine.prototype.setColorWrite = function (enable) {
  8634. this._gl.colorMask(enable, enable, enable, enable);
  8635. };
  8636. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  8637. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  8638. if (this._alphaMode === mode) {
  8639. return;
  8640. }
  8641. switch (mode) {
  8642. case Engine.ALPHA_DISABLE:
  8643. this._alphaState.alphaBlend = false;
  8644. break;
  8645. case Engine.ALPHA_PREMULTIPLIED:
  8646. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  8647. this._alphaState.alphaBlend = true;
  8648. break;
  8649. case Engine.ALPHA_COMBINE:
  8650. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  8651. this._alphaState.alphaBlend = true;
  8652. break;
  8653. case Engine.ALPHA_ONEONE:
  8654. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  8655. this._alphaState.alphaBlend = true;
  8656. break;
  8657. case Engine.ALPHA_ADD:
  8658. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  8659. this._alphaState.alphaBlend = true;
  8660. break;
  8661. case Engine.ALPHA_SUBTRACT:
  8662. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  8663. this._alphaState.alphaBlend = true;
  8664. break;
  8665. case Engine.ALPHA_MULTIPLY:
  8666. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  8667. this._alphaState.alphaBlend = true;
  8668. break;
  8669. case Engine.ALPHA_MAXIMIZED:
  8670. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  8671. this._alphaState.alphaBlend = true;
  8672. break;
  8673. }
  8674. if (!noDepthWriteChange) {
  8675. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  8676. }
  8677. this._alphaMode = mode;
  8678. };
  8679. Engine.prototype.getAlphaMode = function () {
  8680. return this._alphaMode;
  8681. };
  8682. Engine.prototype.setAlphaTesting = function (enable) {
  8683. this._alphaTest = enable;
  8684. };
  8685. Engine.prototype.getAlphaTesting = function () {
  8686. return !!this._alphaTest;
  8687. };
  8688. // Textures
  8689. Engine.prototype.wipeCaches = function () {
  8690. if (this.preventCacheWipeBetweenFrames) {
  8691. return;
  8692. }
  8693. this.resetTextureCache();
  8694. this._currentEffect = null;
  8695. this._stencilState.reset();
  8696. this._depthCullingState.reset();
  8697. this.setDepthFunctionToLessOrEqual();
  8698. this._alphaState.reset();
  8699. this._cachedVertexBuffers = null;
  8700. this._cachedIndexBuffer = null;
  8701. this._cachedEffectForVertexBuffers = null;
  8702. this._unBindVertexArrayObject();
  8703. this.bindIndexBuffer(null);
  8704. this.bindArrayBuffer(null);
  8705. };
  8706. /**
  8707. * Set the compressed texture format to use, based on the formats you have, and the formats
  8708. * supported by the hardware / browser.
  8709. *
  8710. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  8711. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  8712. * to API arguments needed to compressed textures. This puts the burden on the container
  8713. * generator to house the arcane code for determining these for current & future formats.
  8714. *
  8715. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  8716. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  8717. *
  8718. * Note: The result of this call is not taken into account when a texture is base64.
  8719. *
  8720. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  8721. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  8722. *
  8723. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  8724. * @returns The extension selected.
  8725. */
  8726. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  8727. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  8728. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  8729. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  8730. return this._textureFormatInUse = this._texturesSupported[i];
  8731. }
  8732. }
  8733. }
  8734. // actively set format to nothing, to allow this to be called more than once
  8735. // and possibly fail the 2nd time
  8736. return this._textureFormatInUse = null;
  8737. };
  8738. /**
  8739. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  8740. * @param {string} urlArg- This contains one of the following:
  8741. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  8742. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  8743. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  8744. *
  8745. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  8746. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  8747. * @param {Scene} scene- Needed for loading to the correct scene.
  8748. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  8749. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  8750. * @param {callback} onError- Optional callback to be called upon failure.
  8751. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  8752. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  8753. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  8754. *
  8755. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  8756. */
  8757. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  8758. var _this = this;
  8759. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  8760. if (onLoad === void 0) { onLoad = null; }
  8761. if (onError === void 0) { onError = null; }
  8762. if (buffer === void 0) { buffer = null; }
  8763. var texture = fallBack ? fallBack : this._gl.createTexture();
  8764. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  8765. var fromData = url.substr(0, 5) === "data:";
  8766. var isBase64 = fromData && url.indexOf("base64") !== -1;
  8767. // establish the file extension, if possible
  8768. var lastDot = url.lastIndexOf('.');
  8769. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  8770. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  8771. if (isDDS) {
  8772. BABYLON.Tools.Warn("DDS files deprecated since 3.0, use KTX files");
  8773. }
  8774. var isTGA = (extension === ".tga");
  8775. // determine if a ktx file should be substituted
  8776. var isKTX = false;
  8777. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  8778. url = url.substring(0, lastDot) + this._textureFormatInUse;
  8779. isKTX = true;
  8780. }
  8781. scene._addPendingData(texture);
  8782. texture.url = url;
  8783. texture.noMipmap = noMipmap;
  8784. texture.references = 1;
  8785. texture.samplingMode = samplingMode;
  8786. texture.onLoadedCallbacks = [];
  8787. if (onLoad) {
  8788. texture.onLoadedCallbacks.push(onLoad);
  8789. }
  8790. if (!fallBack)
  8791. this._loadedTexturesCache.push(texture);
  8792. var onerror = function () {
  8793. scene._removePendingData(texture);
  8794. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  8795. if (isKTX) {
  8796. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  8797. }
  8798. else if (onError) {
  8799. onError();
  8800. }
  8801. };
  8802. var callback;
  8803. // processing for non-image formats
  8804. if (isKTX || isTGA || isDDS) {
  8805. if (isKTX) {
  8806. callback = function (data) {
  8807. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 1);
  8808. prepareWebGLTexture(texture, _this._gl, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  8809. ktx.uploadLevels(_this._gl, !noMipmap);
  8810. }, samplingMode);
  8811. };
  8812. }
  8813. else if (isTGA) {
  8814. callback = function (arrayBuffer) {
  8815. var data = new Uint8Array(arrayBuffer);
  8816. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  8817. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  8818. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  8819. }, samplingMode);
  8820. };
  8821. }
  8822. else if (isDDS) {
  8823. callback = function (data) {
  8824. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  8825. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  8826. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  8827. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  8828. }, samplingMode);
  8829. };
  8830. }
  8831. if (!buffer) {
  8832. BABYLON.Tools.LoadFile(url, function (data) {
  8833. callback(data);
  8834. }, null, scene.database, true, onerror);
  8835. }
  8836. else {
  8837. callback(buffer);
  8838. }
  8839. // image format processing
  8840. }
  8841. else {
  8842. var onload = function (img) {
  8843. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  8844. var isPot = (img.width === potWidth && img.height === potHeight);
  8845. if (!isPot) {
  8846. _this._prepareWorkingCanvas();
  8847. _this._workingCanvas.width = potWidth;
  8848. _this._workingCanvas.height = potHeight;
  8849. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  8850. _this._workingContext.imageSmoothingEnabled = false;
  8851. _this._workingContext.mozImageSmoothingEnabled = false;
  8852. _this._workingContext.oImageSmoothingEnabled = false;
  8853. _this._workingContext.webkitImageSmoothingEnabled = false;
  8854. _this._workingContext.msImageSmoothingEnabled = false;
  8855. }
  8856. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  8857. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  8858. _this._workingContext.imageSmoothingEnabled = true;
  8859. _this._workingContext.mozImageSmoothingEnabled = true;
  8860. _this._workingContext.oImageSmoothingEnabled = true;
  8861. _this._workingContext.webkitImageSmoothingEnabled = true;
  8862. _this._workingContext.msImageSmoothingEnabled = true;
  8863. }
  8864. }
  8865. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? _this._gl.RGB : _this._gl.RGBA);
  8866. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  8867. }, samplingMode);
  8868. };
  8869. if (!fromData || isBase64)
  8870. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  8871. else if (buffer instanceof Array || typeof buffer === "string")
  8872. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  8873. else
  8874. onload(buffer);
  8875. }
  8876. return texture;
  8877. };
  8878. Engine.prototype._getInternalFormat = function (format) {
  8879. var internalFormat = this._gl.RGBA;
  8880. switch (format) {
  8881. case Engine.TEXTUREFORMAT_ALPHA:
  8882. internalFormat = this._gl.ALPHA;
  8883. break;
  8884. case Engine.TEXTUREFORMAT_LUMINANCE:
  8885. internalFormat = this._gl.LUMINANCE;
  8886. break;
  8887. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  8888. internalFormat = this._gl.LUMINANCE_ALPHA;
  8889. break;
  8890. case Engine.TEXTUREFORMAT_RGB:
  8891. internalFormat = this._gl.RGB;
  8892. break;
  8893. case Engine.TEXTUREFORMAT_RGBA:
  8894. internalFormat = this._gl.RGBA;
  8895. break;
  8896. }
  8897. return internalFormat;
  8898. };
  8899. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  8900. if (compression === void 0) { compression = null; }
  8901. var internalFormat = this._getInternalFormat(format);
  8902. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8903. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  8904. if (texture._width % 4 !== 0) {
  8905. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  8906. }
  8907. if (compression) {
  8908. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  8909. }
  8910. else {
  8911. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  8912. }
  8913. if (texture.generateMipMaps) {
  8914. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  8915. }
  8916. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8917. this.resetTextureCache();
  8918. texture.isReady = true;
  8919. };
  8920. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  8921. if (compression === void 0) { compression = null; }
  8922. var texture = this._gl.createTexture();
  8923. texture._baseWidth = width;
  8924. texture._baseHeight = height;
  8925. texture._width = width;
  8926. texture._height = height;
  8927. texture.references = 1;
  8928. this.updateRawTexture(texture, data, format, invertY, compression);
  8929. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8930. // Filters
  8931. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  8932. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  8933. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  8934. if (generateMipMaps) {
  8935. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  8936. }
  8937. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8938. texture.samplingMode = samplingMode;
  8939. this._loadedTexturesCache.push(texture);
  8940. return texture;
  8941. };
  8942. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  8943. var texture = this._gl.createTexture();
  8944. texture._baseWidth = width;
  8945. texture._baseHeight = height;
  8946. if (generateMipMaps) {
  8947. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  8948. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  8949. }
  8950. this.resetTextureCache();
  8951. texture._width = width;
  8952. texture._height = height;
  8953. texture.isReady = false;
  8954. texture.generateMipMaps = generateMipMaps;
  8955. texture.references = 1;
  8956. texture.samplingMode = samplingMode;
  8957. this.updateTextureSamplingMode(samplingMode, texture);
  8958. this._loadedTexturesCache.push(texture);
  8959. return texture;
  8960. };
  8961. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  8962. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  8963. if (texture.isCube) {
  8964. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  8965. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  8966. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  8967. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  8968. }
  8969. else {
  8970. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8971. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  8972. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  8973. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8974. }
  8975. texture.samplingMode = samplingMode;
  8976. };
  8977. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  8978. if (premulAlpha === void 0) { premulAlpha = false; }
  8979. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8980. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  8981. if (premulAlpha) {
  8982. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  8983. }
  8984. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  8985. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  8986. if (texture.generateMipMaps) {
  8987. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  8988. }
  8989. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8990. if (premulAlpha) {
  8991. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  8992. }
  8993. this.resetTextureCache();
  8994. texture.isReady = true;
  8995. };
  8996. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  8997. if (texture._isDisabled) {
  8998. return;
  8999. }
  9000. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9001. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  9002. try {
  9003. // Testing video texture support
  9004. if (this._videoTextureSupported === undefined) {
  9005. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  9006. if (this._gl.getError() !== 0) {
  9007. this._videoTextureSupported = false;
  9008. }
  9009. else {
  9010. this._videoTextureSupported = true;
  9011. }
  9012. }
  9013. // Copy video through the current working canvas if video texture is not supported
  9014. if (!this._videoTextureSupported) {
  9015. if (!texture._workingCanvas) {
  9016. texture._workingCanvas = document.createElement("canvas");
  9017. texture._workingContext = texture._workingCanvas.getContext("2d");
  9018. texture._workingCanvas.width = texture._width;
  9019. texture._workingCanvas.height = texture._height;
  9020. }
  9021. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  9022. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  9023. }
  9024. else {
  9025. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  9026. }
  9027. if (texture.generateMipMaps) {
  9028. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9029. }
  9030. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9031. this.resetTextureCache();
  9032. texture.isReady = true;
  9033. }
  9034. catch (ex) {
  9035. // Something unexpected
  9036. // Let's disable the texture
  9037. texture._isDisabled = true;
  9038. }
  9039. };
  9040. Engine.prototype.createRenderTargetTexture = function (size, options) {
  9041. // old version had a "generateMipMaps" arg instead of options.
  9042. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  9043. // in the same way, generateDepthBuffer is defaulted to true
  9044. var generateMipMaps = false;
  9045. var generateDepthBuffer = true;
  9046. var generateStencilBuffer = false;
  9047. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9048. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9049. if (options !== undefined) {
  9050. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  9051. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9052. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  9053. type = options.type === undefined ? type : options.type;
  9054. if (options.samplingMode !== undefined) {
  9055. samplingMode = options.samplingMode;
  9056. }
  9057. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  9058. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  9059. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9060. }
  9061. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  9062. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  9063. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9064. }
  9065. }
  9066. var gl = this._gl;
  9067. var texture = gl.createTexture();
  9068. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  9069. var width = size.width || size;
  9070. var height = size.height || size;
  9071. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9072. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  9073. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9074. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  9075. }
  9076. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  9077. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  9078. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9079. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9080. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  9081. // Create the framebuffer
  9082. var framebuffer = gl.createFramebuffer();
  9083. this.bindUnboundFramebuffer(framebuffer);
  9084. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  9085. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  9086. if (generateMipMaps) {
  9087. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9088. }
  9089. // Unbind
  9090. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9091. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9092. this.bindUnboundFramebuffer(null);
  9093. texture._framebuffer = framebuffer;
  9094. texture._baseWidth = width;
  9095. texture._baseHeight = height;
  9096. texture._width = width;
  9097. texture._height = height;
  9098. texture.isReady = true;
  9099. texture.samples = 1;
  9100. texture.generateMipMaps = generateMipMaps;
  9101. texture.references = 1;
  9102. texture.samplingMode = samplingMode;
  9103. texture.type = type;
  9104. texture._generateDepthBuffer = generateDepthBuffer;
  9105. texture._generateStencilBuffer = generateStencilBuffer;
  9106. this.resetTextureCache();
  9107. this._loadedTexturesCache.push(texture);
  9108. return texture;
  9109. };
  9110. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  9111. if (samples === void 0) { samples = 1; }
  9112. var depthStencilBuffer = null;
  9113. var gl = this._gl;
  9114. // Create the depth/stencil buffer
  9115. if (generateStencilBuffer) {
  9116. depthStencilBuffer = gl.createRenderbuffer();
  9117. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  9118. if (samples > 1) {
  9119. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_STENCIL, width, height);
  9120. }
  9121. else {
  9122. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  9123. }
  9124. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  9125. }
  9126. else if (generateDepthBuffer) {
  9127. depthStencilBuffer = gl.createRenderbuffer();
  9128. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  9129. if (samples > 1) {
  9130. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  9131. }
  9132. else {
  9133. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  9134. }
  9135. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  9136. }
  9137. return depthStencilBuffer;
  9138. };
  9139. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  9140. if (this.webGLVersion < 2) {
  9141. return 1;
  9142. }
  9143. if (texture.samples === samples) {
  9144. return samples;
  9145. }
  9146. var gl = this._gl;
  9147. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  9148. // Dispose previous render buffers
  9149. if (texture._depthStencilBuffer) {
  9150. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  9151. }
  9152. if (texture._MSAAFramebuffer) {
  9153. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  9154. }
  9155. if (texture._MSAARenderBuffer) {
  9156. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  9157. }
  9158. if (samples > 1) {
  9159. texture._MSAAFramebuffer = gl.createFramebuffer();
  9160. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  9161. var colorRenderbuffer = gl.createRenderbuffer();
  9162. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  9163. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.RGBA8, texture._width, texture._height);
  9164. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  9165. texture._MSAARenderBuffer = colorRenderbuffer;
  9166. }
  9167. else {
  9168. this.bindUnboundFramebuffer(texture._framebuffer);
  9169. }
  9170. texture.samples = samples;
  9171. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture._width, texture._height, samples);
  9172. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9173. this.bindUnboundFramebuffer(null);
  9174. return samples;
  9175. };
  9176. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  9177. var gl = this._gl;
  9178. var texture = gl.createTexture();
  9179. var generateMipMaps = true;
  9180. var generateDepthBuffer = true;
  9181. var generateStencilBuffer = false;
  9182. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9183. if (options !== undefined) {
  9184. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  9185. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9186. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  9187. if (options.samplingMode !== undefined) {
  9188. samplingMode = options.samplingMode;
  9189. }
  9190. }
  9191. texture.isCube = true;
  9192. texture.references = 1;
  9193. texture.generateMipMaps = generateMipMaps;
  9194. texture.references = 1;
  9195. texture.samples = 1;
  9196. texture.samplingMode = samplingMode;
  9197. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9198. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9199. for (var face = 0; face < 6; face++) {
  9200. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  9201. }
  9202. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  9203. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  9204. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9205. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9206. // Create the framebuffer
  9207. var framebuffer = gl.createFramebuffer();
  9208. this.bindUnboundFramebuffer(framebuffer);
  9209. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  9210. // Mipmaps
  9211. if (texture.generateMipMaps) {
  9212. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9213. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9214. }
  9215. // Unbind
  9216. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9217. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9218. this.bindUnboundFramebuffer(null);
  9219. texture._framebuffer = framebuffer;
  9220. texture._width = size;
  9221. texture._height = size;
  9222. texture.isReady = true;
  9223. this.resetTextureCache();
  9224. this._loadedTexturesCache.push(texture);
  9225. return texture;
  9226. };
  9227. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format) {
  9228. var _this = this;
  9229. if (onLoad === void 0) { onLoad = null; }
  9230. if (onError === void 0) { onError = null; }
  9231. var gl = this._gl;
  9232. var texture = gl.createTexture();
  9233. texture.isCube = true;
  9234. texture.url = rootUrl;
  9235. texture.references = 1;
  9236. texture.onLoadedCallbacks = [];
  9237. var isKTX = false;
  9238. var lastDot = rootUrl.lastIndexOf('.');
  9239. var extension = rootUrl.substring(lastDot).toLowerCase();
  9240. if (this._textureFormatInUse) {
  9241. extension = this._textureFormatInUse;
  9242. rootUrl = rootUrl.substring(0, lastDot) + this._textureFormatInUse;
  9243. isKTX = true;
  9244. }
  9245. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  9246. if (isDDS) {
  9247. BABYLON.Tools.Warn("DDS files deprecated since 3.0, use KTX files");
  9248. }
  9249. if (isKTX) {
  9250. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  9251. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 6);
  9252. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  9253. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9254. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  9255. ktx.uploadLevels(_this._gl, !noMipmap);
  9256. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9257. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  9258. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9259. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9260. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9261. _this.resetTextureCache();
  9262. texture._width = ktx.pixelWidth;
  9263. texture._height = ktx.pixelHeight;
  9264. texture.isReady = true;
  9265. }, null, null, true, onError);
  9266. }
  9267. else if (isDDS) {
  9268. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  9269. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  9270. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  9271. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9272. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  9273. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  9274. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  9275. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9276. }
  9277. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9278. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  9279. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9280. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9281. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9282. _this.resetTextureCache();
  9283. texture._width = info.width;
  9284. texture._height = info.height;
  9285. texture.isReady = true;
  9286. }, null, null, true, onError);
  9287. }
  9288. else {
  9289. cascadeLoad(rootUrl, scene, function (imgs) {
  9290. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  9291. var height = width;
  9292. _this._prepareWorkingCanvas();
  9293. _this._workingCanvas.width = width;
  9294. _this._workingCanvas.height = height;
  9295. var faces = [
  9296. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  9297. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  9298. ];
  9299. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9300. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  9301. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  9302. for (var index = 0; index < faces.length; index++) {
  9303. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  9304. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  9305. }
  9306. if (!noMipmap) {
  9307. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9308. }
  9309. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9310. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  9311. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9312. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9313. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9314. _this.resetTextureCache();
  9315. texture._width = width;
  9316. texture._height = height;
  9317. texture.isReady = true;
  9318. texture.onLoadedCallbacks.forEach(function (callback) {
  9319. callback();
  9320. });
  9321. if (onLoad) {
  9322. onLoad();
  9323. }
  9324. }, files, onError);
  9325. }
  9326. this._loadedTexturesCache.push(texture);
  9327. return texture;
  9328. };
  9329. Engine.prototype.updateTextureSize = function (texture, width, height) {
  9330. texture._width = width;
  9331. texture._height = height;
  9332. texture._size = width * height;
  9333. texture._baseWidth = width;
  9334. texture._baseHeight = height;
  9335. };
  9336. Engine.prototype.createRawCubeTexture = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError) {
  9337. var _this = this;
  9338. if (onLoad === void 0) { onLoad = null; }
  9339. if (onError === void 0) { onError = null; }
  9340. var gl = this._gl;
  9341. var texture = gl.createTexture();
  9342. scene._addPendingData(texture);
  9343. texture.isCube = true;
  9344. texture.references = 1;
  9345. texture.url = url;
  9346. var textureType = gl.UNSIGNED_BYTE;
  9347. if (type === Engine.TEXTURETYPE_FLOAT) {
  9348. textureType = gl.FLOAT;
  9349. }
  9350. var internalFormat = this._getInternalFormat(format);
  9351. var needConversion = false;
  9352. if (internalFormat === gl.RGB) {
  9353. internalFormat = gl.RGBA;
  9354. needConversion = true;
  9355. }
  9356. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  9357. var width = size;
  9358. var height = width;
  9359. var isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  9360. texture._width = width;
  9361. texture._height = height;
  9362. var onerror = function () {
  9363. scene._removePendingData(texture);
  9364. if (onError) {
  9365. onError();
  9366. }
  9367. };
  9368. var internalCallback = function (data) {
  9369. var rgbeDataArrays = callback(data);
  9370. var facesIndex = [
  9371. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  9372. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  9373. ];
  9374. width = texture._width;
  9375. height = texture._height;
  9376. isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  9377. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9378. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  9379. if (mipmmapGenerator) {
  9380. var arrayTemp = [];
  9381. // Data are known to be in +X +Y +Z -X -Y -Z
  9382. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  9383. arrayTemp.push(rgbeDataArrays[0]); // +X
  9384. arrayTemp.push(rgbeDataArrays[3]); // -X
  9385. arrayTemp.push(rgbeDataArrays[1]); // +Y
  9386. arrayTemp.push(rgbeDataArrays[4]); // -Y
  9387. arrayTemp.push(rgbeDataArrays[2]); // +Z
  9388. arrayTemp.push(rgbeDataArrays[5]); // -Z
  9389. var mipData = mipmmapGenerator(arrayTemp);
  9390. // mipData is order in +X -X +Y -Y +Z -Z
  9391. var mipFaces = [0, 2, 4, 1, 3, 5];
  9392. for (var level = 0; level < mipData.length; level++) {
  9393. var mipSize = width >> level;
  9394. for (var mipIndex in mipFaces) {
  9395. var mipFaceData = mipData[level][mipFaces[mipIndex]];
  9396. if (needConversion) {
  9397. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  9398. }
  9399. gl.texImage2D(facesIndex[mipIndex], level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  9400. }
  9401. }
  9402. }
  9403. else {
  9404. // Data are known to be in +X +Y +Z -X -Y -Z
  9405. for (var index = 0; index < facesIndex.length; index++) {
  9406. var faceData = rgbeDataArrays[index];
  9407. if (needConversion) {
  9408. faceData = _this._convertRGBtoRGBATextureData(faceData, width, height, type);
  9409. }
  9410. gl.texImage2D(facesIndex[index], 0, internalSizedFomat, width, height, 0, internalFormat, textureType, faceData);
  9411. }
  9412. if (!noMipmap && isPot) {
  9413. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9414. }
  9415. else {
  9416. noMipmap = true;
  9417. }
  9418. }
  9419. if (textureType === gl.FLOAT && !_this._caps.textureFloatLinearFiltering) {
  9420. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  9421. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  9422. }
  9423. else if (textureType === Engine.HALF_FLOAT_OES && !_this._caps.textureHalfFloatLinearFiltering) {
  9424. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  9425. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  9426. }
  9427. else {
  9428. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9429. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  9430. }
  9431. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9432. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9433. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9434. texture.isReady = true;
  9435. _this.resetTextureCache();
  9436. scene._removePendingData(texture);
  9437. if (onLoad) {
  9438. onLoad();
  9439. }
  9440. };
  9441. BABYLON.Tools.LoadFile(url, function (data) {
  9442. internalCallback(data);
  9443. }, onerror, scene.database, true);
  9444. return texture;
  9445. };
  9446. ;
  9447. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  9448. // Create new RGBA data container.
  9449. var rgbaData;
  9450. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  9451. rgbaData = new Float32Array(width * height * 4);
  9452. }
  9453. else {
  9454. rgbaData = new Uint32Array(width * height * 4);
  9455. }
  9456. // Convert each pixel.
  9457. for (var x = 0; x < width; x++) {
  9458. for (var y = 0; y < height; y++) {
  9459. var index = (y * width + x) * 3;
  9460. var newIndex = (y * width + x) * 4;
  9461. // Map Old Value to new value.
  9462. rgbaData[newIndex + 0] = rgbData[index + 0];
  9463. rgbaData[newIndex + 1] = rgbData[index + 1];
  9464. rgbaData[newIndex + 2] = rgbData[index + 2];
  9465. // Add fully opaque alpha channel.
  9466. rgbaData[newIndex + 3] = 1;
  9467. }
  9468. }
  9469. return rgbaData;
  9470. };
  9471. Engine.prototype._releaseTexture = function (texture) {
  9472. var gl = this._gl;
  9473. if (texture._framebuffer) {
  9474. gl.deleteFramebuffer(texture._framebuffer);
  9475. }
  9476. if (texture._depthStencilBuffer) {
  9477. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  9478. }
  9479. if (texture._MSAAFramebuffer) {
  9480. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  9481. }
  9482. if (texture._MSAARenderBuffer) {
  9483. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  9484. }
  9485. gl.deleteTexture(texture);
  9486. // Unbind channels
  9487. this.unbindAllTextures();
  9488. var index = this._loadedTexturesCache.indexOf(texture);
  9489. if (index !== -1) {
  9490. this._loadedTexturesCache.splice(index, 1);
  9491. }
  9492. };
  9493. Engine.prototype.setProgram = function (program) {
  9494. if (this._currentProgram !== program) {
  9495. this._gl.useProgram(program);
  9496. this._currentProgram = program;
  9497. }
  9498. };
  9499. Engine.prototype.bindSamplers = function (effect) {
  9500. this.setProgram(effect.getProgram());
  9501. var samplers = effect.getSamplers();
  9502. for (var index = 0; index < samplers.length; index++) {
  9503. var uniform = effect.getUniform(samplers[index]);
  9504. this._gl.uniform1i(uniform, index);
  9505. }
  9506. this._currentEffect = null;
  9507. };
  9508. Engine.prototype.activateTexture = function (texture) {
  9509. if (this._activeTexture !== texture) {
  9510. this._gl.activeTexture(texture);
  9511. this._activeTexture = texture;
  9512. }
  9513. };
  9514. Engine.prototype._bindTextureDirectly = function (target, texture) {
  9515. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  9516. this._gl.bindTexture(target, texture);
  9517. this._activeTexturesCache[this._activeTexture] = texture;
  9518. }
  9519. };
  9520. Engine.prototype._bindTexture = function (channel, texture) {
  9521. if (channel < 0) {
  9522. return;
  9523. }
  9524. this.activateTexture(this._gl.TEXTURE0 + channel);
  9525. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9526. };
  9527. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  9528. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  9529. };
  9530. Engine.prototype.unbindAllTextures = function () {
  9531. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  9532. this.activateTexture(this._gl["TEXTURE" + channel]);
  9533. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9534. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  9535. }
  9536. };
  9537. Engine.prototype.setTexture = function (channel, uniform, texture) {
  9538. if (channel < 0) {
  9539. return;
  9540. }
  9541. this._gl.uniform1i(uniform, channel);
  9542. this._setTexture(channel, texture);
  9543. };
  9544. Engine.prototype._setTexture = function (channel, texture) {
  9545. // Not ready?
  9546. if (!texture || !texture.isReady()) {
  9547. if (this._activeTexturesCache[channel] != null) {
  9548. this.activateTexture(this._gl["TEXTURE" + channel]);
  9549. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9550. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  9551. }
  9552. return;
  9553. }
  9554. // Video
  9555. var alreadyActivated = false;
  9556. if (texture.video) {
  9557. this.activateTexture(this._gl["TEXTURE" + channel]);
  9558. alreadyActivated = true;
  9559. texture.update();
  9560. }
  9561. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  9562. texture.delayLoad();
  9563. return;
  9564. }
  9565. var internalTexture = texture.getInternalTexture();
  9566. if (this._activeTexturesCache[channel] === internalTexture) {
  9567. return;
  9568. }
  9569. if (!alreadyActivated) {
  9570. this.activateTexture(this._gl["TEXTURE" + channel]);
  9571. }
  9572. if (internalTexture.isCube) {
  9573. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  9574. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  9575. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  9576. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  9577. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  9578. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  9579. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  9580. }
  9581. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  9582. }
  9583. else {
  9584. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  9585. if (internalTexture._cachedWrapU !== texture.wrapU) {
  9586. internalTexture._cachedWrapU = texture.wrapU;
  9587. switch (texture.wrapU) {
  9588. case BABYLON.Texture.WRAP_ADDRESSMODE:
  9589. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  9590. break;
  9591. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  9592. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  9593. break;
  9594. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  9595. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  9596. break;
  9597. }
  9598. }
  9599. if (internalTexture._cachedWrapV !== texture.wrapV) {
  9600. internalTexture._cachedWrapV = texture.wrapV;
  9601. switch (texture.wrapV) {
  9602. case BABYLON.Texture.WRAP_ADDRESSMODE:
  9603. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  9604. break;
  9605. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  9606. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  9607. break;
  9608. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  9609. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  9610. break;
  9611. }
  9612. }
  9613. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  9614. }
  9615. };
  9616. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  9617. if (channel < 0) {
  9618. return;
  9619. }
  9620. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  9621. this._textureUnits = new Int32Array(textures.length);
  9622. }
  9623. for (var i = 0; i < textures.length; i++) {
  9624. this._textureUnits[i] = channel + i;
  9625. }
  9626. this._gl.uniform1iv(uniform, this._textureUnits);
  9627. for (var index = 0; index < textures.length; index++) {
  9628. this._setTexture(channel + index, textures[index]);
  9629. }
  9630. };
  9631. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  9632. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  9633. var value = texture.anisotropicFilteringLevel;
  9634. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  9635. value = 1;
  9636. }
  9637. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  9638. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  9639. texture._cachedAnisotropicFilteringLevel = value;
  9640. }
  9641. };
  9642. Engine.prototype.readPixels = function (x, y, width, height) {
  9643. var data = new Uint8Array(height * width * 4);
  9644. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  9645. return data;
  9646. };
  9647. /**
  9648. * Add an externaly attached data from its key.
  9649. * This method call will fail and return false, if such key already exists.
  9650. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  9651. * @param key the unique key that identifies the data
  9652. * @param data the data object to associate to the key for this Engine instance
  9653. * @return true if no such key were already present and the data was added successfully, false otherwise
  9654. */
  9655. Engine.prototype.addExternalData = function (key, data) {
  9656. if (!this._externalData) {
  9657. this._externalData = new BABYLON.StringDictionary();
  9658. }
  9659. return this._externalData.add(key, data);
  9660. };
  9661. /**
  9662. * Get an externaly attached data from its key
  9663. * @param key the unique key that identifies the data
  9664. * @return the associated data, if present (can be null), or undefined if not present
  9665. */
  9666. Engine.prototype.getExternalData = function (key) {
  9667. if (!this._externalData) {
  9668. this._externalData = new BABYLON.StringDictionary();
  9669. }
  9670. return this._externalData.get(key);
  9671. };
  9672. /**
  9673. * Get an externaly attached data from its key, create it using a factory if it's not already present
  9674. * @param key the unique key that identifies the data
  9675. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  9676. * @return the associated data, can be null if the factory returned null.
  9677. */
  9678. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  9679. if (!this._externalData) {
  9680. this._externalData = new BABYLON.StringDictionary();
  9681. }
  9682. return this._externalData.getOrAddWithFactory(key, factory);
  9683. };
  9684. /**
  9685. * Remove an externaly attached data from the Engine instance
  9686. * @param key the unique key that identifies the data
  9687. * @return true if the data was successfully removed, false if it doesn't exist
  9688. */
  9689. Engine.prototype.removeExternalData = function (key) {
  9690. if (!this._externalData) {
  9691. this._externalData = new BABYLON.StringDictionary();
  9692. }
  9693. return this._externalData.remove(key);
  9694. };
  9695. Engine.prototype.releaseInternalTexture = function (texture) {
  9696. if (!texture) {
  9697. return;
  9698. }
  9699. texture.references--;
  9700. // Final reference ?
  9701. if (texture.references === 0) {
  9702. var texturesCache = this.getLoadedTexturesCache();
  9703. var index = texturesCache.indexOf(texture);
  9704. if (index > -1) {
  9705. texturesCache.splice(index, 1);
  9706. }
  9707. this._releaseTexture(texture);
  9708. }
  9709. };
  9710. Engine.prototype.unbindAllAttributes = function () {
  9711. if (this._mustWipeVertexAttributes) {
  9712. this._mustWipeVertexAttributes = false;
  9713. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  9714. this._gl.disableVertexAttribArray(i);
  9715. this._vertexAttribArraysEnabled[i] = false;
  9716. this._currentBufferPointers[i] = null;
  9717. }
  9718. return;
  9719. }
  9720. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  9721. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  9722. continue;
  9723. }
  9724. this._gl.disableVertexAttribArray(i);
  9725. this._vertexAttribArraysEnabled[i] = false;
  9726. this._currentBufferPointers[i] = null;
  9727. }
  9728. };
  9729. Engine.prototype.releaseEffects = function () {
  9730. for (var name in this._compiledEffects) {
  9731. this._gl.deleteProgram(this._compiledEffects[name]._program);
  9732. }
  9733. this._compiledEffects = {};
  9734. };
  9735. // Dispose
  9736. Engine.prototype.dispose = function () {
  9737. this.hideLoadingUI();
  9738. this.stopRenderLoop();
  9739. // Release scenes
  9740. while (this.scenes.length) {
  9741. this.scenes[0].dispose();
  9742. }
  9743. // Release audio engine
  9744. Engine.audioEngine.dispose();
  9745. // Release effects
  9746. this.releaseEffects();
  9747. // Unbind
  9748. this.unbindAllAttributes();
  9749. this._gl = null;
  9750. //WebVR
  9751. this.disableVR();
  9752. // Events
  9753. window.removeEventListener("blur", this._onBlur);
  9754. window.removeEventListener("focus", this._onFocus);
  9755. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  9756. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  9757. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  9758. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  9759. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  9760. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  9761. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  9762. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  9763. // Remove from Instances
  9764. var index = Engine.Instances.indexOf(this);
  9765. if (index >= 0) {
  9766. Engine.Instances.splice(index, 1);
  9767. }
  9768. };
  9769. // Loading screen
  9770. Engine.prototype.displayLoadingUI = function () {
  9771. this.loadingScreen.displayLoadingUI();
  9772. };
  9773. Engine.prototype.hideLoadingUI = function () {
  9774. this.loadingScreen.hideLoadingUI();
  9775. };
  9776. Object.defineProperty(Engine.prototype, "loadingScreen", {
  9777. get: function () {
  9778. if (!this._loadingScreen)
  9779. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  9780. return this._loadingScreen;
  9781. },
  9782. set: function (loadingScreen) {
  9783. this._loadingScreen = loadingScreen;
  9784. },
  9785. enumerable: true,
  9786. configurable: true
  9787. });
  9788. Object.defineProperty(Engine.prototype, "loadingUIText", {
  9789. set: function (text) {
  9790. this.loadingScreen.loadingUIText = text;
  9791. },
  9792. enumerable: true,
  9793. configurable: true
  9794. });
  9795. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  9796. set: function (color) {
  9797. this.loadingScreen.loadingUIBackgroundColor = color;
  9798. },
  9799. enumerable: true,
  9800. configurable: true
  9801. });
  9802. Engine.prototype.attachContextLostEvent = function (callback) {
  9803. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  9804. };
  9805. Engine.prototype.attachContextRestoredEvent = function (callback) {
  9806. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  9807. };
  9808. Engine.prototype.getVertexShaderSource = function (program) {
  9809. var shaders = this._gl.getAttachedShaders(program);
  9810. return this._gl.getShaderSource(shaders[0]);
  9811. };
  9812. Engine.prototype.getFragmentShaderSource = function (program) {
  9813. var shaders = this._gl.getAttachedShaders(program);
  9814. return this._gl.getShaderSource(shaders[1]);
  9815. };
  9816. // FPS
  9817. Engine.prototype.getFps = function () {
  9818. return this.fps;
  9819. };
  9820. Engine.prototype.getDeltaTime = function () {
  9821. return this.deltaTime;
  9822. };
  9823. Engine.prototype._measureFps = function () {
  9824. this.previousFramesDuration.push(BABYLON.Tools.Now);
  9825. var length = this.previousFramesDuration.length;
  9826. if (length >= 2) {
  9827. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  9828. }
  9829. if (length >= this.fpsRange) {
  9830. if (length > this.fpsRange) {
  9831. this.previousFramesDuration.splice(0, 1);
  9832. length = this.previousFramesDuration.length;
  9833. }
  9834. var sum = 0;
  9835. for (var id = 0; id < length - 1; id++) {
  9836. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  9837. }
  9838. this.fps = 1000.0 / (sum / (length - 1));
  9839. }
  9840. };
  9841. Engine.prototype._canRenderToFloatFramebuffer = function () {
  9842. if (this._webGLVersion > 1) {
  9843. return this._caps.colorBufferFloat;
  9844. }
  9845. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_FLOAT);
  9846. };
  9847. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  9848. if (this._webGLVersion > 1) {
  9849. return this._caps.colorBufferFloat;
  9850. }
  9851. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  9852. };
  9853. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  9854. Engine.prototype._canRenderToFramebuffer = function (type) {
  9855. var gl = this._gl;
  9856. //clear existing errors
  9857. while (gl.getError() !== gl.NO_ERROR) { }
  9858. var successful = true;
  9859. var texture = gl.createTexture();
  9860. gl.bindTexture(gl.TEXTURE_2D, texture);
  9861. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  9862. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  9863. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  9864. var fb = gl.createFramebuffer();
  9865. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  9866. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  9867. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  9868. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  9869. successful = successful && (gl.getError() === gl.NO_ERROR);
  9870. //try render by clearing frame buffer's color buffer
  9871. if (successful) {
  9872. gl.clear(gl.COLOR_BUFFER_BIT);
  9873. successful = successful && (gl.getError() === gl.NO_ERROR);
  9874. }
  9875. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  9876. if (successful) {
  9877. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  9878. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  9879. var readFormat = gl.RGBA;
  9880. var readType = gl.UNSIGNED_BYTE;
  9881. var buffer = new Uint8Array(4);
  9882. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  9883. successful = successful && (gl.getError() === gl.NO_ERROR);
  9884. }
  9885. //clean up
  9886. gl.deleteTexture(texture);
  9887. gl.deleteFramebuffer(fb);
  9888. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  9889. //clear accumulated errors
  9890. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  9891. return successful;
  9892. };
  9893. Engine.prototype._getWebGLTextureType = function (type) {
  9894. if (type === Engine.TEXTURETYPE_FLOAT) {
  9895. return this._gl.FLOAT;
  9896. }
  9897. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  9898. // Add Half Float Constant.
  9899. return Engine.HALF_FLOAT_OES;
  9900. }
  9901. return this._gl.UNSIGNED_BYTE;
  9902. };
  9903. ;
  9904. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  9905. if (this._webGLVersion === 1) {
  9906. return this._gl.RGBA;
  9907. }
  9908. if (type === Engine.TEXTURETYPE_FLOAT) {
  9909. return Engine.RGBA32F;
  9910. }
  9911. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  9912. return Engine.RGBA16F;
  9913. }
  9914. return this._gl.RGBA;
  9915. };
  9916. ;
  9917. // Statics
  9918. Engine.isSupported = function () {
  9919. try {
  9920. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  9921. if (navigator.isCocoonJS) {
  9922. return true;
  9923. }
  9924. var tempcanvas = document.createElement("canvas");
  9925. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  9926. return gl != null && !!window.WebGLRenderingContext;
  9927. }
  9928. catch (e) {
  9929. return false;
  9930. }
  9931. };
  9932. return Engine;
  9933. }());
  9934. Engine.Instances = new Array();
  9935. // Const statics
  9936. Engine._ALPHA_DISABLE = 0;
  9937. Engine._ALPHA_ADD = 1;
  9938. Engine._ALPHA_COMBINE = 2;
  9939. Engine._ALPHA_SUBTRACT = 3;
  9940. Engine._ALPHA_MULTIPLY = 4;
  9941. Engine._ALPHA_MAXIMIZED = 5;
  9942. Engine._ALPHA_ONEONE = 6;
  9943. Engine._ALPHA_PREMULTIPLIED = 7;
  9944. Engine._DELAYLOADSTATE_NONE = 0;
  9945. Engine._DELAYLOADSTATE_LOADED = 1;
  9946. Engine._DELAYLOADSTATE_LOADING = 2;
  9947. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  9948. Engine._TEXTUREFORMAT_ALPHA = 0;
  9949. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  9950. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  9951. Engine._TEXTUREFORMAT_RGB = 4;
  9952. Engine._TEXTUREFORMAT_RGBA = 5;
  9953. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  9954. Engine._TEXTURETYPE_FLOAT = 1;
  9955. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  9956. // Depht or Stencil test Constants.
  9957. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  9958. 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.
  9959. 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.
  9960. 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.
  9961. 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.
  9962. 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.
  9963. 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.
  9964. 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.
  9965. Engine.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  9966. Engine.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  9967. Engine.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  9968. // Stencil Actions Constants.
  9969. Engine._KEEP = 0x1E00;
  9970. Engine._REPLACE = 0x1E01;
  9971. Engine._INCR = 0x1E02;
  9972. Engine._DECR = 0x1E03;
  9973. Engine._INVERT = 0x150A;
  9974. Engine._INCR_WRAP = 0x8507;
  9975. Engine._DECR_WRAP = 0x8508;
  9976. // Updatable statics so stick with vars here
  9977. Engine.CollisionsEpsilon = 0.001;
  9978. Engine.CodeRepository = "src/";
  9979. Engine.ShadersRepository = "src/Shaders/";
  9980. BABYLON.Engine = Engine;
  9981. })(BABYLON || (BABYLON = {}));
  9982. //# sourceMappingURL=babylon.engine.js.map
  9983. /// <reference path="Tools\babylon.decorators.ts" />
  9984. var BABYLON;
  9985. (function (BABYLON) {
  9986. /**
  9987. * Node is the basic class for all scene objects (Mesh, Light Camera).
  9988. */
  9989. var Node = (function () {
  9990. /**
  9991. * @constructor
  9992. * @param {string} name - the name and id to be given to this node
  9993. * @param {BABYLON.Scene} the scene this node will be added to
  9994. */
  9995. function Node(name, scene) {
  9996. this.state = "";
  9997. this.metadata = null;
  9998. this.doNotSerialize = false;
  9999. this.animations = new Array();
  10000. this._ranges = {};
  10001. this._childrenFlag = -1;
  10002. this._isEnabled = true;
  10003. this._isReady = true;
  10004. this._currentRenderId = -1;
  10005. this._parentRenderId = -1;
  10006. /**
  10007. * An event triggered when the mesh is disposed.
  10008. * @type {BABYLON.Observable}
  10009. */
  10010. this.onDisposeObservable = new BABYLON.Observable();
  10011. this.name = name;
  10012. this.id = name;
  10013. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  10014. this._initCache();
  10015. }
  10016. Object.defineProperty(Node.prototype, "parent", {
  10017. get: function () {
  10018. return this._parentNode;
  10019. },
  10020. set: function (parent) {
  10021. if (this._parentNode === parent) {
  10022. return;
  10023. }
  10024. if (this._parentNode) {
  10025. var index = this._parentNode._children.indexOf(this);
  10026. if (index !== -1) {
  10027. this._parentNode._children.splice(index, 1);
  10028. }
  10029. }
  10030. this._parentNode = parent;
  10031. if (this._parentNode) {
  10032. if (!this._parentNode._children) {
  10033. this._parentNode._children = new Array();
  10034. }
  10035. this._parentNode._children.push(this);
  10036. }
  10037. },
  10038. enumerable: true,
  10039. configurable: true
  10040. });
  10041. Node.prototype.getClassName = function () {
  10042. return "Node";
  10043. };
  10044. Object.defineProperty(Node.prototype, "onDispose", {
  10045. set: function (callback) {
  10046. if (this._onDisposeObserver) {
  10047. this.onDisposeObservable.remove(this._onDisposeObserver);
  10048. }
  10049. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  10050. },
  10051. enumerable: true,
  10052. configurable: true
  10053. });
  10054. Node.prototype.getScene = function () {
  10055. return this._scene;
  10056. };
  10057. Node.prototype.getEngine = function () {
  10058. return this._scene.getEngine();
  10059. };
  10060. // override it in derived class
  10061. Node.prototype.getWorldMatrix = function () {
  10062. return BABYLON.Matrix.Identity();
  10063. };
  10064. // override it in derived class if you add new variables to the cache
  10065. // and call the parent class method
  10066. Node.prototype._initCache = function () {
  10067. this._cache = {};
  10068. this._cache.parent = undefined;
  10069. };
  10070. Node.prototype.updateCache = function (force) {
  10071. if (!force && this.isSynchronized())
  10072. return;
  10073. this._cache.parent = this.parent;
  10074. this._updateCache();
  10075. };
  10076. // override it in derived class if you add new variables to the cache
  10077. // and call the parent class method if !ignoreParentClass
  10078. Node.prototype._updateCache = function (ignoreParentClass) {
  10079. };
  10080. // override it in derived class if you add new variables to the cache
  10081. Node.prototype._isSynchronized = function () {
  10082. return true;
  10083. };
  10084. Node.prototype._markSyncedWithParent = function () {
  10085. this._parentRenderId = this.parent._currentRenderId;
  10086. };
  10087. Node.prototype.isSynchronizedWithParent = function () {
  10088. if (!this.parent) {
  10089. return true;
  10090. }
  10091. if (this._parentRenderId !== this.parent._currentRenderId) {
  10092. return false;
  10093. }
  10094. return this.parent.isSynchronized();
  10095. };
  10096. Node.prototype.isSynchronized = function (updateCache) {
  10097. var check = this.hasNewParent();
  10098. check = check || !this.isSynchronizedWithParent();
  10099. check = check || !this._isSynchronized();
  10100. if (updateCache)
  10101. this.updateCache(true);
  10102. return !check;
  10103. };
  10104. Node.prototype.hasNewParent = function (update) {
  10105. if (this._cache.parent === this.parent)
  10106. return false;
  10107. if (update)
  10108. this._cache.parent = this.parent;
  10109. return true;
  10110. };
  10111. /**
  10112. * Is this node ready to be used/rendered
  10113. * @return {boolean} is it ready
  10114. */
  10115. Node.prototype.isReady = function () {
  10116. return this._isReady;
  10117. };
  10118. /**
  10119. * Is this node enabled.
  10120. * If the node has a parent and is enabled, the parent will be inspected as well.
  10121. * @return {boolean} whether this node (and its parent) is enabled.
  10122. * @see setEnabled
  10123. */
  10124. Node.prototype.isEnabled = function () {
  10125. if (!this._isEnabled) {
  10126. return false;
  10127. }
  10128. if (this.parent) {
  10129. return this.parent.isEnabled();
  10130. }
  10131. return true;
  10132. };
  10133. /**
  10134. * Set the enabled state of this node.
  10135. * @param {boolean} value - the new enabled state
  10136. * @see isEnabled
  10137. */
  10138. Node.prototype.setEnabled = function (value) {
  10139. this._isEnabled = value;
  10140. };
  10141. /**
  10142. * Is this node a descendant of the given node.
  10143. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  10144. * @param {BABYLON.Node} ancestor - The parent node to inspect
  10145. * @see parent
  10146. */
  10147. Node.prototype.isDescendantOf = function (ancestor) {
  10148. if (this.parent) {
  10149. if (this.parent === ancestor) {
  10150. return true;
  10151. }
  10152. return this.parent.isDescendantOf(ancestor);
  10153. }
  10154. return false;
  10155. };
  10156. /**
  10157. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  10158. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  10159. * @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.
  10160. * @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.
  10161. */
  10162. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  10163. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  10164. if (!this._children) {
  10165. return;
  10166. }
  10167. for (var index = 0; index < this._children.length; index++) {
  10168. var item = this._children[index];
  10169. if (!predicate || predicate(item)) {
  10170. results.push(item);
  10171. }
  10172. if (!directDescendantsOnly) {
  10173. item._getDescendants(results, false, predicate);
  10174. }
  10175. }
  10176. };
  10177. /**
  10178. * Will return all nodes that have this node as ascendant.
  10179. * @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.
  10180. * @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.
  10181. * @return {BABYLON.Node[]} all children nodes of all types.
  10182. */
  10183. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  10184. var results = [];
  10185. this._getDescendants(results, directDescendantsOnly, predicate);
  10186. return results;
  10187. };
  10188. /**
  10189. * Get all child-meshes of this node.
  10190. */
  10191. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  10192. var results = [];
  10193. this._getDescendants(results, directDecendantsOnly, function (node) {
  10194. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  10195. });
  10196. return results;
  10197. };
  10198. /**
  10199. * Get all direct children of this node.
  10200. */
  10201. Node.prototype.getChildren = function (predicate) {
  10202. return this.getDescendants(true, predicate);
  10203. };
  10204. Node.prototype._setReady = function (state) {
  10205. if (state === this._isReady) {
  10206. return;
  10207. }
  10208. if (!state) {
  10209. this._isReady = false;
  10210. return;
  10211. }
  10212. this._isReady = true;
  10213. if (this.onReady) {
  10214. this.onReady(this);
  10215. }
  10216. };
  10217. Node.prototype.getAnimationByName = function (name) {
  10218. for (var i = 0; i < this.animations.length; i++) {
  10219. var animation = this.animations[i];
  10220. if (animation.name === name) {
  10221. return animation;
  10222. }
  10223. }
  10224. return null;
  10225. };
  10226. Node.prototype.createAnimationRange = function (name, from, to) {
  10227. // check name not already in use
  10228. if (!this._ranges[name]) {
  10229. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  10230. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  10231. if (this.animations[i]) {
  10232. this.animations[i].createRange(name, from, to);
  10233. }
  10234. }
  10235. }
  10236. };
  10237. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  10238. if (deleteFrames === void 0) { deleteFrames = true; }
  10239. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  10240. if (this.animations[i]) {
  10241. this.animations[i].deleteRange(name, deleteFrames);
  10242. }
  10243. }
  10244. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  10245. };
  10246. Node.prototype.getAnimationRange = function (name) {
  10247. return this._ranges[name];
  10248. };
  10249. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  10250. var range = this.getAnimationRange(name);
  10251. if (!range) {
  10252. return null;
  10253. }
  10254. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  10255. };
  10256. Node.prototype.serializeAnimationRanges = function () {
  10257. var serializationRanges = [];
  10258. for (var name in this._ranges) {
  10259. var range = {};
  10260. range.name = name;
  10261. range.from = this._ranges[name].from;
  10262. range.to = this._ranges[name].to;
  10263. serializationRanges.push(range);
  10264. }
  10265. return serializationRanges;
  10266. };
  10267. Node.prototype.dispose = function () {
  10268. this.parent = null;
  10269. // Callback
  10270. this.onDisposeObservable.notifyObservers(this);
  10271. this.onDisposeObservable.clear();
  10272. };
  10273. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  10274. if (parsedNode.ranges) {
  10275. for (var index = 0; index < parsedNode.ranges.length; index++) {
  10276. var data = parsedNode.ranges[index];
  10277. node.createAnimationRange(data.name, data.from, data.to);
  10278. }
  10279. }
  10280. };
  10281. return Node;
  10282. }());
  10283. __decorate([
  10284. BABYLON.serialize()
  10285. ], Node.prototype, "name", void 0);
  10286. __decorate([
  10287. BABYLON.serialize()
  10288. ], Node.prototype, "id", void 0);
  10289. __decorate([
  10290. BABYLON.serialize()
  10291. ], Node.prototype, "uniqueId", void 0);
  10292. __decorate([
  10293. BABYLON.serialize()
  10294. ], Node.prototype, "state", void 0);
  10295. __decorate([
  10296. BABYLON.serialize()
  10297. ], Node.prototype, "metadata", void 0);
  10298. BABYLON.Node = Node;
  10299. })(BABYLON || (BABYLON = {}));
  10300. //# sourceMappingURL=babylon.node.js.map
  10301. var BABYLON;
  10302. (function (BABYLON) {
  10303. var BoundingSphere = (function () {
  10304. function BoundingSphere(minimum, maximum) {
  10305. this.minimum = minimum;
  10306. this.maximum = maximum;
  10307. this._tempRadiusVector = BABYLON.Vector3.Zero();
  10308. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  10309. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  10310. this.radius = distance * 0.5;
  10311. this.centerWorld = BABYLON.Vector3.Zero();
  10312. this._update(BABYLON.Matrix.Identity());
  10313. }
  10314. // Methods
  10315. BoundingSphere.prototype._update = function (world) {
  10316. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  10317. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  10318. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  10319. };
  10320. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  10321. for (var i = 0; i < 6; i++) {
  10322. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  10323. return false;
  10324. }
  10325. return true;
  10326. };
  10327. BoundingSphere.prototype.intersectsPoint = function (point) {
  10328. var x = this.centerWorld.x - point.x;
  10329. var y = this.centerWorld.y - point.y;
  10330. var z = this.centerWorld.z - point.z;
  10331. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  10332. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  10333. return false;
  10334. return true;
  10335. };
  10336. // Statics
  10337. BoundingSphere.Intersects = function (sphere0, sphere1) {
  10338. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  10339. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  10340. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  10341. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  10342. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  10343. return false;
  10344. return true;
  10345. };
  10346. return BoundingSphere;
  10347. }());
  10348. BABYLON.BoundingSphere = BoundingSphere;
  10349. })(BABYLON || (BABYLON = {}));
  10350. //# sourceMappingURL=babylon.boundingSphere.js.map
  10351. var BABYLON;
  10352. (function (BABYLON) {
  10353. var BoundingBox = (function () {
  10354. function BoundingBox(minimum, maximum) {
  10355. this.minimum = minimum;
  10356. this.maximum = maximum;
  10357. this.vectors = new Array();
  10358. this.vectorsWorld = new Array();
  10359. // Bounding vectors
  10360. this.vectors.push(this.minimum.clone());
  10361. this.vectors.push(this.maximum.clone());
  10362. this.vectors.push(this.minimum.clone());
  10363. this.vectors[2].x = this.maximum.x;
  10364. this.vectors.push(this.minimum.clone());
  10365. this.vectors[3].y = this.maximum.y;
  10366. this.vectors.push(this.minimum.clone());
  10367. this.vectors[4].z = this.maximum.z;
  10368. this.vectors.push(this.maximum.clone());
  10369. this.vectors[5].z = this.minimum.z;
  10370. this.vectors.push(this.maximum.clone());
  10371. this.vectors[6].x = this.minimum.x;
  10372. this.vectors.push(this.maximum.clone());
  10373. this.vectors[7].y = this.minimum.y;
  10374. // OBB
  10375. this.center = this.maximum.add(this.minimum).scale(0.5);
  10376. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  10377. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  10378. // World
  10379. for (var index = 0; index < this.vectors.length; index++) {
  10380. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  10381. }
  10382. this.minimumWorld = BABYLON.Vector3.Zero();
  10383. this.maximumWorld = BABYLON.Vector3.Zero();
  10384. this.centerWorld = BABYLON.Vector3.Zero();
  10385. this.extendSizeWorld = BABYLON.Vector3.Zero();
  10386. this._update(BABYLON.Matrix.Identity());
  10387. }
  10388. // Methods
  10389. BoundingBox.prototype.getWorldMatrix = function () {
  10390. return this._worldMatrix;
  10391. };
  10392. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  10393. this._worldMatrix.copyFrom(matrix);
  10394. return this;
  10395. };
  10396. BoundingBox.prototype._update = function (world) {
  10397. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  10398. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  10399. for (var index = 0; index < this.vectors.length; index++) {
  10400. var v = this.vectorsWorld[index];
  10401. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  10402. if (v.x < this.minimumWorld.x)
  10403. this.minimumWorld.x = v.x;
  10404. if (v.y < this.minimumWorld.y)
  10405. this.minimumWorld.y = v.y;
  10406. if (v.z < this.minimumWorld.z)
  10407. this.minimumWorld.z = v.z;
  10408. if (v.x > this.maximumWorld.x)
  10409. this.maximumWorld.x = v.x;
  10410. if (v.y > this.maximumWorld.y)
  10411. this.maximumWorld.y = v.y;
  10412. if (v.z > this.maximumWorld.z)
  10413. this.maximumWorld.z = v.z;
  10414. }
  10415. // Extend
  10416. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  10417. this.extendSizeWorld.scaleInPlace(0.5);
  10418. // OBB
  10419. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  10420. this.centerWorld.scaleInPlace(0.5);
  10421. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  10422. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  10423. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  10424. this._worldMatrix = world;
  10425. };
  10426. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  10427. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  10428. };
  10429. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  10430. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  10431. };
  10432. BoundingBox.prototype.intersectsPoint = function (point) {
  10433. var delta = -BABYLON.Epsilon;
  10434. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  10435. return false;
  10436. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  10437. return false;
  10438. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  10439. return false;
  10440. return true;
  10441. };
  10442. BoundingBox.prototype.intersectsSphere = function (sphere) {
  10443. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  10444. };
  10445. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  10446. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  10447. return false;
  10448. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  10449. return false;
  10450. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  10451. return false;
  10452. return true;
  10453. };
  10454. // Statics
  10455. BoundingBox.Intersects = function (box0, box1) {
  10456. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  10457. return false;
  10458. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  10459. return false;
  10460. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  10461. return false;
  10462. return true;
  10463. };
  10464. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  10465. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  10466. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  10467. return (num <= (sphereRadius * sphereRadius));
  10468. };
  10469. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  10470. for (var p = 0; p < 6; p++) {
  10471. for (var i = 0; i < 8; i++) {
  10472. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  10473. return false;
  10474. }
  10475. }
  10476. }
  10477. return true;
  10478. };
  10479. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  10480. for (var p = 0; p < 6; p++) {
  10481. var inCount = 8;
  10482. for (var i = 0; i < 8; i++) {
  10483. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  10484. --inCount;
  10485. }
  10486. else {
  10487. break;
  10488. }
  10489. }
  10490. if (inCount === 0)
  10491. return false;
  10492. }
  10493. return true;
  10494. };
  10495. return BoundingBox;
  10496. }());
  10497. BABYLON.BoundingBox = BoundingBox;
  10498. })(BABYLON || (BABYLON = {}));
  10499. //# sourceMappingURL=babylon.boundingBox.js.map
  10500. var BABYLON;
  10501. (function (BABYLON) {
  10502. var computeBoxExtents = function (axis, box) {
  10503. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  10504. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  10505. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  10506. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  10507. var r = r0 + r1 + r2;
  10508. return {
  10509. min: p - r,
  10510. max: p + r
  10511. };
  10512. };
  10513. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  10514. var axisOverlap = function (axis, box0, box1) {
  10515. var result0 = computeBoxExtents(axis, box0);
  10516. var result1 = computeBoxExtents(axis, box1);
  10517. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  10518. };
  10519. var BoundingInfo = (function () {
  10520. function BoundingInfo(minimum, maximum) {
  10521. this.minimum = minimum;
  10522. this.maximum = maximum;
  10523. this._isLocked = false;
  10524. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  10525. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  10526. }
  10527. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  10528. get: function () {
  10529. return this._isLocked;
  10530. },
  10531. set: function (value) {
  10532. this._isLocked = value;
  10533. },
  10534. enumerable: true,
  10535. configurable: true
  10536. });
  10537. // Methods
  10538. BoundingInfo.prototype.update = function (world) {
  10539. if (this._isLocked) {
  10540. return;
  10541. }
  10542. this.boundingBox._update(world);
  10543. this.boundingSphere._update(world);
  10544. };
  10545. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  10546. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  10547. return false;
  10548. return this.boundingBox.isInFrustum(frustumPlanes);
  10549. };
  10550. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  10551. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  10552. };
  10553. BoundingInfo.prototype._checkCollision = function (collider) {
  10554. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  10555. };
  10556. BoundingInfo.prototype.intersectsPoint = function (point) {
  10557. if (!this.boundingSphere.centerWorld) {
  10558. return false;
  10559. }
  10560. if (!this.boundingSphere.intersectsPoint(point)) {
  10561. return false;
  10562. }
  10563. if (!this.boundingBox.intersectsPoint(point)) {
  10564. return false;
  10565. }
  10566. return true;
  10567. };
  10568. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  10569. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  10570. return false;
  10571. }
  10572. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  10573. return false;
  10574. }
  10575. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  10576. return false;
  10577. }
  10578. if (!precise) {
  10579. return true;
  10580. }
  10581. var box0 = this.boundingBox;
  10582. var box1 = boundingInfo.boundingBox;
  10583. if (!axisOverlap(box0.directions[0], box0, box1))
  10584. return false;
  10585. if (!axisOverlap(box0.directions[1], box0, box1))
  10586. return false;
  10587. if (!axisOverlap(box0.directions[2], box0, box1))
  10588. return false;
  10589. if (!axisOverlap(box1.directions[0], box0, box1))
  10590. return false;
  10591. if (!axisOverlap(box1.directions[1], box0, box1))
  10592. return false;
  10593. if (!axisOverlap(box1.directions[2], box0, box1))
  10594. return false;
  10595. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  10596. return false;
  10597. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  10598. return false;
  10599. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  10600. return false;
  10601. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  10602. return false;
  10603. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  10604. return false;
  10605. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  10606. return false;
  10607. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  10608. return false;
  10609. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  10610. return false;
  10611. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  10612. return false;
  10613. return true;
  10614. };
  10615. return BoundingInfo;
  10616. }());
  10617. BABYLON.BoundingInfo = BoundingInfo;
  10618. })(BABYLON || (BABYLON = {}));
  10619. //# sourceMappingURL=babylon.boundingInfo.js.map
  10620. var BABYLON;
  10621. (function (BABYLON) {
  10622. var AbstractMesh = (function (_super) {
  10623. __extends(AbstractMesh, _super);
  10624. // Constructor
  10625. function AbstractMesh(name, scene) {
  10626. var _this = _super.call(this, name, scene) || this;
  10627. _this._facetNb = 0; // facet number
  10628. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  10629. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  10630. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  10631. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  10632. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  10633. _this._subDiv = {
  10634. max: 1,
  10635. X: 1,
  10636. Y: 1,
  10637. Z: 1
  10638. };
  10639. // Events
  10640. /**
  10641. * An event triggered when this mesh collides with another one
  10642. * @type {BABYLON.Observable}
  10643. */
  10644. _this.onCollideObservable = new BABYLON.Observable();
  10645. /**
  10646. * An event triggered when the collision's position changes
  10647. * @type {BABYLON.Observable}
  10648. */
  10649. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  10650. /**
  10651. * An event triggered after the world matrix is updated
  10652. * @type {BABYLON.Observable}
  10653. */
  10654. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  10655. // Properties
  10656. _this.definedFacingForward = true; // orientation for POV movement & rotation
  10657. _this.position = new BABYLON.Vector3(0.0, 0.0, 0.0);
  10658. _this._rotation = new BABYLON.Vector3(0.0, 0.0, 0.0);
  10659. _this._scaling = new BABYLON.Vector3(1.0, 1.0, 1.0);
  10660. _this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  10661. _this.visibility = 1.0;
  10662. _this.alphaIndex = Number.MAX_VALUE;
  10663. _this.infiniteDistance = false;
  10664. _this.isVisible = true;
  10665. _this.isPickable = true;
  10666. _this.showBoundingBox = false;
  10667. _this.showSubMeshesBoundingBox = false;
  10668. _this.isBlocker = false;
  10669. _this.renderingGroupId = 0;
  10670. _this._receiveShadows = false;
  10671. _this.renderOutline = false;
  10672. _this.outlineColor = BABYLON.Color3.Red();
  10673. _this.outlineWidth = 0.02;
  10674. _this.renderOverlay = false;
  10675. _this.overlayColor = BABYLON.Color3.Red();
  10676. _this.overlayAlpha = 0.5;
  10677. _this._hasVertexAlpha = false;
  10678. _this._useVertexColors = true;
  10679. _this._computeBonesUsingShaders = true;
  10680. _this._numBoneInfluencers = 4;
  10681. _this._applyFog = true;
  10682. _this.scalingDeterminant = 1;
  10683. _this.useOctreeForRenderingSelection = true;
  10684. _this.useOctreeForPicking = true;
  10685. _this.useOctreeForCollisions = true;
  10686. _this.layerMask = 0x0FFFFFFF;
  10687. /**
  10688. * True if the mesh must be rendered in any case.
  10689. */
  10690. _this.alwaysSelectAsActiveMesh = false;
  10691. // Collisions
  10692. _this._checkCollisions = false;
  10693. _this._collisionMask = -1;
  10694. _this._collisionGroup = -1;
  10695. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  10696. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  10697. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10698. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10699. _this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10700. // Edges
  10701. _this.edgesWidth = 1;
  10702. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  10703. // Cache
  10704. _this._localWorld = BABYLON.Matrix.Zero();
  10705. _this._worldMatrix = BABYLON.Matrix.Zero();
  10706. _this._absolutePosition = BABYLON.Vector3.Zero();
  10707. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  10708. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  10709. _this._isDirty = false;
  10710. _this._pivotMatrix = BABYLON.Matrix.Identity();
  10711. _this._isDisposed = false;
  10712. _this._renderId = 0;
  10713. _this._intersectionsInProgress = new Array();
  10714. _this._isWorldMatrixFrozen = false;
  10715. _this._unIndexed = false;
  10716. _this._lightSources = new Array();
  10717. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  10718. if (collidedMesh === void 0) { collidedMesh = null; }
  10719. //TODO move this to the collision coordinator!
  10720. if (_this.getScene().workerCollisions)
  10721. newPosition.multiplyInPlace(_this._collider.radius);
  10722. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  10723. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  10724. _this.position.addInPlace(_this._diffPositionForCollisions);
  10725. }
  10726. if (collidedMesh) {
  10727. _this.onCollideObservable.notifyObservers(collidedMesh);
  10728. }
  10729. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  10730. };
  10731. _this.getScene().addMesh(_this);
  10732. _this._resyncLightSources();
  10733. return _this;
  10734. }
  10735. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  10736. get: function () {
  10737. return AbstractMesh._BILLBOARDMODE_NONE;
  10738. },
  10739. enumerable: true,
  10740. configurable: true
  10741. });
  10742. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  10743. get: function () {
  10744. return AbstractMesh._BILLBOARDMODE_X;
  10745. },
  10746. enumerable: true,
  10747. configurable: true
  10748. });
  10749. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  10750. get: function () {
  10751. return AbstractMesh._BILLBOARDMODE_Y;
  10752. },
  10753. enumerable: true,
  10754. configurable: true
  10755. });
  10756. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  10757. get: function () {
  10758. return AbstractMesh._BILLBOARDMODE_Z;
  10759. },
  10760. enumerable: true,
  10761. configurable: true
  10762. });
  10763. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  10764. get: function () {
  10765. return AbstractMesh._BILLBOARDMODE_ALL;
  10766. },
  10767. enumerable: true,
  10768. configurable: true
  10769. });
  10770. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  10771. /**
  10772. * Read-only : the number of facets in the mesh
  10773. */
  10774. get: function () {
  10775. return this._facetNb;
  10776. },
  10777. enumerable: true,
  10778. configurable: true
  10779. });
  10780. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  10781. /**
  10782. * The number (integer) of subdivisions per axis in the partioning space
  10783. */
  10784. get: function () {
  10785. return this._partitioningSubdivisions;
  10786. },
  10787. set: function (nb) {
  10788. this._partitioningSubdivisions = nb;
  10789. },
  10790. enumerable: true,
  10791. configurable: true
  10792. });
  10793. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  10794. /**
  10795. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  10796. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  10797. */
  10798. get: function () {
  10799. return this._partitioningBBoxRatio;
  10800. },
  10801. set: function (ratio) {
  10802. this._partitioningBBoxRatio = ratio;
  10803. },
  10804. enumerable: true,
  10805. configurable: true
  10806. });
  10807. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  10808. /**
  10809. * Read-only boolean : is the feature facetData enabled ?
  10810. */
  10811. get: function () {
  10812. return this._facetDataEnabled;
  10813. },
  10814. enumerable: true,
  10815. configurable: true
  10816. });
  10817. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  10818. set: function (callback) {
  10819. if (this._onCollideObserver) {
  10820. this.onCollideObservable.remove(this._onCollideObserver);
  10821. }
  10822. this._onCollideObserver = this.onCollideObservable.add(callback);
  10823. },
  10824. enumerable: true,
  10825. configurable: true
  10826. });
  10827. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  10828. set: function (callback) {
  10829. if (this._onCollisionPositionChangeObserver) {
  10830. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  10831. }
  10832. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  10833. },
  10834. enumerable: true,
  10835. configurable: true
  10836. });
  10837. Object.defineProperty(AbstractMesh.prototype, "material", {
  10838. get: function () {
  10839. return this._material;
  10840. },
  10841. set: function (value) {
  10842. if (this._material === value) {
  10843. return;
  10844. }
  10845. this._material = value;
  10846. if (!this.subMeshes) {
  10847. return;
  10848. }
  10849. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  10850. var subMesh = _a[_i];
  10851. subMesh.setEffect(null);
  10852. }
  10853. },
  10854. enumerable: true,
  10855. configurable: true
  10856. });
  10857. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  10858. get: function () {
  10859. return this._receiveShadows;
  10860. },
  10861. set: function (value) {
  10862. if (this._receiveShadows === value) {
  10863. return;
  10864. }
  10865. this._receiveShadows = value;
  10866. this._markSubMeshesAsLightDirty();
  10867. },
  10868. enumerable: true,
  10869. configurable: true
  10870. });
  10871. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  10872. get: function () {
  10873. return this._hasVertexAlpha;
  10874. },
  10875. set: function (value) {
  10876. if (this._hasVertexAlpha === value) {
  10877. return;
  10878. }
  10879. this._hasVertexAlpha = value;
  10880. this._markSubMeshesAsAttributesDirty();
  10881. },
  10882. enumerable: true,
  10883. configurable: true
  10884. });
  10885. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  10886. get: function () {
  10887. return this._useVertexColors;
  10888. },
  10889. set: function (value) {
  10890. if (this._useVertexColors === value) {
  10891. return;
  10892. }
  10893. this._useVertexColors = value;
  10894. this._markSubMeshesAsAttributesDirty();
  10895. },
  10896. enumerable: true,
  10897. configurable: true
  10898. });
  10899. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  10900. get: function () {
  10901. return this._computeBonesUsingShaders;
  10902. },
  10903. set: function (value) {
  10904. if (this._computeBonesUsingShaders === value) {
  10905. return;
  10906. }
  10907. this._computeBonesUsingShaders = value;
  10908. this._markSubMeshesAsAttributesDirty();
  10909. },
  10910. enumerable: true,
  10911. configurable: true
  10912. });
  10913. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  10914. get: function () {
  10915. return this._numBoneInfluencers;
  10916. },
  10917. set: function (value) {
  10918. if (this._numBoneInfluencers === value) {
  10919. return;
  10920. }
  10921. this._numBoneInfluencers = value;
  10922. this._markSubMeshesAsAttributesDirty();
  10923. },
  10924. enumerable: true,
  10925. configurable: true
  10926. });
  10927. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  10928. get: function () {
  10929. return this._applyFog;
  10930. },
  10931. set: function (value) {
  10932. if (this._applyFog === value) {
  10933. return;
  10934. }
  10935. this._applyFog = value;
  10936. this._markSubMeshesAsMiscDirty();
  10937. },
  10938. enumerable: true,
  10939. configurable: true
  10940. });
  10941. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  10942. get: function () {
  10943. return this._collisionMask;
  10944. },
  10945. set: function (mask) {
  10946. this._collisionMask = !isNaN(mask) ? mask : -1;
  10947. },
  10948. enumerable: true,
  10949. configurable: true
  10950. });
  10951. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  10952. get: function () {
  10953. return this._collisionGroup;
  10954. },
  10955. set: function (mask) {
  10956. this._collisionGroup = !isNaN(mask) ? mask : -1;
  10957. },
  10958. enumerable: true,
  10959. configurable: true
  10960. });
  10961. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  10962. get: function () {
  10963. return this._skeleton;
  10964. },
  10965. set: function (value) {
  10966. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  10967. this._skeleton._unregisterMeshWithPoseMatrix(this);
  10968. }
  10969. if (value && value.needInitialSkinMatrix) {
  10970. value._registerMeshWithPoseMatrix(this);
  10971. }
  10972. this._skeleton = value;
  10973. if (!this._skeleton) {
  10974. this._bonesTransformMatrices = null;
  10975. }
  10976. this._markSubMeshesAsAttributesDirty();
  10977. },
  10978. enumerable: true,
  10979. configurable: true
  10980. });
  10981. /**
  10982. * Returns the string "AbstractMesh"
  10983. */
  10984. AbstractMesh.prototype.getClassName = function () {
  10985. return "AbstractMesh";
  10986. };
  10987. /**
  10988. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  10989. */
  10990. AbstractMesh.prototype.toString = function (fullDetails) {
  10991. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  10992. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  10993. if (this._skeleton) {
  10994. ret += ", skeleton: " + this._skeleton.name;
  10995. }
  10996. if (fullDetails) {
  10997. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  10998. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  10999. }
  11000. return ret;
  11001. };
  11002. AbstractMesh.prototype._resyncLightSources = function () {
  11003. this._lightSources.length = 0;
  11004. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  11005. var light = _a[_i];
  11006. if (!light.isEnabled()) {
  11007. continue;
  11008. }
  11009. if (light.canAffectMesh(this)) {
  11010. this._lightSources.push(light);
  11011. }
  11012. }
  11013. this._markSubMeshesAsLightDirty();
  11014. };
  11015. AbstractMesh.prototype._resyncLighSource = function (light) {
  11016. var isIn = light.isEnabled() && light.canAffectMesh(this);
  11017. var index = this._lightSources.indexOf(light);
  11018. if (index === -1) {
  11019. if (!isIn) {
  11020. return;
  11021. }
  11022. this._lightSources.push(light);
  11023. }
  11024. else {
  11025. if (isIn) {
  11026. return;
  11027. }
  11028. this._lightSources.splice(index, 1);
  11029. }
  11030. this._markSubMeshesAsLightDirty();
  11031. };
  11032. AbstractMesh.prototype._removeLightSource = function (light) {
  11033. var index = this._lightSources.indexOf(light);
  11034. if (index === -1) {
  11035. return;
  11036. }
  11037. this._lightSources.splice(index, 1);
  11038. };
  11039. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  11040. if (!this.subMeshes) {
  11041. return;
  11042. }
  11043. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  11044. var subMesh = _a[_i];
  11045. if (subMesh._materialDefines) {
  11046. func(subMesh._materialDefines);
  11047. }
  11048. }
  11049. };
  11050. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  11051. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  11052. };
  11053. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  11054. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  11055. };
  11056. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  11057. if (!this.subMeshes) {
  11058. return;
  11059. }
  11060. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  11061. var subMesh = _a[_i];
  11062. var material = subMesh.getMaterial();
  11063. if (material) {
  11064. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  11065. }
  11066. }
  11067. };
  11068. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  11069. /**
  11070. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  11071. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  11072. * Default : (0.0, 0.0, 0.0)
  11073. */
  11074. get: function () {
  11075. return this._rotation;
  11076. },
  11077. set: function (newRotation) {
  11078. this._rotation = newRotation;
  11079. },
  11080. enumerable: true,
  11081. configurable: true
  11082. });
  11083. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  11084. /**
  11085. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  11086. * Default : (1.0, 1.0, 1.0)
  11087. */
  11088. get: function () {
  11089. return this._scaling;
  11090. },
  11091. set: function (newScaling) {
  11092. this._scaling = newScaling;
  11093. if (this.physicsImpostor) {
  11094. this.physicsImpostor.forceUpdate();
  11095. }
  11096. },
  11097. enumerable: true,
  11098. configurable: true
  11099. });
  11100. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  11101. /**
  11102. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  11103. * It's null by default.
  11104. * 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)
  11105. */
  11106. get: function () {
  11107. return this._rotationQuaternion;
  11108. },
  11109. set: function (quaternion) {
  11110. this._rotationQuaternion = quaternion;
  11111. //reset the rotation vector.
  11112. if (quaternion && this.rotation.length()) {
  11113. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  11114. }
  11115. },
  11116. enumerable: true,
  11117. configurable: true
  11118. });
  11119. // Methods
  11120. /**
  11121. * Copies the paramater passed Matrix into the mesh Pose matrix.
  11122. * Returns the AbstractMesh.
  11123. */
  11124. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  11125. this._poseMatrix.copyFrom(matrix);
  11126. return this;
  11127. };
  11128. /**
  11129. * Returns the mesh Pose matrix.
  11130. * Returned object : Matrix
  11131. */
  11132. AbstractMesh.prototype.getPoseMatrix = function () {
  11133. return this._poseMatrix;
  11134. };
  11135. /**
  11136. * Disables the mesh edger rendering mode.
  11137. * Returns the AbstractMesh.
  11138. */
  11139. AbstractMesh.prototype.disableEdgesRendering = function () {
  11140. if (this._edgesRenderer !== undefined) {
  11141. this._edgesRenderer.dispose();
  11142. this._edgesRenderer = undefined;
  11143. }
  11144. return this;
  11145. };
  11146. /**
  11147. * Enables the edge rendering mode on the mesh.
  11148. * This mode makes the mesh edges visible.
  11149. * Returns the AbstractMesh.
  11150. */
  11151. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  11152. if (epsilon === void 0) { epsilon = 0.95; }
  11153. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  11154. this.disableEdgesRendering();
  11155. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  11156. return this;
  11157. };
  11158. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  11159. /**
  11160. * Returns true if the mesh is blocked. Used by the class Mesh.
  11161. * Returns the boolean `false` by default.
  11162. */
  11163. get: function () {
  11164. return false;
  11165. },
  11166. enumerable: true,
  11167. configurable: true
  11168. });
  11169. /**
  11170. * Returns the mesh itself by default, used by the class Mesh.
  11171. * Returned type : AbstractMesh
  11172. */
  11173. AbstractMesh.prototype.getLOD = function (camera) {
  11174. return this;
  11175. };
  11176. /**
  11177. * Returns 0 by default, used by the class Mesh.
  11178. * Returns an integer.
  11179. */
  11180. AbstractMesh.prototype.getTotalVertices = function () {
  11181. return 0;
  11182. };
  11183. /**
  11184. * Returns null by default, used by the class Mesh.
  11185. * Returned type : integer array
  11186. */
  11187. AbstractMesh.prototype.getIndices = function () {
  11188. return null;
  11189. };
  11190. /**
  11191. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  11192. * Returned type : float array or Float32Array
  11193. */
  11194. AbstractMesh.prototype.getVerticesData = function (kind) {
  11195. return null;
  11196. };
  11197. /**
  11198. * Sets the vertex data of the mesh geometry for the requested `kind`.
  11199. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  11200. * The `data` are either a numeric array either a Float32Array.
  11201. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  11202. * 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).
  11203. * Note that a new underlying VertexBuffer object is created each call.
  11204. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  11205. *
  11206. * Possible `kind` values :
  11207. * - BABYLON.VertexBuffer.PositionKind
  11208. * - BABYLON.VertexBuffer.UVKind
  11209. * - BABYLON.VertexBuffer.UV2Kind
  11210. * - BABYLON.VertexBuffer.UV3Kind
  11211. * - BABYLON.VertexBuffer.UV4Kind
  11212. * - BABYLON.VertexBuffer.UV5Kind
  11213. * - BABYLON.VertexBuffer.UV6Kind
  11214. * - BABYLON.VertexBuffer.ColorKind
  11215. * - BABYLON.VertexBuffer.MatricesIndicesKind
  11216. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  11217. * - BABYLON.VertexBuffer.MatricesWeightsKind
  11218. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  11219. *
  11220. * Returns the Mesh.
  11221. */
  11222. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  11223. return null;
  11224. };
  11225. /**
  11226. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  11227. * If the mesh has no geometry, it is simply returned as it is.
  11228. * The `data` are either a numeric array either a Float32Array.
  11229. * No new underlying VertexBuffer object is created.
  11230. * 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.
  11231. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  11232. *
  11233. * Possible `kind` values :
  11234. * - BABYLON.VertexBuffer.PositionKind
  11235. * - BABYLON.VertexBuffer.UVKind
  11236. * - BABYLON.VertexBuffer.UV2Kind
  11237. * - BABYLON.VertexBuffer.UV3Kind
  11238. * - BABYLON.VertexBuffer.UV4Kind
  11239. * - BABYLON.VertexBuffer.UV5Kind
  11240. * - BABYLON.VertexBuffer.UV6Kind
  11241. * - BABYLON.VertexBuffer.ColorKind
  11242. * - BABYLON.VertexBuffer.MatricesIndicesKind
  11243. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  11244. * - BABYLON.VertexBuffer.MatricesWeightsKind
  11245. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  11246. *
  11247. * Returns the Mesh.
  11248. */
  11249. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  11250. return null;
  11251. };
  11252. /**
  11253. * Sets the mesh indices.
  11254. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  11255. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  11256. * This method creates a new index buffer each call.
  11257. * Returns the Mesh.
  11258. */
  11259. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  11260. return null;
  11261. };
  11262. /** Returns false by default, used by the class Mesh.
  11263. * Returns a boolean
  11264. */
  11265. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  11266. return false;
  11267. };
  11268. /**
  11269. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  11270. * Returns a BoundingInfo
  11271. */
  11272. AbstractMesh.prototype.getBoundingInfo = function () {
  11273. if (this._masterMesh) {
  11274. return this._masterMesh.getBoundingInfo();
  11275. }
  11276. if (!this._boundingInfo) {
  11277. this._updateBoundingInfo();
  11278. }
  11279. return this._boundingInfo;
  11280. };
  11281. /**
  11282. * Sets a mesh new object BoundingInfo.
  11283. * Returns the AbstractMesh.
  11284. */
  11285. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  11286. this._boundingInfo = boundingInfo;
  11287. return this;
  11288. };
  11289. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  11290. get: function () {
  11291. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  11292. },
  11293. enumerable: true,
  11294. configurable: true
  11295. });
  11296. AbstractMesh.prototype._preActivate = function () {
  11297. };
  11298. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  11299. };
  11300. AbstractMesh.prototype._activate = function (renderId) {
  11301. this._renderId = renderId;
  11302. };
  11303. /**
  11304. * Returns the last update of the World matrix
  11305. * Returns a Matrix.
  11306. */
  11307. AbstractMesh.prototype.getWorldMatrix = function () {
  11308. if (this._masterMesh) {
  11309. return this._masterMesh.getWorldMatrix();
  11310. }
  11311. if (this._currentRenderId !== this.getScene().getRenderId() || !this.isSynchronized()) {
  11312. this.computeWorldMatrix();
  11313. }
  11314. return this._worldMatrix;
  11315. };
  11316. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  11317. /**
  11318. * Returns directly the last state of the mesh World matrix.
  11319. * A Matrix is returned.
  11320. */
  11321. get: function () {
  11322. return this._worldMatrix;
  11323. },
  11324. enumerable: true,
  11325. configurable: true
  11326. });
  11327. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  11328. /**
  11329. * Returns the current mesh absolute position.
  11330. * Retuns a Vector3.
  11331. */
  11332. get: function () {
  11333. return this._absolutePosition;
  11334. },
  11335. enumerable: true,
  11336. configurable: true
  11337. });
  11338. /**
  11339. * Prevents the World matrix to be computed any longer.
  11340. * Returns the AbstractMesh.
  11341. */
  11342. AbstractMesh.prototype.freezeWorldMatrix = function () {
  11343. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  11344. this.computeWorldMatrix(true);
  11345. this._isWorldMatrixFrozen = true;
  11346. return this;
  11347. };
  11348. /**
  11349. * Allows back the World matrix computation.
  11350. * Returns the AbstractMesh.
  11351. */
  11352. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  11353. this._isWorldMatrixFrozen = false;
  11354. this.computeWorldMatrix(true);
  11355. return this;
  11356. };
  11357. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  11358. /**
  11359. * True if the World matrix has been frozen.
  11360. * Returns a boolean.
  11361. */
  11362. get: function () {
  11363. return this._isWorldMatrixFrozen;
  11364. },
  11365. enumerable: true,
  11366. configurable: true
  11367. });
  11368. /**
  11369. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  11370. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  11371. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  11372. * The passed axis is also normalized.
  11373. * Returns the AbstractMesh.
  11374. */
  11375. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  11376. axis.normalize();
  11377. if (!this.rotationQuaternion) {
  11378. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  11379. this.rotation = BABYLON.Vector3.Zero();
  11380. }
  11381. var rotationQuaternion;
  11382. if (!space || space === BABYLON.Space.LOCAL) {
  11383. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  11384. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  11385. }
  11386. else {
  11387. if (this.parent) {
  11388. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  11389. invertParentWorldMatrix.invert();
  11390. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  11391. }
  11392. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  11393. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  11394. }
  11395. return this;
  11396. };
  11397. /**
  11398. * Translates the mesh along the axis vector for the passed distance in the given space.
  11399. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  11400. * Returns the AbstractMesh.
  11401. */
  11402. AbstractMesh.prototype.translate = function (axis, distance, space) {
  11403. var displacementVector = axis.scale(distance);
  11404. if (!space || space === BABYLON.Space.LOCAL) {
  11405. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  11406. this.setPositionWithLocalVector(tempV3);
  11407. }
  11408. else {
  11409. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  11410. }
  11411. return this;
  11412. };
  11413. /**
  11414. * Adds a rotation step to the mesh current rotation.
  11415. * x, y, z are Euler angles expressed in radians.
  11416. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  11417. * This means this rotation is made in the mesh local space only.
  11418. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  11419. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  11420. * ```javascript
  11421. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  11422. * ```
  11423. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  11424. * 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.
  11425. * Returns the AbstractMesh.
  11426. */
  11427. AbstractMesh.prototype.addRotation = function (x, y, z) {
  11428. var rotationQuaternion;
  11429. if (this.rotationQuaternion) {
  11430. rotationQuaternion = this.rotationQuaternion;
  11431. }
  11432. else {
  11433. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  11434. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  11435. }
  11436. var accumulation = BABYLON.Tmp.Quaternion[0];
  11437. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  11438. rotationQuaternion.multiplyInPlace(accumulation);
  11439. if (!this.rotationQuaternion) {
  11440. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  11441. }
  11442. return this;
  11443. };
  11444. /**
  11445. * Retuns the mesh absolute position in the World.
  11446. * Returns a Vector3.
  11447. */
  11448. AbstractMesh.prototype.getAbsolutePosition = function () {
  11449. this.computeWorldMatrix();
  11450. return this._absolutePosition;
  11451. };
  11452. /**
  11453. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  11454. * Returns the AbstractMesh.
  11455. */
  11456. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  11457. if (!absolutePosition) {
  11458. return;
  11459. }
  11460. var absolutePositionX;
  11461. var absolutePositionY;
  11462. var absolutePositionZ;
  11463. if (absolutePosition.x === undefined) {
  11464. if (arguments.length < 3) {
  11465. return;
  11466. }
  11467. absolutePositionX = arguments[0];
  11468. absolutePositionY = arguments[1];
  11469. absolutePositionZ = arguments[2];
  11470. }
  11471. else {
  11472. absolutePositionX = absolutePosition.x;
  11473. absolutePositionY = absolutePosition.y;
  11474. absolutePositionZ = absolutePosition.z;
  11475. }
  11476. if (this.parent) {
  11477. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  11478. invertParentWorldMatrix.invert();
  11479. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  11480. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  11481. }
  11482. else {
  11483. this.position.x = absolutePositionX;
  11484. this.position.y = absolutePositionY;
  11485. this.position.z = absolutePositionZ;
  11486. }
  11487. return this;
  11488. };
  11489. // ================================== Point of View Movement =================================
  11490. /**
  11491. * Perform relative position change from the point of view of behind the front of the mesh.
  11492. * This is performed taking into account the meshes current rotation, so you do not have to care.
  11493. * Supports definition of mesh facing forward or backward.
  11494. * @param {number} amountRight
  11495. * @param {number} amountUp
  11496. * @param {number} amountForward
  11497. *
  11498. * Returns the AbstractMesh.
  11499. */
  11500. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  11501. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  11502. return this;
  11503. };
  11504. /**
  11505. * Calculate relative position change from the point of view of behind the front of the mesh.
  11506. * This is performed taking into account the meshes current rotation, so you do not have to care.
  11507. * Supports definition of mesh facing forward or backward.
  11508. * @param {number} amountRight
  11509. * @param {number} amountUp
  11510. * @param {number} amountForward
  11511. *
  11512. * Returns a new Vector3.
  11513. */
  11514. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  11515. var rotMatrix = new BABYLON.Matrix();
  11516. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  11517. rotQuaternion.toRotationMatrix(rotMatrix);
  11518. var translationDelta = BABYLON.Vector3.Zero();
  11519. var defForwardMult = this.definedFacingForward ? -1 : 1;
  11520. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  11521. return translationDelta;
  11522. };
  11523. // ================================== Point of View Rotation =================================
  11524. /**
  11525. * Perform relative rotation change from the point of view of behind the front of the mesh.
  11526. * Supports definition of mesh facing forward or backward.
  11527. * @param {number} flipBack
  11528. * @param {number} twirlClockwise
  11529. * @param {number} tiltRight
  11530. *
  11531. * Returns the AbstractMesh.
  11532. */
  11533. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  11534. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  11535. return this;
  11536. };
  11537. /**
  11538. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  11539. * Supports definition of mesh facing forward or backward.
  11540. * @param {number} flipBack
  11541. * @param {number} twirlClockwise
  11542. * @param {number} tiltRight
  11543. *
  11544. * Returns a new Vector3.
  11545. */
  11546. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  11547. var defForwardMult = this.definedFacingForward ? 1 : -1;
  11548. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  11549. };
  11550. /**
  11551. * Sets a new pivot matrix to the mesh.
  11552. * Returns the AbstractMesh.
  11553. */
  11554. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  11555. this._pivotMatrix = matrix;
  11556. this._cache.pivotMatrixUpdated = true;
  11557. return this;
  11558. };
  11559. /**
  11560. * Returns the mesh pivot matrix.
  11561. * Default : Identity.
  11562. * A Matrix is returned.
  11563. */
  11564. AbstractMesh.prototype.getPivotMatrix = function () {
  11565. return this._pivotMatrix;
  11566. };
  11567. AbstractMesh.prototype._isSynchronized = function () {
  11568. if (this._isDirty) {
  11569. return false;
  11570. }
  11571. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  11572. return false;
  11573. if (this._cache.pivotMatrixUpdated) {
  11574. return false;
  11575. }
  11576. if (this.infiniteDistance) {
  11577. return false;
  11578. }
  11579. if (!this._cache.position.equals(this.position))
  11580. return false;
  11581. if (this.rotationQuaternion) {
  11582. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  11583. return false;
  11584. }
  11585. if (!this._cache.rotation.equals(this.rotation))
  11586. return false;
  11587. if (!this._cache.scaling.equals(this.scaling))
  11588. return false;
  11589. return true;
  11590. };
  11591. AbstractMesh.prototype._initCache = function () {
  11592. _super.prototype._initCache.call(this);
  11593. this._cache.localMatrixUpdated = false;
  11594. this._cache.position = BABYLON.Vector3.Zero();
  11595. this._cache.scaling = BABYLON.Vector3.Zero();
  11596. this._cache.rotation = BABYLON.Vector3.Zero();
  11597. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  11598. this._cache.billboardMode = -1;
  11599. };
  11600. AbstractMesh.prototype.markAsDirty = function (property) {
  11601. if (property === "rotation") {
  11602. this.rotationQuaternion = null;
  11603. }
  11604. this._currentRenderId = Number.MAX_VALUE;
  11605. this._isDirty = true;
  11606. return this;
  11607. };
  11608. /**
  11609. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  11610. * Returns the AbstractMesh.
  11611. */
  11612. AbstractMesh.prototype._updateBoundingInfo = function () {
  11613. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  11614. this._boundingInfo.update(this.worldMatrixFromCache);
  11615. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  11616. return this;
  11617. };
  11618. /**
  11619. * Update a mesh's children BoundingInfo objects only.
  11620. * Returns the AbstractMesh.
  11621. */
  11622. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  11623. if (!this.subMeshes) {
  11624. return;
  11625. }
  11626. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  11627. var subMesh = this.subMeshes[subIndex];
  11628. if (!subMesh.IsGlobal) {
  11629. subMesh.updateBoundingInfo(matrix);
  11630. }
  11631. }
  11632. return this;
  11633. };
  11634. /**
  11635. * Computes the mesh World matrix and returns it.
  11636. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  11637. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  11638. * If the parameter `force`is set to `true`, the actual computation is done.
  11639. * Returns the mesh World Matrix.
  11640. */
  11641. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  11642. if (this._isWorldMatrixFrozen) {
  11643. return this._worldMatrix;
  11644. }
  11645. if (!force && this.isSynchronized(true)) {
  11646. this._currentRenderId = this.getScene().getRenderId();
  11647. return this._worldMatrix;
  11648. }
  11649. this._cache.position.copyFrom(this.position);
  11650. this._cache.scaling.copyFrom(this.scaling);
  11651. this._cache.pivotMatrixUpdated = false;
  11652. this._cache.billboardMode = this.billboardMode;
  11653. this._currentRenderId = this.getScene().getRenderId();
  11654. this._isDirty = false;
  11655. // Scaling
  11656. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  11657. // Rotation
  11658. //rotate, if quaternion is set and rotation was used
  11659. if (this.rotationQuaternion) {
  11660. var len = this.rotation.length();
  11661. if (len) {
  11662. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  11663. this.rotation.copyFromFloats(0, 0, 0);
  11664. }
  11665. }
  11666. if (this.rotationQuaternion) {
  11667. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  11668. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  11669. }
  11670. else {
  11671. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  11672. this._cache.rotation.copyFrom(this.rotation);
  11673. }
  11674. // Translation
  11675. if (this.infiniteDistance && !this.parent) {
  11676. var camera = this.getScene().activeCamera;
  11677. if (camera) {
  11678. var cameraWorldMatrix = camera.getWorldMatrix();
  11679. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  11680. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  11681. }
  11682. }
  11683. else {
  11684. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  11685. }
  11686. // Composing transformations
  11687. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  11688. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  11689. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  11690. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  11691. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  11692. // Need to decompose each rotation here
  11693. var currentPosition = BABYLON.Tmp.Vector3[3];
  11694. if (this.parent && this.parent.getWorldMatrix) {
  11695. if (this._meshToBoneReferal) {
  11696. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  11697. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  11698. }
  11699. else {
  11700. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  11701. }
  11702. }
  11703. else {
  11704. currentPosition.copyFrom(this.position);
  11705. }
  11706. currentPosition.subtractInPlace(this.getScene().activeCamera.globalPosition);
  11707. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  11708. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_X) === AbstractMesh.BILLBOARDMODE_X) {
  11709. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  11710. }
  11711. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Y) === AbstractMesh.BILLBOARDMODE_Y) {
  11712. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  11713. }
  11714. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Z) === AbstractMesh.BILLBOARDMODE_Z) {
  11715. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  11716. }
  11717. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  11718. }
  11719. else {
  11720. BABYLON.Tmp.Matrix[1].copyFrom(this.getScene().activeCamera.getViewMatrix());
  11721. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  11722. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  11723. }
  11724. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  11725. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  11726. }
  11727. // Local world
  11728. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  11729. // Parent
  11730. if (this.parent && this.parent.getWorldMatrix) {
  11731. this._markSyncedWithParent();
  11732. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE) {
  11733. if (this._meshToBoneReferal) {
  11734. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  11735. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  11736. }
  11737. else {
  11738. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  11739. }
  11740. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  11741. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  11742. this._worldMatrix.copyFrom(this._localWorld);
  11743. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  11744. }
  11745. else {
  11746. if (this._meshToBoneReferal) {
  11747. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  11748. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  11749. }
  11750. else {
  11751. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  11752. }
  11753. }
  11754. }
  11755. else {
  11756. this._worldMatrix.copyFrom(this._localWorld);
  11757. }
  11758. // Bounding info
  11759. this._updateBoundingInfo();
  11760. // Absolute position
  11761. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  11762. // Callbacks
  11763. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  11764. if (!this._poseMatrix) {
  11765. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  11766. }
  11767. return this._worldMatrix;
  11768. };
  11769. /**
  11770. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  11771. * @param func: callback function to add
  11772. *
  11773. * Returns the AbstractMesh.
  11774. */
  11775. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  11776. this.onAfterWorldMatrixUpdateObservable.add(func);
  11777. return this;
  11778. };
  11779. /**
  11780. * Removes a registered callback function.
  11781. * Returns the AbstractMesh.
  11782. */
  11783. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  11784. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  11785. return this;
  11786. };
  11787. /**
  11788. * Sets the mesh position in its local space.
  11789. * Returns the AbstractMesh.
  11790. */
  11791. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  11792. this.computeWorldMatrix();
  11793. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  11794. return this;
  11795. };
  11796. /**
  11797. * Returns the mesh position in the local space from the current World matrix values.
  11798. * Returns a new Vector3.
  11799. */
  11800. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  11801. this.computeWorldMatrix();
  11802. var invLocalWorldMatrix = this._localWorld.clone();
  11803. invLocalWorldMatrix.invert();
  11804. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  11805. };
  11806. /**
  11807. * Translates the mesh along the passed Vector3 in its local space.
  11808. * Returns the AbstractMesh.
  11809. */
  11810. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  11811. this.computeWorldMatrix(true);
  11812. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  11813. return this;
  11814. };
  11815. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  11816. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  11817. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  11818. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  11819. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  11820. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  11821. /// <returns>Mesh oriented towards targetMesh</returns>
  11822. if (yawCor === void 0) { yawCor = 0; }
  11823. if (pitchCor === void 0) { pitchCor = 0; }
  11824. if (rollCor === void 0) { rollCor = 0; }
  11825. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  11826. var dv = AbstractMesh._lookAtVectorCache;
  11827. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  11828. targetPoint.subtractToRef(pos, dv);
  11829. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  11830. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  11831. var pitch = Math.atan2(dv.y, len);
  11832. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  11833. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  11834. return this;
  11835. };
  11836. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  11837. this._meshToBoneReferal = affectedMesh;
  11838. this.parent = bone;
  11839. if (bone.getWorldMatrix().determinant() < 0) {
  11840. this.scalingDeterminant *= -1;
  11841. }
  11842. return this;
  11843. };
  11844. AbstractMesh.prototype.detachFromBone = function () {
  11845. if (this.parent.getWorldMatrix().determinant() < 0) {
  11846. this.scalingDeterminant *= -1;
  11847. }
  11848. this._meshToBoneReferal = null;
  11849. this.parent = null;
  11850. return this;
  11851. };
  11852. /**
  11853. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  11854. * A mesh is in the frustum if its bounding box intersects the frustum.
  11855. * Boolean returned.
  11856. */
  11857. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  11858. return this._boundingInfo.isInFrustum(frustumPlanes);
  11859. };
  11860. /**
  11861. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  11862. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  11863. * Boolean returned.
  11864. */
  11865. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  11866. return this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  11867. ;
  11868. };
  11869. /**
  11870. * True if the mesh intersects another mesh or a SolidParticle object.
  11871. * 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)
  11872. * Returns a boolean.
  11873. */
  11874. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  11875. if (!this._boundingInfo || !mesh._boundingInfo) {
  11876. return false;
  11877. }
  11878. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  11879. };
  11880. /**
  11881. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  11882. * Returns a boolean.
  11883. */
  11884. AbstractMesh.prototype.intersectsPoint = function (point) {
  11885. if (!this._boundingInfo) {
  11886. return false;
  11887. }
  11888. return this._boundingInfo.intersectsPoint(point);
  11889. };
  11890. AbstractMesh.prototype.getPhysicsImpostor = function () {
  11891. return this.physicsImpostor;
  11892. };
  11893. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  11894. if (!camera) {
  11895. camera = this.getScene().activeCamera;
  11896. }
  11897. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  11898. };
  11899. /**
  11900. * Returns the distance from the mesh to the active camera.
  11901. * Returns a float.
  11902. */
  11903. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  11904. if (!camera) {
  11905. camera = this.getScene().activeCamera;
  11906. }
  11907. return this.absolutePosition.subtract(camera.position).length();
  11908. };
  11909. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  11910. if (!this.physicsImpostor) {
  11911. return;
  11912. }
  11913. this.physicsImpostor.applyImpulse(force, contactPoint);
  11914. return this;
  11915. };
  11916. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  11917. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  11918. return;
  11919. }
  11920. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  11921. mainPivot: pivot1,
  11922. connectedPivot: pivot2,
  11923. nativeParams: options
  11924. });
  11925. return this;
  11926. };
  11927. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  11928. // Collisions
  11929. /**
  11930. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  11931. * Default `false`.
  11932. */
  11933. get: function () {
  11934. return this._checkCollisions;
  11935. },
  11936. set: function (collisionEnabled) {
  11937. this._checkCollisions = collisionEnabled;
  11938. if (this.getScene().workerCollisions) {
  11939. this.getScene().collisionCoordinator.onMeshUpdated(this);
  11940. }
  11941. },
  11942. enumerable: true,
  11943. configurable: true
  11944. });
  11945. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  11946. var globalPosition = this.getAbsolutePosition();
  11947. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  11948. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  11949. if (!this._collider) {
  11950. this._collider = new BABYLON.Collider();
  11951. }
  11952. this._collider.radius = this.ellipsoid;
  11953. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  11954. return this;
  11955. };
  11956. // Submeshes octree
  11957. /**
  11958. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  11959. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  11960. * Returns an Octree of submeshes.
  11961. */
  11962. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  11963. if (maxCapacity === void 0) { maxCapacity = 64; }
  11964. if (maxDepth === void 0) { maxDepth = 2; }
  11965. if (!this._submeshesOctree) {
  11966. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  11967. }
  11968. this.computeWorldMatrix(true);
  11969. // Update octree
  11970. var bbox = this.getBoundingInfo().boundingBox;
  11971. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  11972. return this._submeshesOctree;
  11973. };
  11974. // Collisions
  11975. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  11976. this._generatePointsArray();
  11977. // Transformation
  11978. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  11979. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  11980. subMesh._lastColliderWorldVertices = [];
  11981. subMesh._trianglePlanes = [];
  11982. var start = subMesh.verticesStart;
  11983. var end = (subMesh.verticesStart + subMesh.verticesCount);
  11984. for (var i = start; i < end; i++) {
  11985. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  11986. }
  11987. }
  11988. // Collide
  11989. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  11990. if (collider.collisionFound) {
  11991. collider.collidedMesh = this;
  11992. }
  11993. return this;
  11994. };
  11995. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  11996. var subMeshes;
  11997. var len;
  11998. // Octrees
  11999. if (this._submeshesOctree && this.useOctreeForCollisions) {
  12000. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  12001. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  12002. len = intersections.length;
  12003. subMeshes = intersections.data;
  12004. }
  12005. else {
  12006. subMeshes = this.subMeshes;
  12007. len = subMeshes.length;
  12008. }
  12009. for (var index = 0; index < len; index++) {
  12010. var subMesh = subMeshes[index];
  12011. // Bounding test
  12012. if (len > 1 && !subMesh._checkCollision(collider))
  12013. continue;
  12014. this._collideForSubMesh(subMesh, transformMatrix, collider);
  12015. }
  12016. return this;
  12017. };
  12018. AbstractMesh.prototype._checkCollision = function (collider) {
  12019. // Bounding box test
  12020. if (!this._boundingInfo._checkCollision(collider))
  12021. return this;
  12022. // Transformation matrix
  12023. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  12024. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  12025. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  12026. return this;
  12027. };
  12028. // Picking
  12029. AbstractMesh.prototype._generatePointsArray = function () {
  12030. return false;
  12031. };
  12032. /**
  12033. * Checks if the passed Ray intersects with the mesh.
  12034. * Returns an object PickingInfo.
  12035. */
  12036. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  12037. var pickingInfo = new BABYLON.PickingInfo();
  12038. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  12039. return pickingInfo;
  12040. }
  12041. if (!this._generatePointsArray()) {
  12042. return pickingInfo;
  12043. }
  12044. var intersectInfo = null;
  12045. // Octrees
  12046. var subMeshes;
  12047. var len;
  12048. if (this._submeshesOctree && this.useOctreeForPicking) {
  12049. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  12050. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  12051. len = intersections.length;
  12052. subMeshes = intersections.data;
  12053. }
  12054. else {
  12055. subMeshes = this.subMeshes;
  12056. len = subMeshes.length;
  12057. }
  12058. for (var index = 0; index < len; index++) {
  12059. var subMesh = subMeshes[index];
  12060. // Bounding test
  12061. if (len > 1 && !subMesh.canIntersects(ray))
  12062. continue;
  12063. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  12064. if (currentIntersectInfo) {
  12065. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  12066. intersectInfo = currentIntersectInfo;
  12067. intersectInfo.subMeshId = index;
  12068. if (fastCheck) {
  12069. break;
  12070. }
  12071. }
  12072. }
  12073. }
  12074. if (intersectInfo) {
  12075. // Get picked point
  12076. var world = this.getWorldMatrix();
  12077. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  12078. var direction = ray.direction.clone();
  12079. direction = direction.scale(intersectInfo.distance);
  12080. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  12081. var pickedPoint = worldOrigin.add(worldDirection);
  12082. // Return result
  12083. pickingInfo.hit = true;
  12084. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  12085. pickingInfo.pickedPoint = pickedPoint;
  12086. pickingInfo.pickedMesh = this;
  12087. pickingInfo.bu = intersectInfo.bu;
  12088. pickingInfo.bv = intersectInfo.bv;
  12089. pickingInfo.faceId = intersectInfo.faceId;
  12090. pickingInfo.subMeshId = intersectInfo.subMeshId;
  12091. return pickingInfo;
  12092. }
  12093. return pickingInfo;
  12094. };
  12095. /**
  12096. * Clones the mesh, used by the class Mesh.
  12097. * Just returns `null` for an AbstractMesh.
  12098. */
  12099. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  12100. return null;
  12101. };
  12102. /**
  12103. * Disposes all the mesh submeshes.
  12104. * Returns the AbstractMesh.
  12105. */
  12106. AbstractMesh.prototype.releaseSubMeshes = function () {
  12107. if (this.subMeshes) {
  12108. while (this.subMeshes.length) {
  12109. this.subMeshes[0].dispose();
  12110. }
  12111. }
  12112. else {
  12113. this.subMeshes = new Array();
  12114. }
  12115. return this;
  12116. };
  12117. /**
  12118. * Disposes the AbstractMesh.
  12119. * Some internal references are kept for further use.
  12120. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  12121. * Returns nothing.
  12122. */
  12123. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  12124. var _this = this;
  12125. var index;
  12126. // Action manager
  12127. if (this.actionManager) {
  12128. this.actionManager.dispose();
  12129. this.actionManager = null;
  12130. }
  12131. // Skeleton
  12132. this.skeleton = null;
  12133. // Animations
  12134. this.getScene().stopAnimation(this);
  12135. // Physics
  12136. if (this.physicsImpostor) {
  12137. this.physicsImpostor.dispose();
  12138. }
  12139. // Intersections in progress
  12140. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  12141. var other = this._intersectionsInProgress[index];
  12142. var pos = other._intersectionsInProgress.indexOf(this);
  12143. other._intersectionsInProgress.splice(pos, 1);
  12144. }
  12145. this._intersectionsInProgress = [];
  12146. // Lights
  12147. var lights = this.getScene().lights;
  12148. lights.forEach(function (light) {
  12149. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  12150. if (meshIndex !== -1) {
  12151. light.includedOnlyMeshes.splice(meshIndex, 1);
  12152. }
  12153. meshIndex = light.excludedMeshes.indexOf(_this);
  12154. if (meshIndex !== -1) {
  12155. light.excludedMeshes.splice(meshIndex, 1);
  12156. }
  12157. // Shadow generators
  12158. var generator = light.getShadowGenerator();
  12159. if (generator) {
  12160. meshIndex = generator.getShadowMap().renderList.indexOf(_this);
  12161. if (meshIndex !== -1) {
  12162. generator.getShadowMap().renderList.splice(meshIndex, 1);
  12163. }
  12164. }
  12165. });
  12166. // Edges
  12167. if (this._edgesRenderer) {
  12168. this._edgesRenderer.dispose();
  12169. this._edgesRenderer = null;
  12170. }
  12171. // SubMeshes
  12172. if (this.getClassName() !== "InstancedMesh") {
  12173. this.releaseSubMeshes();
  12174. }
  12175. // Octree
  12176. var sceneOctree = this.getScene().selectionOctree;
  12177. if (sceneOctree) {
  12178. var index = sceneOctree.dynamicContent.indexOf(this);
  12179. if (index !== -1) {
  12180. sceneOctree.dynamicContent.splice(index, 1);
  12181. }
  12182. }
  12183. // Engine
  12184. this.getScene().getEngine().wipeCaches();
  12185. // Remove from scene
  12186. this.getScene().removeMesh(this);
  12187. if (!doNotRecurse) {
  12188. // Particles
  12189. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  12190. if (this.getScene().particleSystems[index].emitter === this) {
  12191. this.getScene().particleSystems[index].dispose();
  12192. index--;
  12193. }
  12194. }
  12195. // Children
  12196. var objects = this.getDescendants(true);
  12197. for (index = 0; index < objects.length; index++) {
  12198. objects[index].dispose();
  12199. }
  12200. }
  12201. else {
  12202. var childMeshes = this.getChildMeshes(true);
  12203. for (index = 0; index < childMeshes.length; index++) {
  12204. var child = childMeshes[index];
  12205. child.parent = null;
  12206. child.computeWorldMatrix(true);
  12207. }
  12208. }
  12209. // facet data
  12210. if (this._facetDataEnabled) {
  12211. this.disableFacetData();
  12212. }
  12213. this.onAfterWorldMatrixUpdateObservable.clear();
  12214. this.onCollideObservable.clear();
  12215. this.onCollisionPositionChangeObservable.clear();
  12216. this._isDisposed = true;
  12217. _super.prototype.dispose.call(this);
  12218. };
  12219. /**
  12220. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  12221. * This Vector3 is expressed in the World space.
  12222. */
  12223. AbstractMesh.prototype.getDirection = function (localAxis) {
  12224. var result = BABYLON.Vector3.Zero();
  12225. this.getDirectionToRef(localAxis, result);
  12226. return result;
  12227. };
  12228. /**
  12229. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  12230. * localAxis is expressed in the mesh local space.
  12231. * result is computed in the Wordl space from the mesh World matrix.
  12232. * Returns the AbstractMesh.
  12233. */
  12234. AbstractMesh.prototype.getDirectionToRef = function (localAxis, result) {
  12235. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  12236. return this;
  12237. };
  12238. AbstractMesh.prototype.setPivotPoint = function (point, space) {
  12239. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  12240. if (this.getScene().getRenderId() == 0) {
  12241. this.computeWorldMatrix(true);
  12242. }
  12243. var wm = this.getWorldMatrix();
  12244. if (space == BABYLON.Space.WORLD) {
  12245. var tmat = BABYLON.Tmp.Matrix[0];
  12246. wm.invertToRef(tmat);
  12247. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  12248. }
  12249. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  12250. this._pivotMatrix.m[12] = -point.x;
  12251. this._pivotMatrix.m[13] = -point.y;
  12252. this._pivotMatrix.m[14] = -point.z;
  12253. this._cache.pivotMatrixUpdated = true;
  12254. return this;
  12255. };
  12256. /**
  12257. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  12258. */
  12259. AbstractMesh.prototype.getPivotPoint = function () {
  12260. var point = BABYLON.Vector3.Zero();
  12261. this.getPivotPointToRef(point);
  12262. return point;
  12263. };
  12264. /**
  12265. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  12266. * Returns the AbstractMesh.
  12267. */
  12268. AbstractMesh.prototype.getPivotPointToRef = function (result) {
  12269. result.x = -this._pivotMatrix.m[12];
  12270. result.y = -this._pivotMatrix.m[13];
  12271. result.z = -this._pivotMatrix.m[14];
  12272. return this;
  12273. };
  12274. /**
  12275. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  12276. */
  12277. AbstractMesh.prototype.getAbsolutePivotPoint = function () {
  12278. var point = BABYLON.Vector3.Zero();
  12279. this.getAbsolutePivotPointToRef(point);
  12280. return point;
  12281. };
  12282. /**
  12283. * Defines the passed mesh as the parent of the current mesh.
  12284. * Returns the AbstractMesh.
  12285. */
  12286. AbstractMesh.prototype.setParent = function (mesh) {
  12287. var child = this;
  12288. var parent = mesh;
  12289. if (mesh == null) {
  12290. var rotation = BABYLON.Tmp.Quaternion[0];
  12291. var position = BABYLON.Tmp.Vector3[0];
  12292. var scale = BABYLON.Tmp.Vector3[1];
  12293. child.getWorldMatrix().decompose(scale, rotation, position);
  12294. if (child.rotationQuaternion) {
  12295. child.rotationQuaternion.copyFrom(rotation);
  12296. }
  12297. else {
  12298. rotation.toEulerAnglesToRef(child.rotation);
  12299. }
  12300. child.position.x = position.x;
  12301. child.position.y = position.y;
  12302. child.position.z = position.z;
  12303. }
  12304. else {
  12305. var rotation = BABYLON.Tmp.Quaternion[0];
  12306. var position = BABYLON.Tmp.Vector3[0];
  12307. var scale = BABYLON.Tmp.Vector3[1];
  12308. var m1 = BABYLON.Tmp.Matrix[0];
  12309. var m2 = BABYLON.Tmp.Matrix[1];
  12310. parent.getWorldMatrix().decompose(scale, rotation, position);
  12311. rotation.toRotationMatrix(m1);
  12312. m2.setTranslation(position);
  12313. m2.multiplyToRef(m1, m1);
  12314. var invParentMatrix = BABYLON.Matrix.Invert(m1);
  12315. var m = child.getWorldMatrix().multiply(invParentMatrix);
  12316. m.decompose(scale, rotation, position);
  12317. if (child.rotationQuaternion) {
  12318. child.rotationQuaternion.copyFrom(rotation);
  12319. }
  12320. else {
  12321. rotation.toEulerAnglesToRef(child.rotation);
  12322. }
  12323. invParentMatrix = BABYLON.Matrix.Invert(parent.getWorldMatrix());
  12324. var m = child.getWorldMatrix().multiply(invParentMatrix);
  12325. m.decompose(scale, rotation, position);
  12326. child.position.x = position.x;
  12327. child.position.y = position.y;
  12328. child.position.z = position.z;
  12329. }
  12330. child.parent = parent;
  12331. return this;
  12332. };
  12333. /**
  12334. * Adds the passed mesh as a child to the current mesh.
  12335. * Returns the AbstractMesh.
  12336. */
  12337. AbstractMesh.prototype.addChild = function (mesh) {
  12338. mesh.setParent(this);
  12339. return this;
  12340. };
  12341. /**
  12342. * Removes the passed mesh from the current mesh children list.
  12343. * Returns the AbstractMesh.
  12344. */
  12345. AbstractMesh.prototype.removeChild = function (mesh) {
  12346. mesh.setParent(null);
  12347. return this;
  12348. };
  12349. /**
  12350. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  12351. * Returns the AbstractMesh.
  12352. */
  12353. AbstractMesh.prototype.getAbsolutePivotPointToRef = function (result) {
  12354. result.x = this._pivotMatrix.m[12];
  12355. result.y = this._pivotMatrix.m[13];
  12356. result.z = this._pivotMatrix.m[14];
  12357. this.getPivotPointToRef(result);
  12358. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  12359. return this;
  12360. };
  12361. // Facet data
  12362. /**
  12363. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  12364. * Returns the AbstractMesh.
  12365. */
  12366. AbstractMesh.prototype._initFacetData = function () {
  12367. if (!this._facetNormals) {
  12368. this._facetNormals = new Array();
  12369. }
  12370. if (!this._facetPositions) {
  12371. this._facetPositions = new Array();
  12372. }
  12373. if (!this._facetPartitioning) {
  12374. this._facetPartitioning = new Array();
  12375. }
  12376. this._facetNb = this.getIndices().length / 3;
  12377. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  12378. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  12379. for (var f = 0; f < this._facetNb; f++) {
  12380. this._facetNormals[f] = BABYLON.Vector3.Zero();
  12381. this._facetPositions[f] = BABYLON.Vector3.Zero();
  12382. }
  12383. this._facetDataEnabled = true;
  12384. return this;
  12385. };
  12386. /**
  12387. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  12388. * This method can be called within the render loop.
  12389. * 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.
  12390. * Returns the AbstractMesh.
  12391. */
  12392. AbstractMesh.prototype.updateFacetData = function () {
  12393. if (!this._facetDataEnabled) {
  12394. this._initFacetData();
  12395. }
  12396. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  12397. var indices = this.getIndices();
  12398. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  12399. var bInfo = this.getBoundingInfo();
  12400. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  12401. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  12402. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  12403. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  12404. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  12405. this._subDiv.max = this._partitioningSubdivisions;
  12406. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  12407. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  12408. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  12409. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  12410. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  12411. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  12412. // set the parameters for ComputeNormals()
  12413. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  12414. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  12415. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  12416. this._facetParameters.bInfo = bInfo;
  12417. this._facetParameters.bbSize = this._bbSize;
  12418. this._facetParameters.subDiv = this._subDiv;
  12419. this._facetParameters.ratio = this.partitioningBBoxRatio;
  12420. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  12421. return this;
  12422. };
  12423. /**
  12424. * Returns the facetLocalNormals array.
  12425. * The normals are expressed in the mesh local space.
  12426. */
  12427. AbstractMesh.prototype.getFacetLocalNormals = function () {
  12428. if (!this._facetNormals) {
  12429. this.updateFacetData();
  12430. }
  12431. return this._facetNormals;
  12432. };
  12433. /**
  12434. * Returns the facetLocalPositions array.
  12435. * The facet positions are expressed in the mesh local space.
  12436. */
  12437. AbstractMesh.prototype.getFacetLocalPositions = function () {
  12438. if (!this._facetPositions) {
  12439. this.updateFacetData();
  12440. }
  12441. return this._facetPositions;
  12442. };
  12443. /**
  12444. * Returns the facetLocalPartioning array.
  12445. */
  12446. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  12447. if (!this._facetPartitioning) {
  12448. this.updateFacetData();
  12449. }
  12450. return this._facetPartitioning;
  12451. };
  12452. /**
  12453. * Returns the i-th facet position in the world system.
  12454. * This method allocates a new Vector3 per call.
  12455. */
  12456. AbstractMesh.prototype.getFacetPosition = function (i) {
  12457. var pos = BABYLON.Vector3.Zero();
  12458. this.getFacetPositionToRef(i, pos);
  12459. return pos;
  12460. };
  12461. /**
  12462. * Sets the reference Vector3 with the i-th facet position in the world system.
  12463. * Returns the AbstractMesh.
  12464. */
  12465. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  12466. var localPos = (this.getFacetLocalPositions())[i];
  12467. var world = this.getWorldMatrix();
  12468. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  12469. return this;
  12470. };
  12471. /**
  12472. * Returns the i-th facet normal in the world system.
  12473. * This method allocates a new Vector3 per call.
  12474. */
  12475. AbstractMesh.prototype.getFacetNormal = function (i) {
  12476. var norm = BABYLON.Vector3.Zero();
  12477. this.getFacetNormalToRef(i, norm);
  12478. return norm;
  12479. };
  12480. /**
  12481. * Sets the reference Vector3 with the i-th facet normal in the world system.
  12482. * Returns the AbstractMesh.
  12483. */
  12484. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  12485. var localNorm = (this.getFacetLocalNormals())[i];
  12486. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  12487. return this;
  12488. };
  12489. /**
  12490. * 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).
  12491. */
  12492. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  12493. var bInfo = this.getBoundingInfo();
  12494. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  12495. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  12496. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  12497. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  12498. return null;
  12499. }
  12500. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  12501. };
  12502. /**
  12503. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  12504. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  12505. * 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.
  12506. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  12507. * 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.
  12508. */
  12509. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  12510. if (checkFace === void 0) { checkFace = false; }
  12511. if (facing === void 0) { facing = true; }
  12512. var world = this.getWorldMatrix();
  12513. var invMat = BABYLON.Tmp.Matrix[5];
  12514. world.invertToRef(invMat);
  12515. var invVect = BABYLON.Tmp.Vector3[8];
  12516. var closest = null;
  12517. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  12518. closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  12519. if (projected) {
  12520. // tranform the local computed projected vector to world coordinates
  12521. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  12522. }
  12523. return closest;
  12524. };
  12525. /**
  12526. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  12527. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  12528. * 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.
  12529. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  12530. * 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.
  12531. */
  12532. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  12533. if (checkFace === void 0) { checkFace = false; }
  12534. if (facing === void 0) { facing = true; }
  12535. var closest = null;
  12536. var tmpx = 0.0;
  12537. var tmpy = 0.0;
  12538. var tmpz = 0.0;
  12539. var d = 0.0; // tmp dot facet normal * facet position
  12540. var t0 = 0.0;
  12541. var projx = 0.0;
  12542. var projy = 0.0;
  12543. var projz = 0.0;
  12544. // Get all the facets in the same partitioning block than (x, y, z)
  12545. var facetPositions = this.getFacetLocalPositions();
  12546. var facetNormals = this.getFacetLocalNormals();
  12547. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  12548. if (!facetsInBlock) {
  12549. return null;
  12550. }
  12551. // Get the closest facet to (x, y, z)
  12552. var shortest = Number.MAX_VALUE; // init distance vars
  12553. var tmpDistance = shortest;
  12554. var fib; // current facet in the block
  12555. var norm; // current facet normal
  12556. var p0; // current facet barycenter position
  12557. // loop on all the facets in the current partitioning block
  12558. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  12559. fib = facetsInBlock[idx];
  12560. norm = facetNormals[fib];
  12561. p0 = facetPositions[fib];
  12562. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  12563. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  12564. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  12565. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  12566. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  12567. projx = x + norm.x * t0;
  12568. projy = y + norm.y * t0;
  12569. projz = z + norm.z * t0;
  12570. tmpx = projx - x;
  12571. tmpy = projy - y;
  12572. tmpz = projz - z;
  12573. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  12574. if (tmpDistance < shortest) {
  12575. shortest = tmpDistance;
  12576. closest = fib;
  12577. if (projected) {
  12578. projected.x = projx;
  12579. projected.y = projy;
  12580. projected.z = projz;
  12581. }
  12582. }
  12583. }
  12584. }
  12585. return closest;
  12586. };
  12587. /**
  12588. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  12589. */
  12590. AbstractMesh.prototype.getFacetDataParameters = function () {
  12591. return this._facetParameters;
  12592. };
  12593. /**
  12594. * Disables the feature FacetData and frees the related memory.
  12595. * Returns the AbstractMesh.
  12596. */
  12597. AbstractMesh.prototype.disableFacetData = function () {
  12598. if (this._facetDataEnabled) {
  12599. this._facetDataEnabled = false;
  12600. this._facetPositions = null;
  12601. this._facetNormals = null;
  12602. this._facetPartitioning = null;
  12603. this._facetParameters = null;
  12604. }
  12605. return this;
  12606. };
  12607. /**
  12608. * Creates new normals data for the mesh.
  12609. * @param updatable.
  12610. */
  12611. AbstractMesh.prototype.createNormals = function (updatable) {
  12612. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  12613. var indices = this.getIndices();
  12614. var normals;
  12615. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  12616. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  12617. }
  12618. else {
  12619. normals = [];
  12620. }
  12621. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  12622. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  12623. };
  12624. return AbstractMesh;
  12625. }(BABYLON.Node));
  12626. // Statics
  12627. AbstractMesh._BILLBOARDMODE_NONE = 0;
  12628. AbstractMesh._BILLBOARDMODE_X = 1;
  12629. AbstractMesh._BILLBOARDMODE_Y = 2;
  12630. AbstractMesh._BILLBOARDMODE_Z = 4;
  12631. AbstractMesh._BILLBOARDMODE_ALL = 7;
  12632. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  12633. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  12634. BABYLON.AbstractMesh = AbstractMesh;
  12635. })(BABYLON || (BABYLON = {}));
  12636. //# sourceMappingURL=babylon.abstractMesh.js.map
  12637. var BABYLON;
  12638. (function (BABYLON) {
  12639. var Light = (function (_super) {
  12640. __extends(Light, _super);
  12641. /**
  12642. * Creates a Light object in the scene.
  12643. * Documentation : http://doc.babylonjs.com/tutorials/lights
  12644. */
  12645. function Light(name, scene) {
  12646. var _this = _super.call(this, name, scene) || this;
  12647. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  12648. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  12649. _this.intensity = 1.0;
  12650. _this.range = Number.MAX_VALUE;
  12651. _this._excludeWithLayerMask = 0;
  12652. _this._includeOnlyWithLayerMask = 0;
  12653. _this._lightmapMode = 0;
  12654. // PBR Properties.
  12655. _this.radius = 0.00001;
  12656. _this._excludedMeshesIds = new Array();
  12657. _this._includedOnlyMeshesIds = new Array();
  12658. _this.getScene().addLight(_this);
  12659. _this._uniformBuffer = new BABYLON.UniformBuffer(scene.getEngine());
  12660. _this._buildUniformLayout();
  12661. _this.includedOnlyMeshes = new Array();
  12662. _this.excludedMeshes = new Array();
  12663. _this._resyncMeshes();
  12664. return _this;
  12665. }
  12666. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  12667. /**
  12668. * If every light affecting the material is in this lightmapMode,
  12669. * material.lightmapTexture adds or multiplies
  12670. * (depends on material.useLightmapAsShadowmap)
  12671. * after every other light calculations.
  12672. */
  12673. get: function () {
  12674. return Light._LIGHTMAP_DEFAULT;
  12675. },
  12676. enumerable: true,
  12677. configurable: true
  12678. });
  12679. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  12680. /**
  12681. * material.lightmapTexture as only diffuse lighting from this light
  12682. * adds pnly specular lighting from this light
  12683. * adds dynamic shadows
  12684. */
  12685. get: function () {
  12686. return Light._LIGHTMAP_SPECULAR;
  12687. },
  12688. enumerable: true,
  12689. configurable: true
  12690. });
  12691. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  12692. /**
  12693. * material.lightmapTexture as only lighting
  12694. * no light calculation from this light
  12695. * only adds dynamic shadows from this light
  12696. */
  12697. get: function () {
  12698. return Light._LIGHTMAP_SHADOWSONLY;
  12699. },
  12700. enumerable: true,
  12701. configurable: true
  12702. });
  12703. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  12704. get: function () {
  12705. return this._includedOnlyMeshes;
  12706. },
  12707. set: function (value) {
  12708. this._includedOnlyMeshes = value;
  12709. this._hookArrayForIncludedOnly(value);
  12710. },
  12711. enumerable: true,
  12712. configurable: true
  12713. });
  12714. Object.defineProperty(Light.prototype, "excludedMeshes", {
  12715. get: function () {
  12716. return this._excludedMeshes;
  12717. },
  12718. set: function (value) {
  12719. this._excludedMeshes = value;
  12720. this._hookArrayForExcluded(value);
  12721. },
  12722. enumerable: true,
  12723. configurable: true
  12724. });
  12725. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  12726. get: function () {
  12727. return this._excludeWithLayerMask;
  12728. },
  12729. set: function (value) {
  12730. this._excludeWithLayerMask = value;
  12731. this._resyncMeshes();
  12732. },
  12733. enumerable: true,
  12734. configurable: true
  12735. });
  12736. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  12737. get: function () {
  12738. return this._includeOnlyWithLayerMask;
  12739. },
  12740. set: function (value) {
  12741. this._includeOnlyWithLayerMask = value;
  12742. this._resyncMeshes();
  12743. },
  12744. enumerable: true,
  12745. configurable: true
  12746. });
  12747. Object.defineProperty(Light.prototype, "lightmapMode", {
  12748. get: function () {
  12749. return this._lightmapMode;
  12750. },
  12751. set: function (value) {
  12752. if (this._lightmapMode === value) {
  12753. return;
  12754. }
  12755. this._lightmapMode = value;
  12756. this._markMeshesAsLightDirty();
  12757. },
  12758. enumerable: true,
  12759. configurable: true
  12760. });
  12761. Light.prototype._buildUniformLayout = function () {
  12762. // Overridden
  12763. };
  12764. /**
  12765. * Returns the string "Light".
  12766. */
  12767. Light.prototype.getClassName = function () {
  12768. return "Light";
  12769. };
  12770. /**
  12771. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  12772. */
  12773. Light.prototype.toString = function (fullDetails) {
  12774. var ret = "Name: " + this.name;
  12775. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  12776. if (this.animations) {
  12777. for (var i = 0; i < this.animations.length; i++) {
  12778. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  12779. }
  12780. }
  12781. if (fullDetails) {
  12782. }
  12783. return ret;
  12784. };
  12785. /**
  12786. * Set the enabled state of this node.
  12787. * @param {boolean} value - the new enabled state
  12788. * @see isEnabled
  12789. */
  12790. Light.prototype.setEnabled = function (value) {
  12791. _super.prototype.setEnabled.call(this, value);
  12792. this._resyncMeshes();
  12793. };
  12794. /**
  12795. * Returns the Light associated shadow generator.
  12796. */
  12797. Light.prototype.getShadowGenerator = function () {
  12798. return this._shadowGenerator;
  12799. };
  12800. /**
  12801. * Returns a Vector3, the absolute light position in the World.
  12802. */
  12803. Light.prototype.getAbsolutePosition = function () {
  12804. return BABYLON.Vector3.Zero();
  12805. };
  12806. Light.prototype.transferToEffect = function (effect, lightIndex) {
  12807. };
  12808. Light.prototype._getWorldMatrix = function () {
  12809. return BABYLON.Matrix.Identity();
  12810. };
  12811. /**
  12812. * Boolean : True if the light will affect the passed mesh.
  12813. */
  12814. Light.prototype.canAffectMesh = function (mesh) {
  12815. if (!mesh) {
  12816. return true;
  12817. }
  12818. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  12819. return false;
  12820. }
  12821. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  12822. return false;
  12823. }
  12824. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  12825. return false;
  12826. }
  12827. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  12828. return false;
  12829. }
  12830. return true;
  12831. };
  12832. /**
  12833. * Returns the light World matrix.
  12834. */
  12835. Light.prototype.getWorldMatrix = function () {
  12836. this._currentRenderId = this.getScene().getRenderId();
  12837. var worldMatrix = this._getWorldMatrix();
  12838. if (this.parent && this.parent.getWorldMatrix) {
  12839. if (!this._parentedWorldMatrix) {
  12840. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  12841. }
  12842. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  12843. this._markSyncedWithParent();
  12844. return this._parentedWorldMatrix;
  12845. }
  12846. return worldMatrix;
  12847. };
  12848. /**
  12849. * Disposes the light.
  12850. */
  12851. Light.prototype.dispose = function () {
  12852. if (this._shadowGenerator) {
  12853. this._shadowGenerator.dispose();
  12854. this._shadowGenerator = null;
  12855. }
  12856. // Animations
  12857. this.getScene().stopAnimation(this);
  12858. // Remove from meshes
  12859. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  12860. var mesh = _a[_i];
  12861. mesh._removeLightSource(this);
  12862. }
  12863. this._uniformBuffer.dispose();
  12864. // Remove from scene
  12865. this.getScene().removeLight(this);
  12866. _super.prototype.dispose.call(this);
  12867. };
  12868. /**
  12869. * Returns the light type ID (integer).
  12870. */
  12871. Light.prototype.getTypeID = function () {
  12872. return 0;
  12873. };
  12874. /**
  12875. * Returns a new Light object, named "name", from the current one.
  12876. */
  12877. Light.prototype.clone = function (name) {
  12878. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  12879. };
  12880. /**
  12881. * Serializes the current light into a Serialization object.
  12882. * Returns the serialized object.
  12883. */
  12884. Light.prototype.serialize = function () {
  12885. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  12886. // Type
  12887. serializationObject.type = this.getTypeID();
  12888. // Parent
  12889. if (this.parent) {
  12890. serializationObject.parentId = this.parent.id;
  12891. }
  12892. // Inclusion / exclusions
  12893. if (this.excludedMeshes.length > 0) {
  12894. serializationObject.excludedMeshesIds = [];
  12895. this.excludedMeshes.forEach(function (mesh) {
  12896. serializationObject.excludedMeshesIds.push(mesh.id);
  12897. });
  12898. }
  12899. if (this.includedOnlyMeshes.length > 0) {
  12900. serializationObject.includedOnlyMeshesIds = [];
  12901. this.includedOnlyMeshes.forEach(function (mesh) {
  12902. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  12903. });
  12904. }
  12905. // Animations
  12906. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  12907. serializationObject.ranges = this.serializeAnimationRanges();
  12908. return serializationObject;
  12909. };
  12910. /**
  12911. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  12912. * This new light is named "name" and added to the passed scene.
  12913. */
  12914. Light.GetConstructorFromName = function (type, name, scene) {
  12915. switch (type) {
  12916. case 0:
  12917. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  12918. case 1:
  12919. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  12920. case 2:
  12921. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  12922. case 3:
  12923. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  12924. }
  12925. };
  12926. /**
  12927. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  12928. */
  12929. Light.Parse = function (parsedLight, scene) {
  12930. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  12931. // Inclusion / exclusions
  12932. if (parsedLight.excludedMeshesIds) {
  12933. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  12934. }
  12935. if (parsedLight.includedOnlyMeshesIds) {
  12936. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  12937. }
  12938. // Parent
  12939. if (parsedLight.parentId) {
  12940. light._waitingParentId = parsedLight.parentId;
  12941. }
  12942. // Animations
  12943. if (parsedLight.animations) {
  12944. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  12945. var parsedAnimation = parsedLight.animations[animationIndex];
  12946. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  12947. }
  12948. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  12949. }
  12950. if (parsedLight.autoAnimate) {
  12951. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  12952. }
  12953. return light;
  12954. };
  12955. Light.prototype._hookArrayForExcluded = function (array) {
  12956. var _this = this;
  12957. var oldPush = array.push;
  12958. array.push = function () {
  12959. var items = [];
  12960. for (var _i = 0; _i < arguments.length; _i++) {
  12961. items[_i] = arguments[_i];
  12962. }
  12963. var result = oldPush.apply(array, items);
  12964. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  12965. var item = items_1[_a];
  12966. item._resyncLighSource(_this);
  12967. }
  12968. return result;
  12969. };
  12970. var oldSplice = array.splice;
  12971. array.splice = function (index, deleteCount) {
  12972. var deleted = oldSplice.apply(array, [index, deleteCount]);
  12973. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  12974. var item = deleted_1[_i];
  12975. item._resyncLighSource(_this);
  12976. }
  12977. return deleted;
  12978. };
  12979. };
  12980. Light.prototype._hookArrayForIncludedOnly = function (array) {
  12981. var _this = this;
  12982. var oldPush = array.push;
  12983. array.push = function () {
  12984. var items = [];
  12985. for (var _i = 0; _i < arguments.length; _i++) {
  12986. items[_i] = arguments[_i];
  12987. }
  12988. var result = oldPush.apply(array, items);
  12989. _this._resyncMeshes();
  12990. return result;
  12991. };
  12992. var oldSplice = array.splice;
  12993. array.splice = function (index, deleteCount) {
  12994. var deleted = oldSplice.apply(array, [index, deleteCount]);
  12995. _this._resyncMeshes();
  12996. return deleted;
  12997. };
  12998. };
  12999. Light.prototype._resyncMeshes = function () {
  13000. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  13001. var mesh = _a[_i];
  13002. mesh._resyncLighSource(this);
  13003. }
  13004. };
  13005. Light.prototype._markMeshesAsLightDirty = function () {
  13006. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  13007. var mesh = _a[_i];
  13008. if (mesh._lightSources.indexOf(this) !== -1) {
  13009. mesh._markSubMeshesAsLightDirty();
  13010. }
  13011. }
  13012. };
  13013. return Light;
  13014. }(BABYLON.Node));
  13015. //lightmapMode Consts
  13016. Light._LIGHTMAP_DEFAULT = 0;
  13017. Light._LIGHTMAP_SPECULAR = 1;
  13018. Light._LIGHTMAP_SHADOWSONLY = 2;
  13019. __decorate([
  13020. BABYLON.serializeAsColor3()
  13021. ], Light.prototype, "diffuse", void 0);
  13022. __decorate([
  13023. BABYLON.serializeAsColor3()
  13024. ], Light.prototype, "specular", void 0);
  13025. __decorate([
  13026. BABYLON.serialize()
  13027. ], Light.prototype, "intensity", void 0);
  13028. __decorate([
  13029. BABYLON.serialize()
  13030. ], Light.prototype, "range", void 0);
  13031. __decorate([
  13032. BABYLON.serialize("excludeWithLayerMask")
  13033. ], Light.prototype, "_excludeWithLayerMask", void 0);
  13034. __decorate([
  13035. BABYLON.serialize("includeOnlyWithLayerMask")
  13036. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  13037. __decorate([
  13038. BABYLON.serialize("lightmapMode")
  13039. ], Light.prototype, "_lightmapMode", void 0);
  13040. __decorate([
  13041. BABYLON.serialize()
  13042. ], Light.prototype, "radius", void 0);
  13043. BABYLON.Light = Light;
  13044. })(BABYLON || (BABYLON = {}));
  13045. //# sourceMappingURL=babylon.light.js.map
  13046. var BABYLON;
  13047. (function (BABYLON) {
  13048. var Camera = (function (_super) {
  13049. __extends(Camera, _super);
  13050. function Camera(name, position, scene) {
  13051. var _this = _super.call(this, name, scene) || this;
  13052. _this.upVector = BABYLON.Vector3.Up();
  13053. _this.orthoLeft = null;
  13054. _this.orthoRight = null;
  13055. _this.orthoBottom = null;
  13056. _this.orthoTop = null;
  13057. _this.fov = 0.8;
  13058. _this.minZ = 1.0;
  13059. _this.maxZ = 10000.0;
  13060. _this.inertia = 0.9;
  13061. _this.mode = Camera.PERSPECTIVE_CAMERA;
  13062. _this.isIntermediate = false;
  13063. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  13064. _this.layerMask = 0x0FFFFFFF;
  13065. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  13066. // Camera rig members
  13067. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  13068. _this._rigCameras = new Array();
  13069. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  13070. // Cache
  13071. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  13072. _this._projectionMatrix = new BABYLON.Matrix();
  13073. _this._doNotComputeProjectionMatrix = false;
  13074. _this._postProcesses = new Array();
  13075. _this._transformMatrix = BABYLON.Matrix.Zero();
  13076. _this._activeMeshes = new BABYLON.SmartArray(256);
  13077. _this._globalPosition = BABYLON.Vector3.Zero();
  13078. _this._refreshFrustumPlanes = true;
  13079. _this.getScene().addCamera(_this);
  13080. if (!_this.getScene().activeCamera) {
  13081. _this.getScene().activeCamera = _this;
  13082. }
  13083. _this.position = position;
  13084. return _this;
  13085. }
  13086. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  13087. get: function () {
  13088. return Camera._PERSPECTIVE_CAMERA;
  13089. },
  13090. enumerable: true,
  13091. configurable: true
  13092. });
  13093. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  13094. get: function () {
  13095. return Camera._ORTHOGRAPHIC_CAMERA;
  13096. },
  13097. enumerable: true,
  13098. configurable: true
  13099. });
  13100. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  13101. get: function () {
  13102. return Camera._FOVMODE_VERTICAL_FIXED;
  13103. },
  13104. enumerable: true,
  13105. configurable: true
  13106. });
  13107. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  13108. get: function () {
  13109. return Camera._FOVMODE_HORIZONTAL_FIXED;
  13110. },
  13111. enumerable: true,
  13112. configurable: true
  13113. });
  13114. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  13115. get: function () {
  13116. return Camera._RIG_MODE_NONE;
  13117. },
  13118. enumerable: true,
  13119. configurable: true
  13120. });
  13121. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  13122. get: function () {
  13123. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  13124. },
  13125. enumerable: true,
  13126. configurable: true
  13127. });
  13128. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  13129. get: function () {
  13130. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  13131. },
  13132. enumerable: true,
  13133. configurable: true
  13134. });
  13135. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  13136. get: function () {
  13137. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  13138. },
  13139. enumerable: true,
  13140. configurable: true
  13141. });
  13142. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  13143. get: function () {
  13144. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  13145. },
  13146. enumerable: true,
  13147. configurable: true
  13148. });
  13149. Object.defineProperty(Camera, "RIG_MODE_VR", {
  13150. get: function () {
  13151. return Camera._RIG_MODE_VR;
  13152. },
  13153. enumerable: true,
  13154. configurable: true
  13155. });
  13156. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  13157. get: function () {
  13158. return Camera._RIG_MODE_WEBVR;
  13159. },
  13160. enumerable: true,
  13161. configurable: true
  13162. });
  13163. Camera.prototype.getClassName = function () {
  13164. return "Camera";
  13165. };
  13166. /**
  13167. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  13168. */
  13169. Camera.prototype.toString = function (fullDetails) {
  13170. var ret = "Name: " + this.name;
  13171. ret += ", type: " + this.getClassName();
  13172. if (this.animations) {
  13173. for (var i = 0; i < this.animations.length; i++) {
  13174. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  13175. }
  13176. }
  13177. if (fullDetails) {
  13178. }
  13179. return ret;
  13180. };
  13181. Object.defineProperty(Camera.prototype, "globalPosition", {
  13182. get: function () {
  13183. return this._globalPosition;
  13184. },
  13185. enumerable: true,
  13186. configurable: true
  13187. });
  13188. Camera.prototype.getActiveMeshes = function () {
  13189. return this._activeMeshes;
  13190. };
  13191. Camera.prototype.isActiveMesh = function (mesh) {
  13192. return (this._activeMeshes.indexOf(mesh) !== -1);
  13193. };
  13194. //Cache
  13195. Camera.prototype._initCache = function () {
  13196. _super.prototype._initCache.call(this);
  13197. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13198. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13199. this._cache.mode = undefined;
  13200. this._cache.minZ = undefined;
  13201. this._cache.maxZ = undefined;
  13202. this._cache.fov = undefined;
  13203. this._cache.fovMode = undefined;
  13204. this._cache.aspectRatio = undefined;
  13205. this._cache.orthoLeft = undefined;
  13206. this._cache.orthoRight = undefined;
  13207. this._cache.orthoBottom = undefined;
  13208. this._cache.orthoTop = undefined;
  13209. this._cache.renderWidth = undefined;
  13210. this._cache.renderHeight = undefined;
  13211. };
  13212. Camera.prototype._updateCache = function (ignoreParentClass) {
  13213. if (!ignoreParentClass) {
  13214. _super.prototype._updateCache.call(this);
  13215. }
  13216. var engine = this.getEngine();
  13217. this._cache.position.copyFrom(this.position);
  13218. this._cache.upVector.copyFrom(this.upVector);
  13219. this._cache.mode = this.mode;
  13220. this._cache.minZ = this.minZ;
  13221. this._cache.maxZ = this.maxZ;
  13222. this._cache.fov = this.fov;
  13223. this._cache.fovMode = this.fovMode;
  13224. this._cache.aspectRatio = engine.getAspectRatio(this);
  13225. this._cache.orthoLeft = this.orthoLeft;
  13226. this._cache.orthoRight = this.orthoRight;
  13227. this._cache.orthoBottom = this.orthoBottom;
  13228. this._cache.orthoTop = this.orthoTop;
  13229. this._cache.renderWidth = engine.getRenderWidth();
  13230. this._cache.renderHeight = engine.getRenderHeight();
  13231. };
  13232. Camera.prototype._updateFromScene = function () {
  13233. this.updateCache();
  13234. this.update();
  13235. };
  13236. // Synchronized
  13237. Camera.prototype._isSynchronized = function () {
  13238. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  13239. };
  13240. Camera.prototype._isSynchronizedViewMatrix = function () {
  13241. if (!_super.prototype._isSynchronized.call(this))
  13242. return false;
  13243. return this._cache.position.equals(this.position)
  13244. && this._cache.upVector.equals(this.upVector)
  13245. && this.isSynchronizedWithParent();
  13246. };
  13247. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  13248. var check = this._cache.mode === this.mode
  13249. && this._cache.minZ === this.minZ
  13250. && this._cache.maxZ === this.maxZ;
  13251. if (!check) {
  13252. return false;
  13253. }
  13254. var engine = this.getEngine();
  13255. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  13256. check = this._cache.fov === this.fov
  13257. && this._cache.fovMode === this.fovMode
  13258. && this._cache.aspectRatio === engine.getAspectRatio(this);
  13259. }
  13260. else {
  13261. check = this._cache.orthoLeft === this.orthoLeft
  13262. && this._cache.orthoRight === this.orthoRight
  13263. && this._cache.orthoBottom === this.orthoBottom
  13264. && this._cache.orthoTop === this.orthoTop
  13265. && this._cache.renderWidth === engine.getRenderWidth()
  13266. && this._cache.renderHeight === engine.getRenderHeight();
  13267. }
  13268. return check;
  13269. };
  13270. // Controls
  13271. Camera.prototype.attachControl = function (element, noPreventDefault) {
  13272. };
  13273. Camera.prototype.detachControl = function (element) {
  13274. };
  13275. Camera.prototype.update = function () {
  13276. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  13277. this._updateRigCameras();
  13278. }
  13279. this._checkInputs();
  13280. };
  13281. Camera.prototype._checkInputs = function () {
  13282. };
  13283. Object.defineProperty(Camera.prototype, "rigCameras", {
  13284. get: function () {
  13285. return this._rigCameras;
  13286. },
  13287. enumerable: true,
  13288. configurable: true
  13289. });
  13290. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  13291. get: function () {
  13292. return this._rigPostProcess;
  13293. },
  13294. enumerable: true,
  13295. configurable: true
  13296. });
  13297. Camera.prototype._cascadePostProcessesToRigCams = function () {
  13298. // invalidate framebuffer
  13299. if (this._postProcesses.length > 0) {
  13300. this._postProcesses[0].markTextureDirty();
  13301. }
  13302. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  13303. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  13304. var cam = this._rigCameras[i];
  13305. var rigPostProcess = cam._rigPostProcess;
  13306. // for VR rig, there does not have to be a post process
  13307. if (rigPostProcess) {
  13308. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  13309. if (isPass) {
  13310. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  13311. cam.isIntermediate = this._postProcesses.length === 0;
  13312. }
  13313. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  13314. rigPostProcess.markTextureDirty();
  13315. }
  13316. else {
  13317. cam._postProcesses = this._postProcesses.slice(0);
  13318. }
  13319. }
  13320. };
  13321. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  13322. if (insertAt === void 0) { insertAt = null; }
  13323. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  13324. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  13325. return 0;
  13326. }
  13327. if (insertAt == null || insertAt < 0) {
  13328. this._postProcesses.push(postProcess);
  13329. }
  13330. else {
  13331. this._postProcesses.splice(insertAt, 0, postProcess);
  13332. }
  13333. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  13334. return this._postProcesses.indexOf(postProcess);
  13335. };
  13336. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  13337. if (atIndices === void 0) { atIndices = null; }
  13338. var result = [];
  13339. var i;
  13340. var index;
  13341. if (!atIndices) {
  13342. var idx = this._postProcesses.indexOf(postProcess);
  13343. if (idx !== -1) {
  13344. this._postProcesses.splice(idx, 1);
  13345. }
  13346. }
  13347. else {
  13348. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  13349. // iterate descending, so can just splice as we go
  13350. for (i = atIndices.length - 1; i >= 0; i--) {
  13351. if (this._postProcesses[atIndices[i]] !== postProcess) {
  13352. result.push(i);
  13353. continue;
  13354. }
  13355. index = atIndices[i];
  13356. this._postProcesses.splice(index, 1);
  13357. }
  13358. }
  13359. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  13360. return result;
  13361. };
  13362. Camera.prototype.getWorldMatrix = function () {
  13363. if (!this._worldMatrix) {
  13364. this._worldMatrix = BABYLON.Matrix.Identity();
  13365. }
  13366. var viewMatrix = this.getViewMatrix();
  13367. viewMatrix.invertToRef(this._worldMatrix);
  13368. return this._worldMatrix;
  13369. };
  13370. Camera.prototype._getViewMatrix = function () {
  13371. return BABYLON.Matrix.Identity();
  13372. };
  13373. Camera.prototype.getViewMatrix = function (force) {
  13374. this._computedViewMatrix = this._computeViewMatrix(force);
  13375. if (!force && this._isSynchronizedViewMatrix()) {
  13376. return this._computedViewMatrix;
  13377. }
  13378. this._refreshFrustumPlanes = true;
  13379. if (!this.parent || !this.parent.getWorldMatrix) {
  13380. this._globalPosition.copyFrom(this.position);
  13381. }
  13382. else {
  13383. if (!this._worldMatrix) {
  13384. this._worldMatrix = BABYLON.Matrix.Identity();
  13385. }
  13386. this._computedViewMatrix.invertToRef(this._worldMatrix);
  13387. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  13388. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  13389. this._computedViewMatrix.invert();
  13390. this._markSyncedWithParent();
  13391. }
  13392. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  13393. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  13394. }
  13395. this._currentRenderId = this.getScene().getRenderId();
  13396. return this._computedViewMatrix;
  13397. };
  13398. Camera.prototype._computeViewMatrix = function (force) {
  13399. if (!force && this._isSynchronizedViewMatrix()) {
  13400. return this._computedViewMatrix;
  13401. }
  13402. this._computedViewMatrix = this._getViewMatrix();
  13403. this._currentRenderId = this.getScene().getRenderId();
  13404. return this._computedViewMatrix;
  13405. };
  13406. Camera.prototype.freezeProjectionMatrix = function (projection) {
  13407. this._doNotComputeProjectionMatrix = true;
  13408. if (projection !== undefined) {
  13409. this._projectionMatrix = projection;
  13410. }
  13411. };
  13412. ;
  13413. Camera.prototype.unfreezeProjectionMatrix = function () {
  13414. this._doNotComputeProjectionMatrix = false;
  13415. };
  13416. ;
  13417. Camera.prototype.getProjectionMatrix = function (force) {
  13418. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  13419. return this._projectionMatrix;
  13420. }
  13421. this._refreshFrustumPlanes = true;
  13422. var engine = this.getEngine();
  13423. var scene = this.getScene();
  13424. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  13425. if (this.minZ <= 0) {
  13426. this.minZ = 0.1;
  13427. }
  13428. if (scene.useRightHandedSystem) {
  13429. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  13430. }
  13431. else {
  13432. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  13433. }
  13434. return this._projectionMatrix;
  13435. }
  13436. var halfWidth = engine.getRenderWidth() / 2.0;
  13437. var halfHeight = engine.getRenderHeight() / 2.0;
  13438. if (scene.useRightHandedSystem) {
  13439. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  13440. }
  13441. else {
  13442. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  13443. }
  13444. return this._projectionMatrix;
  13445. };
  13446. Camera.prototype.getTranformationMatrix = function () {
  13447. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  13448. return this._transformMatrix;
  13449. };
  13450. Camera.prototype.updateFrustumPlanes = function () {
  13451. if (!this._refreshFrustumPlanes) {
  13452. return;
  13453. }
  13454. this.getTranformationMatrix();
  13455. if (!this._frustumPlanes) {
  13456. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  13457. }
  13458. else {
  13459. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  13460. }
  13461. this._refreshFrustumPlanes = false;
  13462. };
  13463. Camera.prototype.isInFrustum = function (target) {
  13464. this.updateFrustumPlanes();
  13465. return target.isInFrustum(this._frustumPlanes);
  13466. };
  13467. Camera.prototype.isCompletelyInFrustum = function (target) {
  13468. this.updateFrustumPlanes();
  13469. return target.isCompletelyInFrustum(this._frustumPlanes);
  13470. };
  13471. Camera.prototype.dispose = function () {
  13472. // Animations
  13473. this.getScene().stopAnimation(this);
  13474. // Remove from scene
  13475. this.getScene().removeCamera(this);
  13476. while (this._rigCameras.length > 0) {
  13477. this._rigCameras.pop().dispose();
  13478. }
  13479. // Postprocesses
  13480. var i = this._postProcesses.length;
  13481. while (--i >= 0) {
  13482. this._postProcesses[i].dispose(this);
  13483. }
  13484. _super.prototype.dispose.call(this);
  13485. };
  13486. // ---- Camera rigs section ----
  13487. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  13488. while (this._rigCameras.length > 0) {
  13489. this._rigCameras.pop().dispose();
  13490. }
  13491. this.cameraRigMode = mode;
  13492. this._cameraRigParams = {};
  13493. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  13494. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  13495. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  13496. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  13497. // create the rig cameras, unless none
  13498. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  13499. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  13500. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  13501. }
  13502. switch (this.cameraRigMode) {
  13503. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  13504. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  13505. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  13506. break;
  13507. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  13508. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  13509. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  13510. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  13511. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  13512. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  13513. break;
  13514. case Camera.RIG_MODE_VR:
  13515. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  13516. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  13517. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  13518. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  13519. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  13520. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  13521. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  13522. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  13523. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  13524. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  13525. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  13526. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  13527. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  13528. if (metrics.compensateDistortion) {
  13529. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  13530. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  13531. }
  13532. break;
  13533. case Camera.RIG_MODE_WEBVR:
  13534. if (rigParams.vrDisplay) {
  13535. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  13536. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  13537. //Left eye
  13538. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  13539. this._rigCameras[0].setCameraRigParameter("left", true);
  13540. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  13541. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  13542. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  13543. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  13544. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  13545. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  13546. this._rigCameras[0].parent = this;
  13547. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  13548. //Right eye
  13549. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  13550. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  13551. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  13552. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  13553. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  13554. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  13555. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  13556. this._rigCameras[1].parent = this;
  13557. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  13558. }
  13559. break;
  13560. }
  13561. this._cascadePostProcessesToRigCams();
  13562. this.
  13563. update();
  13564. };
  13565. Camera.prototype._getVRProjectionMatrix = function () {
  13566. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  13567. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  13568. return this._projectionMatrix;
  13569. };
  13570. Camera.prototype._updateCameraRotationMatrix = function () {
  13571. //Here for WebVR
  13572. };
  13573. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  13574. //Here for WebVR
  13575. };
  13576. /**
  13577. * This function MUST be overwritten by the different WebVR cameras available.
  13578. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  13579. */
  13580. Camera.prototype._getWebVRProjectionMatrix = function () {
  13581. return BABYLON.Matrix.Identity();
  13582. };
  13583. /**
  13584. * This function MUST be overwritten by the different WebVR cameras available.
  13585. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  13586. */
  13587. Camera.prototype._getWebVRViewMatrix = function () {
  13588. return BABYLON.Matrix.Identity();
  13589. };
  13590. Camera.prototype.setCameraRigParameter = function (name, value) {
  13591. if (!this._cameraRigParams) {
  13592. this._cameraRigParams = {};
  13593. }
  13594. this._cameraRigParams[name] = value;
  13595. //provisionnally:
  13596. if (name === "interaxialDistance") {
  13597. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  13598. }
  13599. };
  13600. /**
  13601. * needs to be overridden by children so sub has required properties to be copied
  13602. */
  13603. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  13604. return null;
  13605. };
  13606. /**
  13607. * May need to be overridden by children
  13608. */
  13609. Camera.prototype._updateRigCameras = function () {
  13610. for (var i = 0; i < this._rigCameras.length; i++) {
  13611. this._rigCameras[i].minZ = this.minZ;
  13612. this._rigCameras[i].maxZ = this.maxZ;
  13613. this._rigCameras[i].fov = this.fov;
  13614. }
  13615. // only update viewport when ANAGLYPH
  13616. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  13617. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  13618. }
  13619. };
  13620. Camera.prototype._setupInputs = function () {
  13621. };
  13622. Camera.prototype.serialize = function () {
  13623. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  13624. // Type
  13625. serializationObject.type = this.getClassName();
  13626. // Parent
  13627. if (this.parent) {
  13628. serializationObject.parentId = this.parent.id;
  13629. }
  13630. if (this.inputs) {
  13631. this.inputs.serialize(serializationObject);
  13632. }
  13633. // Animations
  13634. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  13635. serializationObject.ranges = this.serializeAnimationRanges();
  13636. return serializationObject;
  13637. };
  13638. Camera.prototype.clone = function (name) {
  13639. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  13640. };
  13641. Camera.prototype.getDirection = function (localAxis) {
  13642. var result = BABYLON.Vector3.Zero();
  13643. this.getDirectionToRef(localAxis, result);
  13644. return result;
  13645. };
  13646. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  13647. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  13648. };
  13649. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  13650. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  13651. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  13652. switch (type) {
  13653. case "ArcRotateCamera":
  13654. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  13655. case "DeviceOrientationCamera":
  13656. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  13657. case "FollowCamera":
  13658. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  13659. case "ArcFollowCamera":
  13660. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  13661. case "GamepadCamera":
  13662. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  13663. case "TouchCamera":
  13664. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  13665. case "VirtualJoysticksCamera":
  13666. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  13667. case "WebVRFreeCamera":
  13668. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  13669. case "WebVRGamepadCamera":
  13670. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  13671. case "VRDeviceOrientationFreeCamera":
  13672. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  13673. case "VRDeviceOrientationGamepadCamera":
  13674. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  13675. case "AnaglyphArcRotateCamera":
  13676. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  13677. case "AnaglyphFreeCamera":
  13678. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  13679. case "AnaglyphGamepadCamera":
  13680. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  13681. case "AnaglyphUniversalCamera":
  13682. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  13683. case "StereoscopicArcRotateCamera":
  13684. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  13685. case "StereoscopicFreeCamera":
  13686. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  13687. case "StereoscopicGamepadCamera":
  13688. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  13689. case "StereoscopicUniversalCamera":
  13690. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  13691. case "FreeCamera":
  13692. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  13693. default:
  13694. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  13695. }
  13696. };
  13697. Camera.Parse = function (parsedCamera, scene) {
  13698. var type = parsedCamera.type;
  13699. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  13700. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  13701. // Parent
  13702. if (parsedCamera.parentId) {
  13703. camera._waitingParentId = parsedCamera.parentId;
  13704. }
  13705. //If camera has an input manager, let it parse inputs settings
  13706. if (camera.inputs) {
  13707. camera.inputs.parse(parsedCamera);
  13708. camera._setupInputs();
  13709. }
  13710. // Target
  13711. if (parsedCamera.target) {
  13712. if (camera.setTarget) {
  13713. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  13714. }
  13715. }
  13716. // Apply 3d rig, when found
  13717. if (parsedCamera.cameraRigMode) {
  13718. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  13719. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  13720. }
  13721. // Animations
  13722. if (parsedCamera.animations) {
  13723. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  13724. var parsedAnimation = parsedCamera.animations[animationIndex];
  13725. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  13726. }
  13727. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  13728. }
  13729. if (parsedCamera.autoAnimate) {
  13730. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  13731. }
  13732. return camera;
  13733. };
  13734. return Camera;
  13735. }(BABYLON.Node));
  13736. // Statics
  13737. Camera._PERSPECTIVE_CAMERA = 0;
  13738. Camera._ORTHOGRAPHIC_CAMERA = 1;
  13739. Camera._FOVMODE_VERTICAL_FIXED = 0;
  13740. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  13741. Camera._RIG_MODE_NONE = 0;
  13742. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  13743. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  13744. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  13745. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  13746. Camera._RIG_MODE_VR = 20;
  13747. Camera._RIG_MODE_WEBVR = 21;
  13748. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  13749. __decorate([
  13750. BABYLON.serializeAsVector3()
  13751. ], Camera.prototype, "position", void 0);
  13752. __decorate([
  13753. BABYLON.serializeAsVector3()
  13754. ], Camera.prototype, "upVector", void 0);
  13755. __decorate([
  13756. BABYLON.serialize()
  13757. ], Camera.prototype, "orthoLeft", void 0);
  13758. __decorate([
  13759. BABYLON.serialize()
  13760. ], Camera.prototype, "orthoRight", void 0);
  13761. __decorate([
  13762. BABYLON.serialize()
  13763. ], Camera.prototype, "orthoBottom", void 0);
  13764. __decorate([
  13765. BABYLON.serialize()
  13766. ], Camera.prototype, "orthoTop", void 0);
  13767. __decorate([
  13768. BABYLON.serialize()
  13769. ], Camera.prototype, "fov", void 0);
  13770. __decorate([
  13771. BABYLON.serialize()
  13772. ], Camera.prototype, "minZ", void 0);
  13773. __decorate([
  13774. BABYLON.serialize()
  13775. ], Camera.prototype, "maxZ", void 0);
  13776. __decorate([
  13777. BABYLON.serialize()
  13778. ], Camera.prototype, "inertia", void 0);
  13779. __decorate([
  13780. BABYLON.serialize()
  13781. ], Camera.prototype, "mode", void 0);
  13782. __decorate([
  13783. BABYLON.serialize()
  13784. ], Camera.prototype, "layerMask", void 0);
  13785. __decorate([
  13786. BABYLON.serialize()
  13787. ], Camera.prototype, "fovMode", void 0);
  13788. __decorate([
  13789. BABYLON.serialize()
  13790. ], Camera.prototype, "cameraRigMode", void 0);
  13791. __decorate([
  13792. BABYLON.serialize()
  13793. ], Camera.prototype, "interaxialDistance", void 0);
  13794. __decorate([
  13795. BABYLON.serialize()
  13796. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  13797. BABYLON.Camera = Camera;
  13798. })(BABYLON || (BABYLON = {}));
  13799. //# sourceMappingURL=babylon.camera.js.map
  13800. var BABYLON;
  13801. (function (BABYLON) {
  13802. var RenderingManager = (function () {
  13803. function RenderingManager(scene) {
  13804. this._renderingGroups = new Array();
  13805. this._autoClearDepthStencil = {};
  13806. this._customOpaqueSortCompareFn = {};
  13807. this._customAlphaTestSortCompareFn = {};
  13808. this._customTransparentSortCompareFn = {};
  13809. this._renderinGroupInfo = null;
  13810. this._scene = scene;
  13811. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  13812. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  13813. }
  13814. }
  13815. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  13816. if (depth === void 0) { depth = true; }
  13817. if (stencil === void 0) { stencil = true; }
  13818. if (this._depthStencilBufferAlreadyCleaned) {
  13819. return;
  13820. }
  13821. this._scene.getEngine().clear(null, false, depth, stencil);
  13822. this._depthStencilBufferAlreadyCleaned = true;
  13823. };
  13824. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  13825. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  13826. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  13827. var info = null;
  13828. if (observable) {
  13829. if (!this._renderinGroupInfo) {
  13830. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  13831. }
  13832. info = this._renderinGroupInfo;
  13833. info.scene = this._scene;
  13834. info.camera = this._scene.activeCamera;
  13835. }
  13836. // Dispatch sprites
  13837. if (renderSprites) {
  13838. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  13839. var manager = this._scene.spriteManagers[index];
  13840. this.dispatchSprites(manager);
  13841. }
  13842. }
  13843. // Render
  13844. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  13845. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  13846. var renderingGroup = this._renderingGroups[index];
  13847. if (!renderingGroup && !observable)
  13848. continue;
  13849. this._currentIndex = index;
  13850. var renderingGroupMask = 0;
  13851. // Fire PRECLEAR stage
  13852. if (observable) {
  13853. renderingGroupMask = Math.pow(2, index);
  13854. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  13855. info.renderingGroupId = index;
  13856. observable.notifyObservers(info, renderingGroupMask);
  13857. }
  13858. // Clear depth/stencil if needed
  13859. var autoClear = this._autoClearDepthStencil[index];
  13860. if (autoClear && autoClear.autoClear) {
  13861. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  13862. }
  13863. if (observable) {
  13864. // Fire PREOPAQUE stage
  13865. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  13866. observable.notifyObservers(info, renderingGroupMask);
  13867. // Fire PRETRANSPARENT stage
  13868. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  13869. observable.notifyObservers(info, renderingGroupMask);
  13870. }
  13871. if (renderingGroup)
  13872. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  13873. // Fire POSTTRANSPARENT stage
  13874. if (observable) {
  13875. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  13876. observable.notifyObservers(info, renderingGroupMask);
  13877. }
  13878. }
  13879. };
  13880. RenderingManager.prototype.reset = function () {
  13881. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  13882. var renderingGroup = this._renderingGroups[index];
  13883. if (renderingGroup) {
  13884. renderingGroup.prepare();
  13885. }
  13886. }
  13887. };
  13888. RenderingManager.prototype.dispose = function () {
  13889. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  13890. var renderingGroup = this._renderingGroups[index];
  13891. if (renderingGroup) {
  13892. renderingGroup.dispose();
  13893. }
  13894. }
  13895. this._renderingGroups.length = 0;
  13896. };
  13897. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  13898. if (!this._renderingGroups[renderingGroupId]) {
  13899. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  13900. }
  13901. };
  13902. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  13903. var renderingGroupId = spriteManager.renderingGroupId || 0;
  13904. this._prepareRenderingGroup(renderingGroupId);
  13905. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  13906. };
  13907. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  13908. var renderingGroupId = particleSystem.renderingGroupId || 0;
  13909. this._prepareRenderingGroup(renderingGroupId);
  13910. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  13911. };
  13912. RenderingManager.prototype.dispatch = function (subMesh) {
  13913. var mesh = subMesh.getMesh();
  13914. var renderingGroupId = mesh.renderingGroupId || 0;
  13915. this._prepareRenderingGroup(renderingGroupId);
  13916. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  13917. };
  13918. /**
  13919. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  13920. * This allowed control for front to back rendering or reversly depending of the special needs.
  13921. *
  13922. * @param renderingGroupId The rendering group id corresponding to its index
  13923. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  13924. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  13925. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  13926. */
  13927. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  13928. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  13929. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  13930. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  13931. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  13932. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  13933. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  13934. if (this._renderingGroups[renderingGroupId]) {
  13935. var group = this._renderingGroups[renderingGroupId];
  13936. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  13937. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  13938. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  13939. }
  13940. };
  13941. /**
  13942. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  13943. *
  13944. * @param renderingGroupId The rendering group id corresponding to its index
  13945. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  13946. * @param depth Automatically clears depth between groups if true and autoClear is true.
  13947. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  13948. */
  13949. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  13950. if (depth === void 0) { depth = true; }
  13951. if (stencil === void 0) { stencil = true; }
  13952. this._autoClearDepthStencil[renderingGroupId] = {
  13953. autoClear: autoClearDepthStencil,
  13954. depth: depth,
  13955. stencil: stencil
  13956. };
  13957. };
  13958. return RenderingManager;
  13959. }());
  13960. /**
  13961. * The max id used for rendering groups (not included)
  13962. */
  13963. RenderingManager.MAX_RENDERINGGROUPS = 4;
  13964. /**
  13965. * The min id used for rendering groups (included)
  13966. */
  13967. RenderingManager.MIN_RENDERINGGROUPS = 0;
  13968. BABYLON.RenderingManager = RenderingManager;
  13969. })(BABYLON || (BABYLON = {}));
  13970. //# sourceMappingURL=babylon.renderingManager.js.map
  13971. var BABYLON;
  13972. (function (BABYLON) {
  13973. var RenderingGroup = (function () {
  13974. /**
  13975. * Creates a new rendering group.
  13976. * @param index The rendering group index
  13977. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  13978. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  13979. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  13980. */
  13981. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  13982. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  13983. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  13984. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  13985. this.index = index;
  13986. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  13987. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  13988. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  13989. this._particleSystems = new BABYLON.SmartArray(256);
  13990. this._spriteManagers = new BABYLON.SmartArray(256);
  13991. this._scene = scene;
  13992. this.opaqueSortCompareFn = opaqueSortCompareFn;
  13993. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  13994. this.transparentSortCompareFn = transparentSortCompareFn;
  13995. }
  13996. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  13997. /**
  13998. * Set the opaque sort comparison function.
  13999. * If null the sub meshes will be render in the order they were created
  14000. */
  14001. set: function (value) {
  14002. this._opaqueSortCompareFn = value;
  14003. if (value) {
  14004. this._renderOpaque = this.renderOpaqueSorted;
  14005. }
  14006. else {
  14007. this._renderOpaque = RenderingGroup.renderUnsorted;
  14008. }
  14009. },
  14010. enumerable: true,
  14011. configurable: true
  14012. });
  14013. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  14014. /**
  14015. * Set the alpha test sort comparison function.
  14016. * If null the sub meshes will be render in the order they were created
  14017. */
  14018. set: function (value) {
  14019. this._alphaTestSortCompareFn = value;
  14020. if (value) {
  14021. this._renderAlphaTest = this.renderAlphaTestSorted;
  14022. }
  14023. else {
  14024. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  14025. }
  14026. },
  14027. enumerable: true,
  14028. configurable: true
  14029. });
  14030. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  14031. /**
  14032. * Set the transparent sort comparison function.
  14033. * If null the sub meshes will be render in the order they were created
  14034. */
  14035. set: function (value) {
  14036. if (value) {
  14037. this._transparentSortCompareFn = value;
  14038. }
  14039. else {
  14040. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  14041. }
  14042. this._renderTransparent = this.renderTransparentSorted;
  14043. },
  14044. enumerable: true,
  14045. configurable: true
  14046. });
  14047. /**
  14048. * Render all the sub meshes contained in the group.
  14049. * @param customRenderFunction Used to override the default render behaviour of the group.
  14050. * @returns true if rendered some submeshes.
  14051. */
  14052. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  14053. if (customRenderFunction) {
  14054. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  14055. return;
  14056. }
  14057. var engine = this._scene.getEngine();
  14058. // Opaque
  14059. if (this._opaqueSubMeshes.length !== 0) {
  14060. this._renderOpaque(this._opaqueSubMeshes);
  14061. }
  14062. // Alpha test
  14063. if (this._alphaTestSubMeshes.length !== 0) {
  14064. engine.setAlphaTesting(true);
  14065. this._renderAlphaTest(this._alphaTestSubMeshes);
  14066. engine.setAlphaTesting(false);
  14067. }
  14068. var stencilState = engine.getStencilBuffer();
  14069. engine.setStencilBuffer(false);
  14070. // Sprites
  14071. if (renderSprites) {
  14072. this._renderSprites();
  14073. }
  14074. // Particles
  14075. if (renderParticles) {
  14076. this._renderParticles(activeMeshes);
  14077. }
  14078. if (this.onBeforeTransparentRendering) {
  14079. this.onBeforeTransparentRendering();
  14080. }
  14081. // Transparent
  14082. if (this._transparentSubMeshes.length !== 0) {
  14083. this._renderTransparent(this._transparentSubMeshes);
  14084. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  14085. }
  14086. engine.setStencilBuffer(stencilState);
  14087. };
  14088. /**
  14089. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  14090. * @param subMeshes The submeshes to render
  14091. */
  14092. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  14093. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera.globalPosition, false);
  14094. };
  14095. /**
  14096. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  14097. * @param subMeshes The submeshes to render
  14098. */
  14099. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  14100. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera.globalPosition, false);
  14101. };
  14102. /**
  14103. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  14104. * @param subMeshes The submeshes to render
  14105. */
  14106. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  14107. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera.globalPosition, true);
  14108. };
  14109. /**
  14110. * Renders the submeshes in a specified order.
  14111. * @param subMeshes The submeshes to sort before render
  14112. * @param sortCompareFn The comparison function use to sort
  14113. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  14114. * @param transparent Specifies to activate blending if true
  14115. */
  14116. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, cameraPosition, transparent) {
  14117. var subIndex = 0;
  14118. var subMesh;
  14119. for (; subIndex < subMeshes.length; subIndex++) {
  14120. subMesh = subMeshes.data[subIndex];
  14121. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  14122. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  14123. }
  14124. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  14125. sortedArray.sort(sortCompareFn);
  14126. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  14127. subMesh = sortedArray[subIndex];
  14128. subMesh.render(transparent);
  14129. }
  14130. };
  14131. /**
  14132. * Renders the submeshes in the order they were dispatched (no sort applied).
  14133. * @param subMeshes The submeshes to render
  14134. */
  14135. RenderingGroup.renderUnsorted = function (subMeshes) {
  14136. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  14137. var submesh = subMeshes.data[subIndex];
  14138. submesh.render(false);
  14139. }
  14140. };
  14141. /**
  14142. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  14143. * are rendered back to front if in the same alpha index.
  14144. *
  14145. * @param a The first submesh
  14146. * @param b The second submesh
  14147. * @returns The result of the comparison
  14148. */
  14149. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  14150. // Alpha index first
  14151. if (a._alphaIndex > b._alphaIndex) {
  14152. return 1;
  14153. }
  14154. if (a._alphaIndex < b._alphaIndex) {
  14155. return -1;
  14156. }
  14157. // Then distance to camera
  14158. return RenderingGroup.backToFrontSortCompare(a, b);
  14159. };
  14160. /**
  14161. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  14162. * are rendered back to front.
  14163. *
  14164. * @param a The first submesh
  14165. * @param b The second submesh
  14166. * @returns The result of the comparison
  14167. */
  14168. RenderingGroup.backToFrontSortCompare = function (a, b) {
  14169. // Then distance to camera
  14170. if (a._distanceToCamera < b._distanceToCamera) {
  14171. return 1;
  14172. }
  14173. if (a._distanceToCamera > b._distanceToCamera) {
  14174. return -1;
  14175. }
  14176. return 0;
  14177. };
  14178. /**
  14179. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  14180. * are rendered front to back (prevent overdraw).
  14181. *
  14182. * @param a The first submesh
  14183. * @param b The second submesh
  14184. * @returns The result of the comparison
  14185. */
  14186. RenderingGroup.frontToBackSortCompare = function (a, b) {
  14187. // Then distance to camera
  14188. if (a._distanceToCamera < b._distanceToCamera) {
  14189. return -1;
  14190. }
  14191. if (a._distanceToCamera > b._distanceToCamera) {
  14192. return 1;
  14193. }
  14194. return 0;
  14195. };
  14196. /**
  14197. * Resets the different lists of submeshes to prepare a new frame.
  14198. */
  14199. RenderingGroup.prototype.prepare = function () {
  14200. this._opaqueSubMeshes.reset();
  14201. this._transparentSubMeshes.reset();
  14202. this._alphaTestSubMeshes.reset();
  14203. this._particleSystems.reset();
  14204. this._spriteManagers.reset();
  14205. };
  14206. RenderingGroup.prototype.dispose = function () {
  14207. this._opaqueSubMeshes.dispose();
  14208. this._transparentSubMeshes.dispose();
  14209. this._alphaTestSubMeshes.dispose();
  14210. this._particleSystems.dispose();
  14211. this._spriteManagers.dispose();
  14212. };
  14213. /**
  14214. * Inserts the submesh in its correct queue depending on its material.
  14215. * @param subMesh The submesh to dispatch
  14216. */
  14217. RenderingGroup.prototype.dispatch = function (subMesh) {
  14218. var material = subMesh.getMaterial();
  14219. var mesh = subMesh.getMesh();
  14220. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  14221. this._transparentSubMeshes.push(subMesh);
  14222. }
  14223. else if (material.needAlphaTesting()) {
  14224. this._alphaTestSubMeshes.push(subMesh);
  14225. }
  14226. else {
  14227. this._opaqueSubMeshes.push(subMesh); // Opaque
  14228. }
  14229. };
  14230. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  14231. this._spriteManagers.push(spriteManager);
  14232. };
  14233. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  14234. this._particleSystems.push(particleSystem);
  14235. };
  14236. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  14237. if (this._particleSystems.length === 0) {
  14238. return;
  14239. }
  14240. // Particles
  14241. var activeCamera = this._scene.activeCamera;
  14242. this._scene._particlesDuration.beginMonitoring();
  14243. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  14244. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  14245. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  14246. continue;
  14247. }
  14248. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  14249. this._scene._activeParticles.addCount(particleSystem.render(), false);
  14250. }
  14251. }
  14252. this._scene._particlesDuration.endMonitoring(false);
  14253. };
  14254. RenderingGroup.prototype._renderSprites = function () {
  14255. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  14256. return;
  14257. }
  14258. // Sprites
  14259. var activeCamera = this._scene.activeCamera;
  14260. this._scene._spritesDuration.beginMonitoring();
  14261. for (var id = 0; id < this._spriteManagers.length; id++) {
  14262. var spriteManager = this._spriteManagers.data[id];
  14263. if (((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  14264. spriteManager.render();
  14265. }
  14266. }
  14267. this._scene._spritesDuration.endMonitoring(false);
  14268. };
  14269. return RenderingGroup;
  14270. }());
  14271. BABYLON.RenderingGroup = RenderingGroup;
  14272. })(BABYLON || (BABYLON = {}));
  14273. //# sourceMappingURL=babylon.renderingGroup.js.map
  14274. var BABYLON;
  14275. (function (BABYLON) {
  14276. var ClickInfo = (function () {
  14277. function ClickInfo() {
  14278. this._singleClick = false;
  14279. this._doubleClick = false;
  14280. this._hasSwiped = false;
  14281. this._ignore = false;
  14282. }
  14283. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  14284. get: function () {
  14285. return this._singleClick;
  14286. },
  14287. set: function (b) {
  14288. this._singleClick = b;
  14289. },
  14290. enumerable: true,
  14291. configurable: true
  14292. });
  14293. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  14294. get: function () {
  14295. return this._doubleClick;
  14296. },
  14297. set: function (b) {
  14298. this._doubleClick = b;
  14299. },
  14300. enumerable: true,
  14301. configurable: true
  14302. });
  14303. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  14304. get: function () {
  14305. return this._hasSwiped;
  14306. },
  14307. set: function (b) {
  14308. this._hasSwiped = b;
  14309. },
  14310. enumerable: true,
  14311. configurable: true
  14312. });
  14313. Object.defineProperty(ClickInfo.prototype, "ignore", {
  14314. get: function () {
  14315. return this._ignore;
  14316. },
  14317. set: function (b) {
  14318. this._ignore = b;
  14319. },
  14320. enumerable: true,
  14321. configurable: true
  14322. });
  14323. return ClickInfo;
  14324. }());
  14325. var PointerEventTypes = (function () {
  14326. function PointerEventTypes() {
  14327. }
  14328. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  14329. get: function () {
  14330. return PointerEventTypes._POINTERDOWN;
  14331. },
  14332. enumerable: true,
  14333. configurable: true
  14334. });
  14335. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  14336. get: function () {
  14337. return PointerEventTypes._POINTERUP;
  14338. },
  14339. enumerable: true,
  14340. configurable: true
  14341. });
  14342. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  14343. get: function () {
  14344. return PointerEventTypes._POINTERMOVE;
  14345. },
  14346. enumerable: true,
  14347. configurable: true
  14348. });
  14349. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  14350. get: function () {
  14351. return PointerEventTypes._POINTERWHEEL;
  14352. },
  14353. enumerable: true,
  14354. configurable: true
  14355. });
  14356. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  14357. get: function () {
  14358. return PointerEventTypes._POINTERPICK;
  14359. },
  14360. enumerable: true,
  14361. configurable: true
  14362. });
  14363. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  14364. get: function () {
  14365. return PointerEventTypes._POINTERTAP;
  14366. },
  14367. enumerable: true,
  14368. configurable: true
  14369. });
  14370. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  14371. get: function () {
  14372. return PointerEventTypes._POINTERDOUBLETAP;
  14373. },
  14374. enumerable: true,
  14375. configurable: true
  14376. });
  14377. return PointerEventTypes;
  14378. }());
  14379. PointerEventTypes._POINTERDOWN = 0x01;
  14380. PointerEventTypes._POINTERUP = 0x02;
  14381. PointerEventTypes._POINTERMOVE = 0x04;
  14382. PointerEventTypes._POINTERWHEEL = 0x08;
  14383. PointerEventTypes._POINTERPICK = 0x10;
  14384. PointerEventTypes._POINTERTAP = 0x20;
  14385. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  14386. BABYLON.PointerEventTypes = PointerEventTypes;
  14387. var PointerInfoBase = (function () {
  14388. function PointerInfoBase(type, event) {
  14389. this.type = type;
  14390. this.event = event;
  14391. }
  14392. return PointerInfoBase;
  14393. }());
  14394. BABYLON.PointerInfoBase = PointerInfoBase;
  14395. /**
  14396. * This class is used to store pointer related info for the onPrePointerObservable event.
  14397. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  14398. */
  14399. var PointerInfoPre = (function (_super) {
  14400. __extends(PointerInfoPre, _super);
  14401. function PointerInfoPre(type, event, localX, localY) {
  14402. var _this = _super.call(this, type, event) || this;
  14403. _this.skipOnPointerObservable = false;
  14404. _this.localPosition = new BABYLON.Vector2(localX, localY);
  14405. return _this;
  14406. }
  14407. return PointerInfoPre;
  14408. }(PointerInfoBase));
  14409. BABYLON.PointerInfoPre = PointerInfoPre;
  14410. /**
  14411. * This type contains all the data related to a pointer event in Babylon.js.
  14412. * 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.
  14413. */
  14414. var PointerInfo = (function (_super) {
  14415. __extends(PointerInfo, _super);
  14416. function PointerInfo(type, event, pickInfo) {
  14417. var _this = _super.call(this, type, event) || this;
  14418. _this.pickInfo = pickInfo;
  14419. return _this;
  14420. }
  14421. return PointerInfo;
  14422. }(PointerInfoBase));
  14423. BABYLON.PointerInfo = PointerInfo;
  14424. /**
  14425. * This class is used by the onRenderingGroupObservable
  14426. */
  14427. var RenderingGroupInfo = (function () {
  14428. function RenderingGroupInfo() {
  14429. }
  14430. return RenderingGroupInfo;
  14431. }());
  14432. /**
  14433. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  14434. * This stage will be fired no matter what
  14435. */
  14436. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  14437. /**
  14438. * Called before opaque object are rendered.
  14439. * This stage will be fired only if there's 3D Opaque content to render
  14440. */
  14441. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  14442. /**
  14443. * Called after the opaque objects are rendered and before the transparent ones
  14444. * This stage will be fired only if there's 3D transparent content to render
  14445. */
  14446. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  14447. /**
  14448. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  14449. * This stage will be fired no matter what
  14450. */
  14451. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  14452. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  14453. /**
  14454. * Represents a scene to be rendered by the engine.
  14455. * @see http://doc.babylonjs.com/page.php?p=21911
  14456. */
  14457. var Scene = (function () {
  14458. /**
  14459. * @constructor
  14460. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  14461. */
  14462. function Scene(engine) {
  14463. // Members
  14464. this.autoClear = true;
  14465. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  14466. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  14467. this.forceWireframe = false;
  14468. this._forcePointsCloud = false;
  14469. this.forceShowBoundingBoxes = false;
  14470. this.animationsEnabled = true;
  14471. this.constantlyUpdateMeshUnderPointer = false;
  14472. this.useRightHandedSystem = false;
  14473. this.hoverCursor = "pointer";
  14474. // Metadata
  14475. this.metadata = null;
  14476. // Events
  14477. /**
  14478. * An event triggered when the scene is disposed.
  14479. * @type {BABYLON.Observable}
  14480. */
  14481. this.onDisposeObservable = new BABYLON.Observable();
  14482. /**
  14483. * An event triggered before rendering the scene
  14484. * @type {BABYLON.Observable}
  14485. */
  14486. this.onBeforeRenderObservable = new BABYLON.Observable();
  14487. /**
  14488. * An event triggered after rendering the scene
  14489. * @type {BABYLON.Observable}
  14490. */
  14491. this.onAfterRenderObservable = new BABYLON.Observable();
  14492. /**
  14493. * An event triggered when the scene is ready
  14494. * @type {BABYLON.Observable}
  14495. */
  14496. this.onReadyObservable = new BABYLON.Observable();
  14497. /**
  14498. * An event triggered before rendering a camera
  14499. * @type {BABYLON.Observable}
  14500. */
  14501. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  14502. /**
  14503. * An event triggered after rendering a camera
  14504. * @type {BABYLON.Observable}
  14505. */
  14506. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  14507. /**
  14508. * An event triggered when a camera is created
  14509. * @type {BABYLON.Observable}
  14510. */
  14511. this.onNewCameraAddedObservable = new BABYLON.Observable();
  14512. /**
  14513. * An event triggered when a camera is removed
  14514. * @type {BABYLON.Observable}
  14515. */
  14516. this.onCameraRemovedObservable = new BABYLON.Observable();
  14517. /**
  14518. * An event triggered when a light is created
  14519. * @type {BABYLON.Observable}
  14520. */
  14521. this.onNewLightAddedObservable = new BABYLON.Observable();
  14522. /**
  14523. * An event triggered when a light is removed
  14524. * @type {BABYLON.Observable}
  14525. */
  14526. this.onLightRemovedObservable = new BABYLON.Observable();
  14527. /**
  14528. * An event triggered when a geometry is created
  14529. * @type {BABYLON.Observable}
  14530. */
  14531. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  14532. /**
  14533. * An event triggered when a geometry is removed
  14534. * @type {BABYLON.Observable}
  14535. */
  14536. this.onGeometryRemovedObservable = new BABYLON.Observable();
  14537. /**
  14538. * An event triggered when a mesh is created
  14539. * @type {BABYLON.Observable}
  14540. */
  14541. this.onNewMeshAddedObservable = new BABYLON.Observable();
  14542. /**
  14543. * An event triggered when a mesh is removed
  14544. * @type {BABYLON.Observable}
  14545. */
  14546. this.onMeshRemovedObservable = new BABYLON.Observable();
  14547. /**
  14548. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  14549. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  14550. * 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)
  14551. */
  14552. this.onRenderingGroupObservable = new BABYLON.Observable();
  14553. // Animations
  14554. this.animations = [];
  14555. /**
  14556. * 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).
  14557. * You have the possibility to skip the 3D Engine process and the call to onPointerObservable by setting PointerInfoBase.skipOnPointerObservable to true
  14558. */
  14559. this.onPrePointerObservable = new BABYLON.Observable();
  14560. /**
  14561. * Observable event triggered each time an input event is received from the rendering canvas
  14562. */
  14563. this.onPointerObservable = new BABYLON.Observable();
  14564. this._meshPickProceed = false;
  14565. this._previousHasSwiped = false;
  14566. this._currentPickResult = null;
  14567. this._previousPickResult = null;
  14568. this._isButtonPressed = false;
  14569. this._doubleClickOccured = false;
  14570. 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
  14571. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  14572. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  14573. this._startingPointerTime = 0;
  14574. this._previousStartingPointerTime = 0;
  14575. // Fog
  14576. /**
  14577. * is fog enabled on this scene.
  14578. * @type {boolean}
  14579. */
  14580. this._fogEnabled = true;
  14581. this._fogMode = Scene.FOGMODE_NONE;
  14582. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  14583. this.fogDensity = 0.1;
  14584. this.fogStart = 0;
  14585. this.fogEnd = 1000.0;
  14586. // Lights
  14587. /**
  14588. * is shadow enabled on this scene.
  14589. * @type {boolean}
  14590. */
  14591. this._shadowsEnabled = true;
  14592. /**
  14593. * is light enabled on this scene.
  14594. * @type {boolean}
  14595. */
  14596. this._lightsEnabled = true;
  14597. /**
  14598. * All of the lights added to this scene.
  14599. * @see BABYLON.Light
  14600. * @type {BABYLON.Light[]}
  14601. */
  14602. this.lights = new Array();
  14603. // Cameras
  14604. /**
  14605. * All of the cameras added to this scene.
  14606. * @see BABYLON.Camera
  14607. * @type {BABYLON.Camera[]}
  14608. */
  14609. this.cameras = new Array();
  14610. this.activeCameras = new Array();
  14611. // Meshes
  14612. /**
  14613. * All of the (abstract) meshes added to this scene.
  14614. * @see BABYLON.AbstractMesh
  14615. * @type {BABYLON.AbstractMesh[]}
  14616. */
  14617. this.meshes = new Array();
  14618. // Geometries
  14619. this._geometries = new Array();
  14620. this.materials = new Array();
  14621. this.multiMaterials = new Array();
  14622. // Textures
  14623. this._texturesEnabled = true;
  14624. this.textures = new Array();
  14625. // Particles
  14626. this.particlesEnabled = true;
  14627. this.particleSystems = new Array();
  14628. // Sprites
  14629. this.spritesEnabled = true;
  14630. this.spriteManagers = new Array();
  14631. // Layers
  14632. this.layers = new Array();
  14633. this.highlightLayers = new Array();
  14634. // Skeletons
  14635. this._skeletonsEnabled = true;
  14636. this.skeletons = new Array();
  14637. // Morph targets
  14638. this.morphTargetManagers = new Array();
  14639. // Lens flares
  14640. this.lensFlaresEnabled = true;
  14641. this.lensFlareSystems = new Array();
  14642. // Collisions
  14643. this.collisionsEnabled = true;
  14644. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  14645. // Postprocesses
  14646. this.postProcessesEnabled = true;
  14647. // Customs render targets
  14648. this.renderTargetsEnabled = true;
  14649. this.dumpNextRenderTargets = false;
  14650. this.customRenderTargets = new Array();
  14651. // Imported meshes
  14652. this.importedMeshesFiles = new Array();
  14653. // Probes
  14654. this.probesEnabled = true;
  14655. this.reflectionProbes = new Array();
  14656. this._actionManagers = new Array();
  14657. this._meshesForIntersections = new BABYLON.SmartArray(256);
  14658. // Procedural textures
  14659. this.proceduralTexturesEnabled = true;
  14660. this._proceduralTextures = new Array();
  14661. this.soundTracks = new Array();
  14662. this._audioEnabled = true;
  14663. this._headphone = false;
  14664. // Performance counters
  14665. this._totalMeshesCounter = new BABYLON.PerfCounter();
  14666. this._totalLightsCounter = new BABYLON.PerfCounter();
  14667. this._totalMaterialsCounter = new BABYLON.PerfCounter();
  14668. this._totalTexturesCounter = new BABYLON.PerfCounter();
  14669. this._totalVertices = new BABYLON.PerfCounter();
  14670. this._activeIndices = new BABYLON.PerfCounter();
  14671. this._activeParticles = new BABYLON.PerfCounter();
  14672. this._lastFrameDuration = new BABYLON.PerfCounter();
  14673. this._evaluateActiveMeshesDuration = new BABYLON.PerfCounter();
  14674. this._renderTargetsDuration = new BABYLON.PerfCounter();
  14675. this._particlesDuration = new BABYLON.PerfCounter();
  14676. this._renderDuration = new BABYLON.PerfCounter();
  14677. this._spritesDuration = new BABYLON.PerfCounter();
  14678. this._activeBones = new BABYLON.PerfCounter();
  14679. this._animationTime = 0;
  14680. this.animationTimeScale = 1;
  14681. this._renderId = 0;
  14682. this._executeWhenReadyTimeoutId = -1;
  14683. this._intermediateRendering = false;
  14684. this._viewUpdateFlag = -1;
  14685. this._projectionUpdateFlag = -1;
  14686. this._toBeDisposed = new BABYLON.SmartArray(256);
  14687. this._pendingData = []; //ANY
  14688. this._activeMeshes = new BABYLON.SmartArray(256);
  14689. this._processedMaterials = new BABYLON.SmartArray(256);
  14690. this._renderTargets = new BABYLON.SmartArray(256);
  14691. this._activeParticleSystems = new BABYLON.SmartArray(256);
  14692. this._activeSkeletons = new BABYLON.SmartArray(32);
  14693. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  14694. this._activeAnimatables = new Array();
  14695. this._transformMatrix = BABYLON.Matrix.Zero();
  14696. this._edgesRenderers = new BABYLON.SmartArray(16);
  14697. this._uniqueIdCounter = 0;
  14698. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  14699. this._engine.scenes.push(this);
  14700. this._uid = null;
  14701. this._renderingManager = new BABYLON.RenderingManager(this);
  14702. this.postProcessManager = new BABYLON.PostProcessManager(this);
  14703. if (BABYLON.OutlineRenderer) {
  14704. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  14705. }
  14706. this.attachControl();
  14707. if (BABYLON.SoundTrack) {
  14708. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  14709. }
  14710. //simplification queue
  14711. if (BABYLON.SimplificationQueue) {
  14712. this.simplificationQueue = new BABYLON.SimplificationQueue();
  14713. }
  14714. //collision coordinator initialization. For now legacy per default.
  14715. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  14716. // Uniform Buffer
  14717. this._createUbo();
  14718. }
  14719. Object.defineProperty(Scene, "FOGMODE_NONE", {
  14720. get: function () {
  14721. return Scene._FOGMODE_NONE;
  14722. },
  14723. enumerable: true,
  14724. configurable: true
  14725. });
  14726. Object.defineProperty(Scene, "FOGMODE_EXP", {
  14727. get: function () {
  14728. return Scene._FOGMODE_EXP;
  14729. },
  14730. enumerable: true,
  14731. configurable: true
  14732. });
  14733. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  14734. get: function () {
  14735. return Scene._FOGMODE_EXP2;
  14736. },
  14737. enumerable: true,
  14738. configurable: true
  14739. });
  14740. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  14741. get: function () {
  14742. return Scene._FOGMODE_LINEAR;
  14743. },
  14744. enumerable: true,
  14745. configurable: true
  14746. });
  14747. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  14748. get: function () {
  14749. return this._forcePointsCloud;
  14750. },
  14751. set: function (value) {
  14752. if (this._forcePointsCloud === value) {
  14753. return;
  14754. }
  14755. this._forcePointsCloud = value;
  14756. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  14757. },
  14758. enumerable: true,
  14759. configurable: true
  14760. });
  14761. Object.defineProperty(Scene.prototype, "onDispose", {
  14762. set: function (callback) {
  14763. if (this._onDisposeObserver) {
  14764. this.onDisposeObservable.remove(this._onDisposeObserver);
  14765. }
  14766. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  14767. },
  14768. enumerable: true,
  14769. configurable: true
  14770. });
  14771. Object.defineProperty(Scene.prototype, "beforeRender", {
  14772. set: function (callback) {
  14773. if (this._onBeforeRenderObserver) {
  14774. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  14775. }
  14776. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  14777. },
  14778. enumerable: true,
  14779. configurable: true
  14780. });
  14781. Object.defineProperty(Scene.prototype, "afterRender", {
  14782. set: function (callback) {
  14783. if (this._onAfterRenderObserver) {
  14784. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  14785. }
  14786. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  14787. },
  14788. enumerable: true,
  14789. configurable: true
  14790. });
  14791. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  14792. set: function (callback) {
  14793. if (this._onBeforeCameraRenderObserver) {
  14794. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  14795. }
  14796. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  14797. },
  14798. enumerable: true,
  14799. configurable: true
  14800. });
  14801. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  14802. set: function (callback) {
  14803. if (this._onAfterCameraRenderObserver) {
  14804. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  14805. }
  14806. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  14807. },
  14808. enumerable: true,
  14809. configurable: true
  14810. });
  14811. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  14812. get: function () {
  14813. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  14814. },
  14815. enumerable: true,
  14816. configurable: true
  14817. });
  14818. Object.defineProperty(Scene.prototype, "fogEnabled", {
  14819. get: function () {
  14820. return this._fogEnabled;
  14821. },
  14822. set: function (value) {
  14823. if (this._fogEnabled === value) {
  14824. return;
  14825. }
  14826. this._fogEnabled = value;
  14827. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  14828. },
  14829. enumerable: true,
  14830. configurable: true
  14831. });
  14832. Object.defineProperty(Scene.prototype, "fogMode", {
  14833. get: function () {
  14834. return this._fogMode;
  14835. },
  14836. set: function (value) {
  14837. if (this._fogMode === value) {
  14838. return;
  14839. }
  14840. this._fogMode = value;
  14841. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  14842. },
  14843. enumerable: true,
  14844. configurable: true
  14845. });
  14846. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  14847. get: function () {
  14848. return this._shadowsEnabled;
  14849. },
  14850. set: function (value) {
  14851. if (this._shadowsEnabled === value) {
  14852. return;
  14853. }
  14854. this._shadowsEnabled = value;
  14855. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  14856. },
  14857. enumerable: true,
  14858. configurable: true
  14859. });
  14860. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  14861. get: function () {
  14862. return this._lightsEnabled;
  14863. },
  14864. set: function (value) {
  14865. if (this._lightsEnabled === value) {
  14866. return;
  14867. }
  14868. this._lightsEnabled = value;
  14869. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  14870. },
  14871. enumerable: true,
  14872. configurable: true
  14873. });
  14874. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  14875. get: function () {
  14876. if (!this._defaultMaterial) {
  14877. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  14878. }
  14879. return this._defaultMaterial;
  14880. },
  14881. enumerable: true,
  14882. configurable: true
  14883. });
  14884. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  14885. get: function () {
  14886. return this._texturesEnabled;
  14887. },
  14888. set: function (value) {
  14889. if (this._texturesEnabled === value) {
  14890. return;
  14891. }
  14892. this._texturesEnabled = value;
  14893. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  14894. },
  14895. enumerable: true,
  14896. configurable: true
  14897. });
  14898. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  14899. get: function () {
  14900. return this._skeletonsEnabled;
  14901. },
  14902. set: function (value) {
  14903. if (this._skeletonsEnabled === value) {
  14904. return;
  14905. }
  14906. this._skeletonsEnabled = value;
  14907. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  14908. },
  14909. enumerable: true,
  14910. configurable: true
  14911. });
  14912. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  14913. get: function () {
  14914. if (!this._postProcessRenderPipelineManager) {
  14915. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  14916. }
  14917. return this._postProcessRenderPipelineManager;
  14918. },
  14919. enumerable: true,
  14920. configurable: true
  14921. });
  14922. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  14923. get: function () {
  14924. return this._frustumPlanes;
  14925. },
  14926. enumerable: true,
  14927. configurable: true
  14928. });
  14929. Object.defineProperty(Scene.prototype, "debugLayer", {
  14930. // Properties
  14931. get: function () {
  14932. if (!this._debugLayer) {
  14933. this._debugLayer = new BABYLON.DebugLayer(this);
  14934. }
  14935. return this._debugLayer;
  14936. },
  14937. enumerable: true,
  14938. configurable: true
  14939. });
  14940. Object.defineProperty(Scene.prototype, "workerCollisions", {
  14941. get: function () {
  14942. return this._workerCollisions;
  14943. },
  14944. set: function (enabled) {
  14945. if (!BABYLON.CollisionCoordinatorLegacy) {
  14946. return;
  14947. }
  14948. enabled = (enabled && !!Worker);
  14949. this._workerCollisions = enabled;
  14950. if (this.collisionCoordinator) {
  14951. this.collisionCoordinator.destroy();
  14952. }
  14953. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  14954. this.collisionCoordinator.init(this);
  14955. },
  14956. enumerable: true,
  14957. configurable: true
  14958. });
  14959. Object.defineProperty(Scene.prototype, "selectionOctree", {
  14960. get: function () {
  14961. return this._selectionOctree;
  14962. },
  14963. enumerable: true,
  14964. configurable: true
  14965. });
  14966. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  14967. /**
  14968. * The mesh that is currently under the pointer.
  14969. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  14970. */
  14971. get: function () {
  14972. return this._pointerOverMesh;
  14973. },
  14974. enumerable: true,
  14975. configurable: true
  14976. });
  14977. Object.defineProperty(Scene.prototype, "pointerX", {
  14978. /**
  14979. * Current on-screen X position of the pointer
  14980. * @return {number} X position of the pointer
  14981. */
  14982. get: function () {
  14983. return this._pointerX;
  14984. },
  14985. enumerable: true,
  14986. configurable: true
  14987. });
  14988. Object.defineProperty(Scene.prototype, "pointerY", {
  14989. /**
  14990. * Current on-screen Y position of the pointer
  14991. * @return {number} Y position of the pointer
  14992. */
  14993. get: function () {
  14994. return this._pointerY;
  14995. },
  14996. enumerable: true,
  14997. configurable: true
  14998. });
  14999. Scene.prototype.getCachedMaterial = function () {
  15000. return this._cachedMaterial;
  15001. };
  15002. Scene.prototype.getCachedEffect = function () {
  15003. return this._cachedEffect;
  15004. };
  15005. Scene.prototype.getBoundingBoxRenderer = function () {
  15006. if (!this._boundingBoxRenderer) {
  15007. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  15008. }
  15009. return this._boundingBoxRenderer;
  15010. };
  15011. Scene.prototype.getOutlineRenderer = function () {
  15012. return this._outlineRenderer;
  15013. };
  15014. Scene.prototype.getEngine = function () {
  15015. return this._engine;
  15016. };
  15017. Scene.prototype.getTotalVertices = function () {
  15018. return this._totalVertices.current;
  15019. };
  15020. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  15021. get: function () {
  15022. return this._totalVertices;
  15023. },
  15024. enumerable: true,
  15025. configurable: true
  15026. });
  15027. Scene.prototype.getActiveIndices = function () {
  15028. return this._activeIndices.current;
  15029. };
  15030. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  15031. get: function () {
  15032. return this._activeIndices;
  15033. },
  15034. enumerable: true,
  15035. configurable: true
  15036. });
  15037. Scene.prototype.getActiveParticles = function () {
  15038. return this._activeParticles.current;
  15039. };
  15040. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  15041. get: function () {
  15042. return this._activeParticles;
  15043. },
  15044. enumerable: true,
  15045. configurable: true
  15046. });
  15047. Scene.prototype.getActiveBones = function () {
  15048. return this._activeBones.current;
  15049. };
  15050. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  15051. get: function () {
  15052. return this._activeBones;
  15053. },
  15054. enumerable: true,
  15055. configurable: true
  15056. });
  15057. // Stats
  15058. Scene.prototype.getLastFrameDuration = function () {
  15059. return this._lastFrameDuration.current;
  15060. };
  15061. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  15062. get: function () {
  15063. return this._lastFrameDuration;
  15064. },
  15065. enumerable: true,
  15066. configurable: true
  15067. });
  15068. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  15069. return this._evaluateActiveMeshesDuration.current;
  15070. };
  15071. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  15072. get: function () {
  15073. return this._evaluateActiveMeshesDuration;
  15074. },
  15075. enumerable: true,
  15076. configurable: true
  15077. });
  15078. Scene.prototype.getActiveMeshes = function () {
  15079. return this._activeMeshes;
  15080. };
  15081. Scene.prototype.getRenderTargetsDuration = function () {
  15082. return this._renderTargetsDuration.current;
  15083. };
  15084. Scene.prototype.getRenderDuration = function () {
  15085. return this._renderDuration.current;
  15086. };
  15087. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  15088. get: function () {
  15089. return this._renderDuration;
  15090. },
  15091. enumerable: true,
  15092. configurable: true
  15093. });
  15094. Scene.prototype.getParticlesDuration = function () {
  15095. return this._particlesDuration.current;
  15096. };
  15097. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  15098. get: function () {
  15099. return this._particlesDuration;
  15100. },
  15101. enumerable: true,
  15102. configurable: true
  15103. });
  15104. Scene.prototype.getSpritesDuration = function () {
  15105. return this._spritesDuration.current;
  15106. };
  15107. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  15108. get: function () {
  15109. return this._spritesDuration;
  15110. },
  15111. enumerable: true,
  15112. configurable: true
  15113. });
  15114. Scene.prototype.getAnimationRatio = function () {
  15115. return this._animationRatio;
  15116. };
  15117. Scene.prototype.getRenderId = function () {
  15118. return this._renderId;
  15119. };
  15120. Scene.prototype.incrementRenderId = function () {
  15121. this._renderId++;
  15122. };
  15123. Scene.prototype._updatePointerPosition = function (evt) {
  15124. var canvasRect = this._engine.getRenderingCanvasClientRect();
  15125. this._pointerX = evt.clientX - canvasRect.left;
  15126. this._pointerY = evt.clientY - canvasRect.top;
  15127. this._unTranslatedPointerX = this._pointerX;
  15128. this._unTranslatedPointerY = this._pointerY;
  15129. if (this.cameraToUseForPointers) {
  15130. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  15131. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  15132. }
  15133. };
  15134. Scene.prototype._createUbo = function () {
  15135. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, null, true);
  15136. this._sceneUbo.addUniform("viewProjection", 16);
  15137. this._sceneUbo.addUniform("view", 16);
  15138. };
  15139. // Pointers handling
  15140. /**
  15141. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  15142. * @param attachUp defines if you want to attach events to pointerup
  15143. * @param attachDown defines if you want to attach events to pointerdown
  15144. * @param attachMove defines if you want to attach events to pointermove
  15145. */
  15146. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  15147. var _this = this;
  15148. if (attachUp === void 0) { attachUp = true; }
  15149. if (attachDown === void 0) { attachDown = true; }
  15150. if (attachMove === void 0) { attachMove = true; }
  15151. this._initActionManager = function (act, clickInfo) {
  15152. if (!_this._meshPickProceed) {
  15153. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  15154. _this._currentPickResult = pickResult;
  15155. if (pickResult) {
  15156. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  15157. }
  15158. _this._meshPickProceed = true;
  15159. }
  15160. return act;
  15161. };
  15162. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  15163. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  15164. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  15165. btn !== _this._previousButtonPressed) {
  15166. _this._doubleClickOccured = false;
  15167. clickInfo.singleClick = true;
  15168. clickInfo.ignore = false;
  15169. cb(clickInfo, _this._currentPickResult);
  15170. }
  15171. };
  15172. this._initClickEvent = function (obs1, obs2, evt, cb) {
  15173. var clickInfo = new ClickInfo();
  15174. _this._currentPickResult = null;
  15175. var act;
  15176. var checkPicking = obs1.hasSpecificMask(PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(PointerEventTypes.POINTERPICK)
  15177. || obs1.hasSpecificMask(PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERTAP)
  15178. || obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  15179. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  15180. act = _this._initActionManager(act, clickInfo);
  15181. if (act)
  15182. checkPicking = act.hasPickTriggers;
  15183. }
  15184. if (checkPicking) {
  15185. var btn = evt.button;
  15186. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  15187. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  15188. if (!clickInfo.hasSwiped) {
  15189. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  15190. if (!checkSingleClickImmediately) {
  15191. checkSingleClickImmediately = !obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) &&
  15192. !obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  15193. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  15194. act = _this._initActionManager(act, clickInfo);
  15195. if (act)
  15196. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  15197. }
  15198. }
  15199. if (checkSingleClickImmediately) {
  15200. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  15201. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  15202. btn !== _this._previousButtonPressed) {
  15203. clickInfo.singleClick = true;
  15204. cb(clickInfo, _this._currentPickResult);
  15205. }
  15206. }
  15207. else {
  15208. // wait that no double click has been raised during the double click delay
  15209. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  15210. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  15211. }
  15212. var checkDoubleClick = obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) ||
  15213. obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  15214. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  15215. act = _this._initActionManager(act, clickInfo);
  15216. if (act)
  15217. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  15218. }
  15219. if (checkDoubleClick) {
  15220. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  15221. if (btn === _this._previousButtonPressed &&
  15222. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  15223. !_this._doubleClickOccured) {
  15224. // pointer has not moved for 2 clicks, it's a double click
  15225. if (!clickInfo.hasSwiped &&
  15226. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  15227. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  15228. _this._previousStartingPointerTime = 0;
  15229. _this._doubleClickOccured = true;
  15230. clickInfo.doubleClick = true;
  15231. clickInfo.ignore = false;
  15232. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout)
  15233. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  15234. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  15235. cb(clickInfo, _this._currentPickResult);
  15236. }
  15237. else {
  15238. _this._doubleClickOccured = false;
  15239. _this._previousStartingPointerTime = _this._startingPointerTime;
  15240. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  15241. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  15242. _this._previousButtonPressed = btn;
  15243. _this._previousHasSwiped = clickInfo.hasSwiped;
  15244. if (Scene.ExclusiveDoubleClickMode) {
  15245. if (_this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout) {
  15246. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  15247. }
  15248. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  15249. cb(clickInfo, _this._previousPickResult);
  15250. }
  15251. else {
  15252. cb(clickInfo, _this._currentPickResult);
  15253. }
  15254. }
  15255. }
  15256. else {
  15257. _this._doubleClickOccured = false;
  15258. _this._previousStartingPointerTime = _this._startingPointerTime;
  15259. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  15260. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  15261. _this._previousButtonPressed = btn;
  15262. _this._previousHasSwiped = clickInfo.hasSwiped;
  15263. }
  15264. }
  15265. }
  15266. }
  15267. clickInfo.ignore = true;
  15268. cb(clickInfo, _this._currentPickResult);
  15269. };
  15270. var spritePredicate = function (sprite) {
  15271. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  15272. };
  15273. this._onPointerMove = function (evt) {
  15274. _this._updatePointerPosition(evt);
  15275. // PreObservable support
  15276. if (_this.onPrePointerObservable.hasObservers()) {
  15277. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  15278. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  15279. _this.onPrePointerObservable.notifyObservers(pi, type);
  15280. if (pi.skipOnPointerObservable) {
  15281. return;
  15282. }
  15283. }
  15284. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  15285. return;
  15286. }
  15287. var canvas = _this._engine.getRenderingCanvas();
  15288. if (!_this.pointerMovePredicate) {
  15289. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && (_this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  15290. }
  15291. // Meshes
  15292. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  15293. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  15294. _this.setPointerOverSprite(null);
  15295. _this.setPointerOverMesh(pickResult.pickedMesh);
  15296. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  15297. if (_this._pointerOverMesh.actionManager.hoverCursor) {
  15298. canvas.style.cursor = _this._pointerOverMesh.actionManager.hoverCursor;
  15299. }
  15300. else {
  15301. canvas.style.cursor = _this.hoverCursor;
  15302. }
  15303. }
  15304. else {
  15305. canvas.style.cursor = "";
  15306. }
  15307. }
  15308. else {
  15309. _this.setPointerOverMesh(null);
  15310. // Sprites
  15311. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  15312. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  15313. _this.setPointerOverSprite(pickResult.pickedSprite);
  15314. if (_this._pointerOverSprite.actionManager && _this._pointerOverSprite.actionManager.hoverCursor) {
  15315. canvas.style.cursor = _this._pointerOverSprite.actionManager.hoverCursor;
  15316. }
  15317. else {
  15318. canvas.style.cursor = _this.hoverCursor;
  15319. }
  15320. }
  15321. else {
  15322. _this.setPointerOverSprite(null);
  15323. // Restore pointer
  15324. canvas.style.cursor = "";
  15325. }
  15326. }
  15327. if (_this.onPointerMove) {
  15328. _this.onPointerMove(evt, pickResult);
  15329. }
  15330. if (_this.onPointerObservable.hasObservers()) {
  15331. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  15332. var pi = new PointerInfo(type, evt, pickResult);
  15333. _this.onPointerObservable.notifyObservers(pi, type);
  15334. }
  15335. };
  15336. this._onPointerDown = function (evt) {
  15337. _this._isButtonPressed = true;
  15338. _this._pickedDownMesh = null;
  15339. _this._meshPickProceed = false;
  15340. _this._updatePointerPosition(evt);
  15341. // PreObservable support
  15342. if (_this.onPrePointerObservable.hasObservers()) {
  15343. var type = PointerEventTypes.POINTERDOWN;
  15344. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  15345. _this.onPrePointerObservable.notifyObservers(pi, type);
  15346. if (pi.skipOnPointerObservable) {
  15347. return;
  15348. }
  15349. }
  15350. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  15351. return;
  15352. }
  15353. _this._startingPointerPosition.x = _this._pointerX;
  15354. _this._startingPointerPosition.y = _this._pointerY;
  15355. _this._startingPointerTime = new Date().getTime();
  15356. if (!_this.pointerDownPredicate) {
  15357. _this.pointerDownPredicate = function (mesh) {
  15358. return mesh.isPickable && mesh.isVisible && mesh.isReady();
  15359. };
  15360. }
  15361. // Meshes
  15362. _this._pickedDownMesh = null;
  15363. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  15364. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  15365. _this._pickedDownMesh = pickResult.pickedMesh;
  15366. var actionManager = pickResult.pickedMesh.actionManager;
  15367. if (actionManager) {
  15368. if (actionManager.hasPickTriggers) {
  15369. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15370. switch (evt.button) {
  15371. case 0:
  15372. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15373. break;
  15374. case 1:
  15375. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15376. break;
  15377. case 2:
  15378. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15379. break;
  15380. }
  15381. }
  15382. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  15383. window.setTimeout((function () {
  15384. var _this = this;
  15385. 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);
  15386. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  15387. if (this._isButtonPressed &&
  15388. ((new Date().getTime() - this._startingPointerTime) > Scene.LongPressDelay) &&
  15389. (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold &&
  15390. Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold)) {
  15391. this._startingPointerTime = 0;
  15392. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15393. }
  15394. }
  15395. }).bind(_this), Scene.LongPressDelay);
  15396. }
  15397. }
  15398. }
  15399. if (_this.onPointerDown) {
  15400. _this.onPointerDown(evt, pickResult);
  15401. }
  15402. if (_this.onPointerObservable.hasObservers()) {
  15403. var type = PointerEventTypes.POINTERDOWN;
  15404. var pi = new PointerInfo(type, evt, pickResult);
  15405. _this.onPointerObservable.notifyObservers(pi, type);
  15406. }
  15407. // Sprites
  15408. _this._pickedDownSprite = null;
  15409. if (_this.spriteManagers.length > 0) {
  15410. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  15411. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  15412. if (pickResult.pickedSprite.actionManager) {
  15413. _this._pickedDownSprite = pickResult.pickedSprite;
  15414. switch (evt.button) {
  15415. case 0:
  15416. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  15417. break;
  15418. case 1:
  15419. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  15420. break;
  15421. case 2:
  15422. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  15423. break;
  15424. }
  15425. if (pickResult.pickedSprite.actionManager) {
  15426. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  15427. }
  15428. }
  15429. }
  15430. }
  15431. };
  15432. this._onPointerUp = function (evt) {
  15433. _this._isButtonPressed = false;
  15434. _this._pickedUpMesh = null;
  15435. _this._meshPickProceed = false;
  15436. _this._updatePointerPosition(evt);
  15437. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, (function (clickInfo, pickResult) {
  15438. // PreObservable support
  15439. if (this.onPrePointerObservable.hasObservers()) {
  15440. if (!clickInfo.ignore) {
  15441. if (!clickInfo.hasSwiped) {
  15442. if (clickInfo.singleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  15443. var type = PointerEventTypes.POINTERTAP;
  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. if (clickInfo.doubleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  15451. var type = PointerEventTypes.POINTERDOUBLETAP;
  15452. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  15453. this.onPrePointerObservable.notifyObservers(pi, type);
  15454. if (pi.skipOnPointerObservable) {
  15455. return;
  15456. }
  15457. }
  15458. }
  15459. }
  15460. else {
  15461. var type = PointerEventTypes.POINTERUP;
  15462. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  15463. this.onPrePointerObservable.notifyObservers(pi, type);
  15464. if (pi.skipOnPointerObservable) {
  15465. return;
  15466. }
  15467. }
  15468. }
  15469. if (!this.cameraToUseForPointers && !this.activeCamera) {
  15470. return;
  15471. }
  15472. if (!this.pointerUpPredicate) {
  15473. this.pointerUpPredicate = function (mesh) {
  15474. return mesh.isPickable && mesh.isVisible && mesh.isReady();
  15475. };
  15476. }
  15477. // Meshes
  15478. if (!this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || this.onPointerObservable.hasObservers())) {
  15479. this._initActionManager(null, clickInfo);
  15480. }
  15481. if (!pickResult) {
  15482. pickResult = this._currentPickResult;
  15483. }
  15484. if (pickResult && pickResult && pickResult.pickedMesh) {
  15485. this._pickedUpMesh = pickResult.pickedMesh;
  15486. if (this._pickedDownMesh === this._pickedUpMesh) {
  15487. if (this.onPointerPick) {
  15488. this.onPointerPick(evt, pickResult);
  15489. }
  15490. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  15491. var type = PointerEventTypes.POINTERPICK;
  15492. var pi = new PointerInfo(type, evt, pickResult);
  15493. this.onPointerObservable.notifyObservers(pi, type);
  15494. }
  15495. }
  15496. if (pickResult.pickedMesh.actionManager) {
  15497. if (clickInfo.ignore) {
  15498. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15499. }
  15500. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  15501. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15502. }
  15503. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  15504. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15505. }
  15506. }
  15507. }
  15508. if (this._pickedDownMesh &&
  15509. this._pickedDownMesh.actionManager &&
  15510. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  15511. this._pickedDownMesh !== this._pickedUpMesh) {
  15512. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  15513. }
  15514. if (this.onPointerUp) {
  15515. this.onPointerUp(evt, pickResult);
  15516. }
  15517. if (this.onPointerObservable.hasObservers()) {
  15518. if (!clickInfo.ignore) {
  15519. if (!clickInfo.hasSwiped) {
  15520. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  15521. var type = PointerEventTypes.POINTERTAP;
  15522. var pi = new PointerInfo(type, evt, pickResult);
  15523. this.onPointerObservable.notifyObservers(pi, type);
  15524. }
  15525. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  15526. var type = PointerEventTypes.POINTERDOUBLETAP;
  15527. var pi = new PointerInfo(type, evt, pickResult);
  15528. this.onPointerObservable.notifyObservers(pi, type);
  15529. }
  15530. }
  15531. }
  15532. else {
  15533. var type = PointerEventTypes.POINTERUP;
  15534. var pi = new PointerInfo(type, evt, pickResult);
  15535. this.onPointerObservable.notifyObservers(pi, type);
  15536. }
  15537. }
  15538. // Sprites
  15539. if (this.spriteManagers.length > 0) {
  15540. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, spritePredicate, false, this.cameraToUseForPointers);
  15541. if (pickResult.hit && pickResult.pickedSprite) {
  15542. if (pickResult.pickedSprite.actionManager) {
  15543. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  15544. if (pickResult.pickedSprite.actionManager) {
  15545. if (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold && Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold) {
  15546. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  15547. }
  15548. }
  15549. }
  15550. }
  15551. if (this._pickedDownSprite && this._pickedDownSprite.actionManager && this._pickedDownSprite !== pickResult.pickedSprite) {
  15552. this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pickedDownSprite, this, evt));
  15553. }
  15554. }
  15555. this._previousPickResult = this._currentPickResult;
  15556. }).bind(_this));
  15557. };
  15558. this._onKeyDown = function (evt) {
  15559. if (_this.actionManager) {
  15560. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  15561. }
  15562. };
  15563. this._onKeyUp = function (evt) {
  15564. if (_this.actionManager) {
  15565. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  15566. }
  15567. };
  15568. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  15569. var canvas = this._engine.getRenderingCanvas();
  15570. if (attachMove) {
  15571. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  15572. // Wheel
  15573. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  15574. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  15575. }
  15576. if (attachDown) {
  15577. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  15578. }
  15579. if (attachUp) {
  15580. canvas.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  15581. }
  15582. canvas.tabIndex = 1;
  15583. canvas.addEventListener("keydown", this._onKeyDown, false);
  15584. canvas.addEventListener("keyup", this._onKeyUp, false);
  15585. };
  15586. Scene.prototype.detachControl = function () {
  15587. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  15588. var canvas = this._engine.getRenderingCanvas();
  15589. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  15590. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  15591. canvas.removeEventListener(eventPrefix + "up", this._onPointerUp);
  15592. // Wheel
  15593. canvas.removeEventListener('mousewheel', this._onPointerMove);
  15594. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  15595. canvas.removeEventListener("keydown", this._onKeyDown);
  15596. canvas.removeEventListener("keyup", this._onKeyUp);
  15597. };
  15598. // Ready
  15599. Scene.prototype.isReady = function () {
  15600. if (this._pendingData.length > 0) {
  15601. return false;
  15602. }
  15603. var index;
  15604. // Geometries
  15605. for (index = 0; index < this._geometries.length; index++) {
  15606. var geometry = this._geometries[index];
  15607. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  15608. return false;
  15609. }
  15610. }
  15611. // Meshes
  15612. for (index = 0; index < this.meshes.length; index++) {
  15613. var mesh = this.meshes[index];
  15614. if (!mesh.isEnabled()) {
  15615. continue;
  15616. }
  15617. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  15618. continue;
  15619. }
  15620. if (!mesh.isReady()) {
  15621. return false;
  15622. }
  15623. var mat = mesh.material;
  15624. if (mat) {
  15625. if (!mat.isReady(mesh)) {
  15626. return false;
  15627. }
  15628. }
  15629. }
  15630. return true;
  15631. };
  15632. Scene.prototype.resetCachedMaterial = function () {
  15633. this._cachedMaterial = null;
  15634. this._cachedEffect = null;
  15635. };
  15636. Scene.prototype.registerBeforeRender = function (func) {
  15637. this.onBeforeRenderObservable.add(func);
  15638. };
  15639. Scene.prototype.unregisterBeforeRender = function (func) {
  15640. this.onBeforeRenderObservable.removeCallback(func);
  15641. };
  15642. Scene.prototype.registerAfterRender = function (func) {
  15643. this.onAfterRenderObservable.add(func);
  15644. };
  15645. Scene.prototype.unregisterAfterRender = function (func) {
  15646. this.onAfterRenderObservable.removeCallback(func);
  15647. };
  15648. Scene.prototype._addPendingData = function (data) {
  15649. this._pendingData.push(data);
  15650. };
  15651. Scene.prototype._removePendingData = function (data) {
  15652. var index = this._pendingData.indexOf(data);
  15653. if (index !== -1) {
  15654. this._pendingData.splice(index, 1);
  15655. }
  15656. };
  15657. Scene.prototype.getWaitingItemsCount = function () {
  15658. return this._pendingData.length;
  15659. };
  15660. /**
  15661. * Registers a function to be executed when the scene is ready.
  15662. * @param {Function} func - the function to be executed.
  15663. */
  15664. Scene.prototype.executeWhenReady = function (func) {
  15665. var _this = this;
  15666. this.onReadyObservable.add(func);
  15667. if (this._executeWhenReadyTimeoutId !== -1) {
  15668. return;
  15669. }
  15670. this._executeWhenReadyTimeoutId = setTimeout(function () {
  15671. _this._checkIsReady();
  15672. }, 150);
  15673. };
  15674. Scene.prototype._checkIsReady = function () {
  15675. var _this = this;
  15676. if (this.isReady()) {
  15677. this.onReadyObservable.notifyObservers(this);
  15678. this.onReadyObservable.clear();
  15679. this._executeWhenReadyTimeoutId = -1;
  15680. return;
  15681. }
  15682. this._executeWhenReadyTimeoutId = setTimeout(function () {
  15683. _this._checkIsReady();
  15684. }, 150);
  15685. };
  15686. // Animations
  15687. /**
  15688. * Will start the animation sequence of a given target
  15689. * @param target - the target
  15690. * @param {number} from - from which frame should animation start
  15691. * @param {number} to - till which frame should animation run.
  15692. * @param {boolean} [loop] - should the animation loop
  15693. * @param {number} [speedRatio] - the speed in which to run the animation
  15694. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  15695. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  15696. * @return {BABYLON.Animatable} the animatable object created for this animation
  15697. * @see BABYLON.Animatable
  15698. * @see http://doc.babylonjs.com/page.php?p=22081
  15699. */
  15700. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  15701. if (speedRatio === void 0) { speedRatio = 1.0; }
  15702. this.stopAnimation(target);
  15703. if (!animatable) {
  15704. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  15705. }
  15706. // Local animations
  15707. if (target.animations) {
  15708. animatable.appendAnimations(target, target.animations);
  15709. }
  15710. // Children animations
  15711. if (target.getAnimatables) {
  15712. var animatables = target.getAnimatables();
  15713. for (var index = 0; index < animatables.length; index++) {
  15714. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  15715. }
  15716. }
  15717. animatable.reset();
  15718. return animatable;
  15719. };
  15720. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  15721. if (speedRatio === undefined) {
  15722. speedRatio = 1.0;
  15723. }
  15724. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  15725. return animatable;
  15726. };
  15727. Scene.prototype.getAnimatableByTarget = function (target) {
  15728. for (var index = 0; index < this._activeAnimatables.length; index++) {
  15729. if (this._activeAnimatables[index].target === target) {
  15730. return this._activeAnimatables[index];
  15731. }
  15732. }
  15733. return null;
  15734. };
  15735. Object.defineProperty(Scene.prototype, "Animatables", {
  15736. get: function () {
  15737. return this._activeAnimatables;
  15738. },
  15739. enumerable: true,
  15740. configurable: true
  15741. });
  15742. /**
  15743. * Will stop the animation of the given target
  15744. * @param target - the target
  15745. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  15746. * @see beginAnimation
  15747. */
  15748. Scene.prototype.stopAnimation = function (target, animationName) {
  15749. var animatable = this.getAnimatableByTarget(target);
  15750. if (animatable) {
  15751. animatable.stop(animationName);
  15752. }
  15753. };
  15754. Scene.prototype._animate = function () {
  15755. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  15756. return;
  15757. }
  15758. // Getting time
  15759. var now = BABYLON.Tools.Now;
  15760. if (!this._animationTimeLast) {
  15761. if (this._pendingData.length > 0) {
  15762. return;
  15763. }
  15764. this._animationTimeLast = now;
  15765. }
  15766. var deltaTime = (now - this._animationTimeLast) * this.animationTimeScale;
  15767. this._animationTime += deltaTime;
  15768. this._animationTimeLast = now;
  15769. for (var index = 0; index < this._activeAnimatables.length; index++) {
  15770. this._activeAnimatables[index]._animate(this._animationTime);
  15771. }
  15772. };
  15773. // Matrix
  15774. Scene.prototype.getViewMatrix = function () {
  15775. return this._viewMatrix;
  15776. };
  15777. Scene.prototype.getProjectionMatrix = function () {
  15778. return this._projectionMatrix;
  15779. };
  15780. Scene.prototype.getTransformMatrix = function () {
  15781. return this._transformMatrix;
  15782. };
  15783. Scene.prototype.setTransformMatrix = function (view, projection) {
  15784. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  15785. return;
  15786. }
  15787. this._viewUpdateFlag = view.updateFlag;
  15788. this._projectionUpdateFlag = projection.updateFlag;
  15789. this._viewMatrix = view;
  15790. this._projectionMatrix = projection;
  15791. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  15792. // Update frustum
  15793. if (!this._frustumPlanes) {
  15794. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  15795. }
  15796. else {
  15797. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  15798. }
  15799. if (this._sceneUbo.useUbo) {
  15800. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  15801. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  15802. this._sceneUbo.update();
  15803. }
  15804. };
  15805. Scene.prototype.getSceneUniformBuffer = function () {
  15806. return this._sceneUbo;
  15807. };
  15808. // Methods
  15809. Scene.prototype.getUniqueId = function () {
  15810. var result = this._uniqueIdCounter;
  15811. this._uniqueIdCounter++;
  15812. return result;
  15813. };
  15814. Scene.prototype.addMesh = function (newMesh) {
  15815. newMesh.uniqueId = this.getUniqueId();
  15816. var position = this.meshes.push(newMesh);
  15817. //notify the collision coordinator
  15818. if (this.collisionCoordinator) {
  15819. this.collisionCoordinator.onMeshAdded(newMesh);
  15820. }
  15821. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  15822. };
  15823. Scene.prototype.removeMesh = function (toRemove) {
  15824. var index = this.meshes.indexOf(toRemove);
  15825. if (index !== -1) {
  15826. // Remove from the scene if mesh found
  15827. this.meshes.splice(index, 1);
  15828. }
  15829. //notify the collision coordinator
  15830. if (this.collisionCoordinator) {
  15831. this.collisionCoordinator.onMeshRemoved(toRemove);
  15832. }
  15833. this.onMeshRemovedObservable.notifyObservers(toRemove);
  15834. return index;
  15835. };
  15836. Scene.prototype.removeSkeleton = function (toRemove) {
  15837. var index = this.skeletons.indexOf(toRemove);
  15838. if (index !== -1) {
  15839. // Remove from the scene if found
  15840. this.skeletons.splice(index, 1);
  15841. }
  15842. return index;
  15843. };
  15844. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  15845. var index = this.morphTargetManagers.indexOf(toRemove);
  15846. if (index !== -1) {
  15847. // Remove from the scene if found
  15848. this.morphTargetManagers.splice(index, 1);
  15849. }
  15850. return index;
  15851. };
  15852. Scene.prototype.removeLight = function (toRemove) {
  15853. var index = this.lights.indexOf(toRemove);
  15854. if (index !== -1) {
  15855. // Remove from the scene if mesh found
  15856. this.lights.splice(index, 1);
  15857. }
  15858. this.onLightRemovedObservable.notifyObservers(toRemove);
  15859. return index;
  15860. };
  15861. Scene.prototype.removeCamera = function (toRemove) {
  15862. var index = this.cameras.indexOf(toRemove);
  15863. if (index !== -1) {
  15864. // Remove from the scene if mesh found
  15865. this.cameras.splice(index, 1);
  15866. }
  15867. // Remove from activeCameras
  15868. var index2 = this.activeCameras.indexOf(toRemove);
  15869. if (index2 !== -1) {
  15870. // Remove from the scene if mesh found
  15871. this.activeCameras.splice(index2, 1);
  15872. }
  15873. // Reset the activeCamera
  15874. if (this.activeCamera === toRemove) {
  15875. if (this.cameras.length > 0) {
  15876. this.activeCamera = this.cameras[0];
  15877. }
  15878. else {
  15879. this.activeCamera = null;
  15880. }
  15881. }
  15882. this.onCameraRemovedObservable.notifyObservers(toRemove);
  15883. return index;
  15884. };
  15885. Scene.prototype.addLight = function (newLight) {
  15886. newLight.uniqueId = this.getUniqueId();
  15887. var position = this.lights.push(newLight);
  15888. this.onNewLightAddedObservable.notifyObservers(newLight);
  15889. };
  15890. Scene.prototype.addCamera = function (newCamera) {
  15891. newCamera.uniqueId = this.getUniqueId();
  15892. var position = this.cameras.push(newCamera);
  15893. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  15894. };
  15895. /**
  15896. * Switch active camera
  15897. * @param {Camera} newCamera - new active camera
  15898. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  15899. */
  15900. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  15901. if (attachControl === void 0) { attachControl = true; }
  15902. var canvas = this._engine.getRenderingCanvas();
  15903. this.activeCamera.detachControl(canvas);
  15904. this.activeCamera = newCamera;
  15905. if (attachControl) {
  15906. newCamera.attachControl(canvas);
  15907. }
  15908. };
  15909. /**
  15910. * sets the active camera of the scene using its ID
  15911. * @param {string} id - the camera's ID
  15912. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  15913. * @see activeCamera
  15914. */
  15915. Scene.prototype.setActiveCameraByID = function (id) {
  15916. var camera = this.getCameraByID(id);
  15917. if (camera) {
  15918. this.activeCamera = camera;
  15919. return camera;
  15920. }
  15921. return null;
  15922. };
  15923. /**
  15924. * sets the active camera of the scene using its name
  15925. * @param {string} name - the camera's name
  15926. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  15927. * @see activeCamera
  15928. */
  15929. Scene.prototype.setActiveCameraByName = function (name) {
  15930. var camera = this.getCameraByName(name);
  15931. if (camera) {
  15932. this.activeCamera = camera;
  15933. return camera;
  15934. }
  15935. return null;
  15936. };
  15937. /**
  15938. * get a material using its id
  15939. * @param {string} the material's ID
  15940. * @return {BABYLON.Material|null} the material or null if none found.
  15941. */
  15942. Scene.prototype.getMaterialByID = function (id) {
  15943. for (var index = 0; index < this.materials.length; index++) {
  15944. if (this.materials[index].id === id) {
  15945. return this.materials[index];
  15946. }
  15947. }
  15948. return null;
  15949. };
  15950. /**
  15951. * get a material using its name
  15952. * @param {string} the material's name
  15953. * @return {BABYLON.Material|null} the material or null if none found.
  15954. */
  15955. Scene.prototype.getMaterialByName = function (name) {
  15956. for (var index = 0; index < this.materials.length; index++) {
  15957. if (this.materials[index].name === name) {
  15958. return this.materials[index];
  15959. }
  15960. }
  15961. return null;
  15962. };
  15963. Scene.prototype.getLensFlareSystemByName = function (name) {
  15964. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  15965. if (this.lensFlareSystems[index].name === name) {
  15966. return this.lensFlareSystems[index];
  15967. }
  15968. }
  15969. return null;
  15970. };
  15971. Scene.prototype.getLensFlareSystemByID = function (id) {
  15972. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  15973. if (this.lensFlareSystems[index].id === id) {
  15974. return this.lensFlareSystems[index];
  15975. }
  15976. }
  15977. return null;
  15978. };
  15979. Scene.prototype.getCameraByID = function (id) {
  15980. for (var index = 0; index < this.cameras.length; index++) {
  15981. if (this.cameras[index].id === id) {
  15982. return this.cameras[index];
  15983. }
  15984. }
  15985. return null;
  15986. };
  15987. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  15988. for (var index = 0; index < this.cameras.length; index++) {
  15989. if (this.cameras[index].uniqueId === uniqueId) {
  15990. return this.cameras[index];
  15991. }
  15992. }
  15993. return null;
  15994. };
  15995. /**
  15996. * get a camera using its name
  15997. * @param {string} the camera's name
  15998. * @return {BABYLON.Camera|null} the camera or null if none found.
  15999. */
  16000. Scene.prototype.getCameraByName = function (name) {
  16001. for (var index = 0; index < this.cameras.length; index++) {
  16002. if (this.cameras[index].name === name) {
  16003. return this.cameras[index];
  16004. }
  16005. }
  16006. return null;
  16007. };
  16008. /**
  16009. * get a bone using its id
  16010. * @param {string} the bone's id
  16011. * @return {BABYLON.Bone|null} the bone or null if not found
  16012. */
  16013. Scene.prototype.getBoneByID = function (id) {
  16014. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  16015. var skeleton = this.skeletons[skeletonIndex];
  16016. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  16017. if (skeleton.bones[boneIndex].id === id) {
  16018. return skeleton.bones[boneIndex];
  16019. }
  16020. }
  16021. }
  16022. return null;
  16023. };
  16024. /**
  16025. * get a bone using its id
  16026. * @param {string} the bone's name
  16027. * @return {BABYLON.Bone|null} the bone or null if not found
  16028. */
  16029. Scene.prototype.getBoneByName = function (name) {
  16030. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  16031. var skeleton = this.skeletons[skeletonIndex];
  16032. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  16033. if (skeleton.bones[boneIndex].name === name) {
  16034. return skeleton.bones[boneIndex];
  16035. }
  16036. }
  16037. }
  16038. return null;
  16039. };
  16040. /**
  16041. * get a light node using its name
  16042. * @param {string} the light's name
  16043. * @return {BABYLON.Light|null} the light or null if none found.
  16044. */
  16045. Scene.prototype.getLightByName = function (name) {
  16046. for (var index = 0; index < this.lights.length; index++) {
  16047. if (this.lights[index].name === name) {
  16048. return this.lights[index];
  16049. }
  16050. }
  16051. return null;
  16052. };
  16053. /**
  16054. * get a light node using its ID
  16055. * @param {string} the light's id
  16056. * @return {BABYLON.Light|null} the light or null if none found.
  16057. */
  16058. Scene.prototype.getLightByID = function (id) {
  16059. for (var index = 0; index < this.lights.length; index++) {
  16060. if (this.lights[index].id === id) {
  16061. return this.lights[index];
  16062. }
  16063. }
  16064. return null;
  16065. };
  16066. /**
  16067. * get a light node using its scene-generated unique ID
  16068. * @param {number} the light's unique id
  16069. * @return {BABYLON.Light|null} the light or null if none found.
  16070. */
  16071. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  16072. for (var index = 0; index < this.lights.length; index++) {
  16073. if (this.lights[index].uniqueId === uniqueId) {
  16074. return this.lights[index];
  16075. }
  16076. }
  16077. return null;
  16078. };
  16079. /**
  16080. * get a particle system by id
  16081. * @param id {number} the particle system id
  16082. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  16083. */
  16084. Scene.prototype.getParticleSystemByID = function (id) {
  16085. for (var index = 0; index < this.particleSystems.length; index++) {
  16086. if (this.particleSystems[index].id === id) {
  16087. return this.particleSystems[index];
  16088. }
  16089. }
  16090. return null;
  16091. };
  16092. /**
  16093. * get a geometry using its ID
  16094. * @param {string} the geometry's id
  16095. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  16096. */
  16097. Scene.prototype.getGeometryByID = function (id) {
  16098. for (var index = 0; index < this._geometries.length; index++) {
  16099. if (this._geometries[index].id === id) {
  16100. return this._geometries[index];
  16101. }
  16102. }
  16103. return null;
  16104. };
  16105. /**
  16106. * add a new geometry to this scene.
  16107. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  16108. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  16109. * @return {boolean} was the geometry added or not
  16110. */
  16111. Scene.prototype.pushGeometry = function (geometry, force) {
  16112. if (!force && this.getGeometryByID(geometry.id)) {
  16113. return false;
  16114. }
  16115. this._geometries.push(geometry);
  16116. //notify the collision coordinator
  16117. if (this.collisionCoordinator) {
  16118. this.collisionCoordinator.onGeometryAdded(geometry);
  16119. }
  16120. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  16121. return true;
  16122. };
  16123. /**
  16124. * Removes an existing geometry
  16125. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  16126. * @return {boolean} was the geometry removed or not
  16127. */
  16128. Scene.prototype.removeGeometry = function (geometry) {
  16129. var index = this._geometries.indexOf(geometry);
  16130. if (index > -1) {
  16131. this._geometries.splice(index, 1);
  16132. //notify the collision coordinator
  16133. if (this.collisionCoordinator) {
  16134. this.collisionCoordinator.onGeometryDeleted(geometry);
  16135. }
  16136. this.onGeometryRemovedObservable.notifyObservers(geometry);
  16137. return true;
  16138. }
  16139. return false;
  16140. };
  16141. Scene.prototype.getGeometries = function () {
  16142. return this._geometries;
  16143. };
  16144. /**
  16145. * Get the first added mesh found of a given ID
  16146. * @param {string} id - the id to search for
  16147. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  16148. */
  16149. Scene.prototype.getMeshByID = function (id) {
  16150. for (var index = 0; index < this.meshes.length; index++) {
  16151. if (this.meshes[index].id === id) {
  16152. return this.meshes[index];
  16153. }
  16154. }
  16155. return null;
  16156. };
  16157. Scene.prototype.getMeshesByID = function (id) {
  16158. return this.meshes.filter(function (m) {
  16159. return m.id === id;
  16160. });
  16161. };
  16162. /**
  16163. * Get a mesh with its auto-generated unique id
  16164. * @param {number} uniqueId - the unique id to search for
  16165. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  16166. */
  16167. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  16168. for (var index = 0; index < this.meshes.length; index++) {
  16169. if (this.meshes[index].uniqueId === uniqueId) {
  16170. return this.meshes[index];
  16171. }
  16172. }
  16173. return null;
  16174. };
  16175. /**
  16176. * Get a the last added mesh found of a given ID
  16177. * @param {string} id - the id to search for
  16178. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  16179. */
  16180. Scene.prototype.getLastMeshByID = function (id) {
  16181. for (var index = this.meshes.length - 1; index >= 0; index--) {
  16182. if (this.meshes[index].id === id) {
  16183. return this.meshes[index];
  16184. }
  16185. }
  16186. return null;
  16187. };
  16188. /**
  16189. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  16190. * @param {string} id - the id to search for
  16191. * @return {BABYLON.Node|null} the node found or null if not found at all.
  16192. */
  16193. Scene.prototype.getLastEntryByID = function (id) {
  16194. var index;
  16195. for (index = this.meshes.length - 1; index >= 0; index--) {
  16196. if (this.meshes[index].id === id) {
  16197. return this.meshes[index];
  16198. }
  16199. }
  16200. for (index = this.cameras.length - 1; index >= 0; index--) {
  16201. if (this.cameras[index].id === id) {
  16202. return this.cameras[index];
  16203. }
  16204. }
  16205. for (index = this.lights.length - 1; index >= 0; index--) {
  16206. if (this.lights[index].id === id) {
  16207. return this.lights[index];
  16208. }
  16209. }
  16210. return null;
  16211. };
  16212. Scene.prototype.getNodeByID = function (id) {
  16213. var mesh = this.getMeshByID(id);
  16214. if (mesh) {
  16215. return mesh;
  16216. }
  16217. var light = this.getLightByID(id);
  16218. if (light) {
  16219. return light;
  16220. }
  16221. var camera = this.getCameraByID(id);
  16222. if (camera) {
  16223. return camera;
  16224. }
  16225. var bone = this.getBoneByID(id);
  16226. return bone;
  16227. };
  16228. Scene.prototype.getNodeByName = function (name) {
  16229. var mesh = this.getMeshByName(name);
  16230. if (mesh) {
  16231. return mesh;
  16232. }
  16233. var light = this.getLightByName(name);
  16234. if (light) {
  16235. return light;
  16236. }
  16237. var camera = this.getCameraByName(name);
  16238. if (camera) {
  16239. return camera;
  16240. }
  16241. var bone = this.getBoneByName(name);
  16242. return bone;
  16243. };
  16244. Scene.prototype.getMeshByName = function (name) {
  16245. for (var index = 0; index < this.meshes.length; index++) {
  16246. if (this.meshes[index].name === name) {
  16247. return this.meshes[index];
  16248. }
  16249. }
  16250. return null;
  16251. };
  16252. Scene.prototype.getSoundByName = function (name) {
  16253. var index;
  16254. if (BABYLON.AudioEngine) {
  16255. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  16256. if (this.mainSoundTrack.soundCollection[index].name === name) {
  16257. return this.mainSoundTrack.soundCollection[index];
  16258. }
  16259. }
  16260. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  16261. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  16262. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  16263. return this.soundTracks[sdIndex].soundCollection[index];
  16264. }
  16265. }
  16266. }
  16267. }
  16268. return null;
  16269. };
  16270. Scene.prototype.getLastSkeletonByID = function (id) {
  16271. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  16272. if (this.skeletons[index].id === id) {
  16273. return this.skeletons[index];
  16274. }
  16275. }
  16276. return null;
  16277. };
  16278. Scene.prototype.getSkeletonById = function (id) {
  16279. for (var index = 0; index < this.skeletons.length; index++) {
  16280. if (this.skeletons[index].id === id) {
  16281. return this.skeletons[index];
  16282. }
  16283. }
  16284. return null;
  16285. };
  16286. Scene.prototype.getSkeletonByName = function (name) {
  16287. for (var index = 0; index < this.skeletons.length; index++) {
  16288. if (this.skeletons[index].name === name) {
  16289. return this.skeletons[index];
  16290. }
  16291. }
  16292. return null;
  16293. };
  16294. Scene.prototype.getMorphTargetManagerById = function (id) {
  16295. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  16296. if (this.morphTargetManagers[index].uniqueId === id) {
  16297. return this.morphTargetManagers[index];
  16298. }
  16299. }
  16300. return null;
  16301. };
  16302. Scene.prototype.isActiveMesh = function (mesh) {
  16303. return (this._activeMeshes.indexOf(mesh) !== -1);
  16304. };
  16305. /**
  16306. * Return a the first highlight layer of the scene with a given name.
  16307. * @param name The name of the highlight layer to look for.
  16308. * @return The highlight layer if found otherwise null.
  16309. */
  16310. Scene.prototype.getHighlightLayerByName = function (name) {
  16311. for (var index = 0; index < this.highlightLayers.length; index++) {
  16312. if (this.highlightLayers[index].name === name) {
  16313. return this.highlightLayers[index];
  16314. }
  16315. }
  16316. return null;
  16317. };
  16318. Object.defineProperty(Scene.prototype, "uid", {
  16319. /**
  16320. * Return a unique id as a string which can serve as an identifier for the scene
  16321. */
  16322. get: function () {
  16323. if (!this._uid) {
  16324. this._uid = BABYLON.Tools.RandomId();
  16325. }
  16326. return this._uid;
  16327. },
  16328. enumerable: true,
  16329. configurable: true
  16330. });
  16331. /**
  16332. * Add an externaly attached data from its key.
  16333. * This method call will fail and return false, if such key already exists.
  16334. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16335. * @param key the unique key that identifies the data
  16336. * @param data the data object to associate to the key for this Engine instance
  16337. * @return true if no such key were already present and the data was added successfully, false otherwise
  16338. */
  16339. Scene.prototype.addExternalData = function (key, data) {
  16340. if (!this._externalData) {
  16341. this._externalData = new BABYLON.StringDictionary();
  16342. }
  16343. return this._externalData.add(key, data);
  16344. };
  16345. /**
  16346. * Get an externaly attached data from its key
  16347. * @param key the unique key that identifies the data
  16348. * @return the associated data, if present (can be null), or undefined if not present
  16349. */
  16350. Scene.prototype.getExternalData = function (key) {
  16351. if (!this._externalData) {
  16352. return null;
  16353. }
  16354. return this._externalData.get(key);
  16355. };
  16356. /**
  16357. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16358. * @param key the unique key that identifies the data
  16359. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16360. * @return the associated data, can be null if the factory returned null.
  16361. */
  16362. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16363. if (!this._externalData) {
  16364. this._externalData = new BABYLON.StringDictionary();
  16365. }
  16366. return this._externalData.getOrAddWithFactory(key, factory);
  16367. };
  16368. /**
  16369. * Remove an externaly attached data from the Engine instance
  16370. * @param key the unique key that identifies the data
  16371. * @return true if the data was successfully removed, false if it doesn't exist
  16372. */
  16373. Scene.prototype.removeExternalData = function (key) {
  16374. return this._externalData.remove(key);
  16375. };
  16376. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  16377. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  16378. var material = subMesh.getMaterial();
  16379. if (mesh.showSubMeshesBoundingBox) {
  16380. this.getBoundingBoxRenderer().renderList.push(subMesh.getBoundingInfo().boundingBox);
  16381. }
  16382. if (material) {
  16383. // Render targets
  16384. if (material.getRenderTargetTextures) {
  16385. if (this._processedMaterials.indexOf(material) === -1) {
  16386. this._processedMaterials.push(material);
  16387. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  16388. }
  16389. }
  16390. // Dispatch
  16391. this._activeIndices.addCount(subMesh.indexCount, false);
  16392. this._renderingManager.dispatch(subMesh);
  16393. }
  16394. }
  16395. };
  16396. Scene.prototype._isInIntermediateRendering = function () {
  16397. return this._intermediateRendering;
  16398. };
  16399. Scene.prototype._evaluateActiveMeshes = function () {
  16400. this.activeCamera._activeMeshes.reset();
  16401. this._activeMeshes.reset();
  16402. this._renderingManager.reset();
  16403. this._processedMaterials.reset();
  16404. this._activeParticleSystems.reset();
  16405. this._activeSkeletons.reset();
  16406. this._softwareSkinnedMeshes.reset();
  16407. if (this._boundingBoxRenderer) {
  16408. this._boundingBoxRenderer.reset();
  16409. }
  16410. this._edgesRenderers.reset();
  16411. // Meshes
  16412. var meshes;
  16413. var len;
  16414. if (this._selectionOctree) {
  16415. var selection = this._selectionOctree.select(this._frustumPlanes);
  16416. meshes = selection.data;
  16417. len = selection.length;
  16418. }
  16419. else {
  16420. len = this.meshes.length;
  16421. meshes = this.meshes;
  16422. }
  16423. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  16424. var mesh = meshes[meshIndex];
  16425. if (mesh.isBlocked) {
  16426. continue;
  16427. }
  16428. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  16429. if (!mesh.isReady() || !mesh.isEnabled()) {
  16430. continue;
  16431. }
  16432. mesh.computeWorldMatrix();
  16433. // Intersections
  16434. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  16435. this._meshesForIntersections.pushNoDuplicate(mesh);
  16436. }
  16437. // Switch to current LOD
  16438. var meshLOD = mesh.getLOD(this.activeCamera);
  16439. if (!meshLOD) {
  16440. continue;
  16441. }
  16442. mesh._preActivate();
  16443. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  16444. this._activeMeshes.push(mesh);
  16445. this.activeCamera._activeMeshes.push(mesh);
  16446. mesh._activate(this._renderId);
  16447. this._activeMesh(mesh, meshLOD);
  16448. }
  16449. }
  16450. // Particle systems
  16451. this._particlesDuration.beginMonitoring();
  16452. var beforeParticlesDate = BABYLON.Tools.Now;
  16453. if (this.particlesEnabled) {
  16454. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  16455. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  16456. var particleSystem = this.particleSystems[particleIndex];
  16457. if (!particleSystem.isStarted()) {
  16458. continue;
  16459. }
  16460. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  16461. this._activeParticleSystems.push(particleSystem);
  16462. particleSystem.animate();
  16463. this._renderingManager.dispatchParticles(particleSystem);
  16464. }
  16465. }
  16466. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  16467. }
  16468. this._particlesDuration.endMonitoring(false);
  16469. };
  16470. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  16471. if (mesh.skeleton && this.skeletonsEnabled) {
  16472. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  16473. mesh.skeleton.prepare();
  16474. }
  16475. if (!mesh.computeBonesUsingShaders) {
  16476. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  16477. }
  16478. }
  16479. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  16480. this.getBoundingBoxRenderer().renderList.push(sourceMesh.getBoundingInfo().boundingBox);
  16481. }
  16482. if (sourceMesh._edgesRenderer) {
  16483. this._edgesRenderers.push(sourceMesh._edgesRenderer);
  16484. }
  16485. if (mesh && mesh.subMeshes) {
  16486. // Submeshes Octrees
  16487. var len;
  16488. var subMeshes;
  16489. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  16490. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  16491. len = intersections.length;
  16492. subMeshes = intersections.data;
  16493. }
  16494. else {
  16495. subMeshes = mesh.subMeshes;
  16496. len = subMeshes.length;
  16497. }
  16498. for (var subIndex = 0; subIndex < len; subIndex++) {
  16499. var subMesh = subMeshes[subIndex];
  16500. this._evaluateSubMesh(subMesh, mesh);
  16501. }
  16502. }
  16503. };
  16504. Scene.prototype.updateTransformMatrix = function (force) {
  16505. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  16506. };
  16507. Scene.prototype._renderForCamera = function (camera) {
  16508. var engine = this._engine;
  16509. var startTime = BABYLON.Tools.Now;
  16510. this.activeCamera = camera;
  16511. if (!this.activeCamera)
  16512. throw new Error("Active camera not set");
  16513. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  16514. // Viewport
  16515. engine.setViewport(this.activeCamera.viewport);
  16516. // Camera
  16517. this.resetCachedMaterial();
  16518. this._renderId++;
  16519. this.updateTransformMatrix();
  16520. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  16521. // Meshes
  16522. this._evaluateActiveMeshesDuration.beginMonitoring();
  16523. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  16524. this._evaluateActiveMeshes();
  16525. this._evaluateActiveMeshesDuration.endMonitoring(false);
  16526. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  16527. // Software skinning
  16528. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  16529. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  16530. mesh.applySkeleton(mesh.skeleton);
  16531. }
  16532. // Render targets
  16533. this._renderTargetsDuration.beginMonitoring();
  16534. var needsRestoreFrameBuffer = false;
  16535. var beforeRenderTargetDate = BABYLON.Tools.Now;
  16536. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  16537. this._intermediateRendering = true;
  16538. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  16539. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  16540. var renderTarget = this._renderTargets.data[renderIndex];
  16541. if (renderTarget._shouldRender()) {
  16542. this._renderId++;
  16543. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  16544. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  16545. }
  16546. }
  16547. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  16548. this._intermediateRendering = false;
  16549. this._renderId++;
  16550. needsRestoreFrameBuffer = true; // Restore back buffer
  16551. }
  16552. // Render HighlightLayer Texture
  16553. var stencilState = this._engine.getStencilBuffer();
  16554. var renderhighlights = false;
  16555. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  16556. this._intermediateRendering = true;
  16557. for (var i = 0; i < this.highlightLayers.length; i++) {
  16558. var highlightLayer = this.highlightLayers[i];
  16559. if (highlightLayer.shouldRender() &&
  16560. (!highlightLayer.camera ||
  16561. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  16562. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  16563. renderhighlights = true;
  16564. var renderTarget = highlightLayer._mainTexture;
  16565. if (renderTarget._shouldRender()) {
  16566. this._renderId++;
  16567. renderTarget.render(false, false);
  16568. needsRestoreFrameBuffer = true;
  16569. }
  16570. }
  16571. }
  16572. this._intermediateRendering = false;
  16573. this._renderId++;
  16574. }
  16575. if (needsRestoreFrameBuffer) {
  16576. engine.restoreDefaultFramebuffer();
  16577. }
  16578. this._renderTargetsDuration.endMonitoring(false);
  16579. // Prepare Frame
  16580. this.postProcessManager._prepareFrame();
  16581. this._renderDuration.beginMonitoring();
  16582. // Backgrounds
  16583. var layerIndex;
  16584. var layer;
  16585. if (this.layers.length) {
  16586. engine.setDepthBuffer(false);
  16587. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  16588. layer = this.layers[layerIndex];
  16589. if (layer.isBackground) {
  16590. layer.render();
  16591. }
  16592. }
  16593. engine.setDepthBuffer(true);
  16594. }
  16595. // Render
  16596. BABYLON.Tools.StartPerformanceCounter("Main render");
  16597. // Activate HighlightLayer stencil
  16598. if (renderhighlights) {
  16599. this._engine.setStencilBuffer(true);
  16600. }
  16601. this._renderingManager.render(null, null, true, true);
  16602. // Restore HighlightLayer stencil
  16603. if (renderhighlights) {
  16604. this._engine.setStencilBuffer(stencilState);
  16605. }
  16606. BABYLON.Tools.EndPerformanceCounter("Main render");
  16607. // Bounding boxes
  16608. if (this._boundingBoxRenderer) {
  16609. this._boundingBoxRenderer.render();
  16610. }
  16611. // Edges
  16612. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  16613. this._edgesRenderers.data[edgesRendererIndex].render();
  16614. }
  16615. // Lens flares
  16616. if (this.lensFlaresEnabled) {
  16617. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  16618. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  16619. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  16620. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  16621. lensFlareSystem.render();
  16622. }
  16623. }
  16624. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  16625. }
  16626. // Foregrounds
  16627. if (this.layers.length) {
  16628. engine.setDepthBuffer(false);
  16629. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  16630. layer = this.layers[layerIndex];
  16631. if (!layer.isBackground) {
  16632. layer.render();
  16633. }
  16634. }
  16635. engine.setDepthBuffer(true);
  16636. }
  16637. // Highlight Layer
  16638. if (renderhighlights) {
  16639. engine.setDepthBuffer(false);
  16640. for (var i = 0; i < this.highlightLayers.length; i++) {
  16641. if (this.highlightLayers[i].shouldRender()) {
  16642. this.highlightLayers[i].render();
  16643. }
  16644. }
  16645. engine.setDepthBuffer(true);
  16646. }
  16647. this._renderDuration.endMonitoring(false);
  16648. // Finalize frame
  16649. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  16650. // Update camera
  16651. this.activeCamera._updateFromScene();
  16652. // Reset some special arrays
  16653. this._renderTargets.reset();
  16654. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  16655. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  16656. };
  16657. Scene.prototype._processSubCameras = function (camera) {
  16658. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  16659. this._renderForCamera(camera);
  16660. return;
  16661. }
  16662. // rig cameras
  16663. for (var index = 0; index < camera._rigCameras.length; index++) {
  16664. this._renderForCamera(camera._rigCameras[index]);
  16665. }
  16666. this.activeCamera = camera;
  16667. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  16668. // Update camera
  16669. this.activeCamera._updateFromScene();
  16670. };
  16671. Scene.prototype._checkIntersections = function () {
  16672. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  16673. var sourceMesh = this._meshesForIntersections.data[index];
  16674. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  16675. var action = sourceMesh.actionManager.actions[actionIndex];
  16676. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  16677. var parameters = action.getTriggerParameter();
  16678. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  16679. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  16680. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  16681. if (areIntersecting && currentIntersectionInProgress === -1) {
  16682. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  16683. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  16684. sourceMesh._intersectionsInProgress.push(otherMesh);
  16685. }
  16686. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  16687. sourceMesh._intersectionsInProgress.push(otherMesh);
  16688. }
  16689. }
  16690. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  16691. //They intersected, and now they don't.
  16692. //is this trigger an exit trigger? execute an event.
  16693. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  16694. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  16695. }
  16696. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  16697. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  16698. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  16699. }
  16700. }
  16701. }
  16702. }
  16703. }
  16704. };
  16705. Scene.prototype.render = function () {
  16706. if (this.isDisposed) {
  16707. return;
  16708. }
  16709. this._lastFrameDuration.beginMonitoring();
  16710. this._particlesDuration.fetchNewFrame();
  16711. this._spritesDuration.fetchNewFrame();
  16712. this._activeParticles.fetchNewFrame();
  16713. this._renderDuration.fetchNewFrame();
  16714. this._renderTargetsDuration.fetchNewFrame();
  16715. this._evaluateActiveMeshesDuration.fetchNewFrame();
  16716. this._totalVertices.fetchNewFrame();
  16717. this._activeIndices.fetchNewFrame();
  16718. this._activeBones.fetchNewFrame();
  16719. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  16720. this._meshesForIntersections.reset();
  16721. this.resetCachedMaterial();
  16722. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  16723. // Actions
  16724. if (this.actionManager) {
  16725. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  16726. }
  16727. //Simplification Queue
  16728. if (this.simplificationQueue && !this.simplificationQueue.running) {
  16729. this.simplificationQueue.executeNext();
  16730. }
  16731. // Animations
  16732. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  16733. this._animationRatio = deltaTime * (60.0 / 1000.0);
  16734. this._animate();
  16735. // Physics
  16736. if (this._physicsEngine) {
  16737. BABYLON.Tools.StartPerformanceCounter("Physics");
  16738. this._physicsEngine._step(deltaTime / 1000.0);
  16739. BABYLON.Tools.EndPerformanceCounter("Physics");
  16740. }
  16741. // Before render
  16742. this.onBeforeRenderObservable.notifyObservers(this);
  16743. // Customs render targets
  16744. this._renderTargetsDuration.beginMonitoring();
  16745. var beforeRenderTargetDate = BABYLON.Tools.Now;
  16746. var engine = this.getEngine();
  16747. var currentActiveCamera = this.activeCamera;
  16748. if (this.renderTargetsEnabled) {
  16749. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  16750. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  16751. var renderTarget = this.customRenderTargets[customIndex];
  16752. if (renderTarget._shouldRender()) {
  16753. this._renderId++;
  16754. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  16755. if (!this.activeCamera)
  16756. throw new Error("Active camera not set");
  16757. // Viewport
  16758. engine.setViewport(this.activeCamera.viewport);
  16759. // Camera
  16760. this.updateTransformMatrix();
  16761. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  16762. }
  16763. }
  16764. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  16765. this._renderId++;
  16766. }
  16767. if (this.customRenderTargets.length > 0) {
  16768. engine.restoreDefaultFramebuffer();
  16769. }
  16770. this._renderTargetsDuration.endMonitoring();
  16771. this.activeCamera = currentActiveCamera;
  16772. // Procedural textures
  16773. if (this.proceduralTexturesEnabled) {
  16774. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  16775. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  16776. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  16777. if (proceduralTexture._shouldRender()) {
  16778. proceduralTexture.render();
  16779. }
  16780. }
  16781. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  16782. }
  16783. // Clear
  16784. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true, true);
  16785. // Shadows
  16786. if (this.shadowsEnabled) {
  16787. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  16788. var light = this.lights[lightIndex];
  16789. var shadowGenerator = light.getShadowGenerator();
  16790. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  16791. this._renderTargets.push(shadowGenerator.getShadowMap());
  16792. }
  16793. }
  16794. }
  16795. // Depth renderer
  16796. if (this._depthRenderer) {
  16797. this._renderTargets.push(this._depthRenderer.getDepthMap());
  16798. }
  16799. // RenderPipeline
  16800. if (this._postProcessRenderPipelineManager) {
  16801. this._postProcessRenderPipelineManager.update();
  16802. }
  16803. // Multi-cameras?
  16804. if (this.activeCameras.length > 0) {
  16805. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  16806. if (cameraIndex > 0) {
  16807. this._engine.clear(null, false, true, true);
  16808. }
  16809. this._processSubCameras(this.activeCameras[cameraIndex]);
  16810. }
  16811. }
  16812. else {
  16813. if (!this.activeCamera) {
  16814. throw new Error("No camera defined");
  16815. }
  16816. this._processSubCameras(this.activeCamera);
  16817. }
  16818. // Intersection checks
  16819. this._checkIntersections();
  16820. // Update the audio listener attached to the camera
  16821. if (BABYLON.AudioEngine) {
  16822. this._updateAudioParameters();
  16823. }
  16824. // After render
  16825. if (this.afterRender) {
  16826. this.afterRender();
  16827. }
  16828. this.onAfterRenderObservable.notifyObservers(this);
  16829. // Cleaning
  16830. for (var index = 0; index < this._toBeDisposed.length; index++) {
  16831. this._toBeDisposed.data[index].dispose();
  16832. this._toBeDisposed[index] = null;
  16833. }
  16834. this._toBeDisposed.reset();
  16835. if (this.dumpNextRenderTargets) {
  16836. this.dumpNextRenderTargets = false;
  16837. }
  16838. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  16839. this._lastFrameDuration.endMonitoring();
  16840. this._totalMeshesCounter.addCount(this.meshes.length, true);
  16841. this._totalLightsCounter.addCount(this.lights.length, true);
  16842. this._totalMaterialsCounter.addCount(this.materials.length, true);
  16843. this._totalTexturesCounter.addCount(this.textures.length, true);
  16844. this._activeBones.addCount(0, true);
  16845. this._activeIndices.addCount(0, true);
  16846. this._activeParticles.addCount(0, true);
  16847. };
  16848. Scene.prototype._updateAudioParameters = function () {
  16849. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  16850. return;
  16851. }
  16852. var listeningCamera;
  16853. var audioEngine = BABYLON.Engine.audioEngine;
  16854. if (this.activeCameras.length > 0) {
  16855. listeningCamera = this.activeCameras[0];
  16856. }
  16857. else {
  16858. listeningCamera = this.activeCamera;
  16859. }
  16860. if (listeningCamera && audioEngine.canUseWebAudio) {
  16861. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  16862. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  16863. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  16864. cameraDirection.normalize();
  16865. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  16866. var i;
  16867. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  16868. var sound = this.mainSoundTrack.soundCollection[i];
  16869. if (sound.useCustomAttenuation) {
  16870. sound.updateDistanceFromListener();
  16871. }
  16872. }
  16873. for (i = 0; i < this.soundTracks.length; i++) {
  16874. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  16875. sound = this.soundTracks[i].soundCollection[j];
  16876. if (sound.useCustomAttenuation) {
  16877. sound.updateDistanceFromListener();
  16878. }
  16879. }
  16880. }
  16881. }
  16882. };
  16883. Object.defineProperty(Scene.prototype, "audioEnabled", {
  16884. // Audio
  16885. get: function () {
  16886. return this._audioEnabled;
  16887. },
  16888. set: function (value) {
  16889. this._audioEnabled = value;
  16890. if (BABYLON.AudioEngine) {
  16891. if (this._audioEnabled) {
  16892. this._enableAudio();
  16893. }
  16894. else {
  16895. this._disableAudio();
  16896. }
  16897. }
  16898. },
  16899. enumerable: true,
  16900. configurable: true
  16901. });
  16902. Scene.prototype._disableAudio = function () {
  16903. var i;
  16904. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  16905. this.mainSoundTrack.soundCollection[i].pause();
  16906. }
  16907. for (i = 0; i < this.soundTracks.length; i++) {
  16908. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  16909. this.soundTracks[i].soundCollection[j].pause();
  16910. }
  16911. }
  16912. };
  16913. Scene.prototype._enableAudio = function () {
  16914. var i;
  16915. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  16916. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  16917. this.mainSoundTrack.soundCollection[i].play();
  16918. }
  16919. }
  16920. for (i = 0; i < this.soundTracks.length; i++) {
  16921. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  16922. if (this.soundTracks[i].soundCollection[j].isPaused) {
  16923. this.soundTracks[i].soundCollection[j].play();
  16924. }
  16925. }
  16926. }
  16927. };
  16928. Object.defineProperty(Scene.prototype, "headphone", {
  16929. get: function () {
  16930. return this._headphone;
  16931. },
  16932. set: function (value) {
  16933. this._headphone = value;
  16934. if (BABYLON.AudioEngine) {
  16935. if (this._headphone) {
  16936. this._switchAudioModeForHeadphones();
  16937. }
  16938. else {
  16939. this._switchAudioModeForNormalSpeakers();
  16940. }
  16941. }
  16942. },
  16943. enumerable: true,
  16944. configurable: true
  16945. });
  16946. Scene.prototype._switchAudioModeForHeadphones = function () {
  16947. this.mainSoundTrack.switchPanningModelToHRTF();
  16948. for (var i = 0; i < this.soundTracks.length; i++) {
  16949. this.soundTracks[i].switchPanningModelToHRTF();
  16950. }
  16951. };
  16952. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  16953. this.mainSoundTrack.switchPanningModelToEqualPower();
  16954. for (var i = 0; i < this.soundTracks.length; i++) {
  16955. this.soundTracks[i].switchPanningModelToEqualPower();
  16956. }
  16957. };
  16958. Scene.prototype.enableDepthRenderer = function () {
  16959. if (this._depthRenderer) {
  16960. return this._depthRenderer;
  16961. }
  16962. this._depthRenderer = new BABYLON.DepthRenderer(this);
  16963. return this._depthRenderer;
  16964. };
  16965. Scene.prototype.disableDepthRenderer = function () {
  16966. if (!this._depthRenderer) {
  16967. return;
  16968. }
  16969. this._depthRenderer.dispose();
  16970. this._depthRenderer = null;
  16971. };
  16972. Scene.prototype.freezeMaterials = function () {
  16973. for (var i = 0; i < this.materials.length; i++) {
  16974. this.materials[i].freeze();
  16975. }
  16976. };
  16977. Scene.prototype.unfreezeMaterials = function () {
  16978. for (var i = 0; i < this.materials.length; i++) {
  16979. this.materials[i].unfreeze();
  16980. }
  16981. };
  16982. Scene.prototype.dispose = function () {
  16983. this.beforeRender = null;
  16984. this.afterRender = null;
  16985. this.skeletons = [];
  16986. this.morphTargetManagers = [];
  16987. if (this._depthRenderer) {
  16988. this._depthRenderer.dispose();
  16989. }
  16990. // Smart arrays
  16991. if (this.activeCamera) {
  16992. this.activeCamera._activeMeshes.dispose();
  16993. this.activeCamera = null;
  16994. }
  16995. this._activeMeshes.dispose();
  16996. this._renderingManager.dispose();
  16997. this._processedMaterials.dispose();
  16998. this._activeParticleSystems.dispose();
  16999. this._activeSkeletons.dispose();
  17000. this._softwareSkinnedMeshes.dispose();
  17001. if (this._boundingBoxRenderer) {
  17002. this._boundingBoxRenderer.dispose();
  17003. }
  17004. this._edgesRenderers.dispose();
  17005. this._meshesForIntersections.dispose();
  17006. this._toBeDisposed.dispose();
  17007. // Debug layer
  17008. if (this._debugLayer) {
  17009. this._debugLayer.hide();
  17010. }
  17011. // Events
  17012. this.onDisposeObservable.notifyObservers(this);
  17013. this.onDisposeObservable.clear();
  17014. this.onBeforeRenderObservable.clear();
  17015. this.onAfterRenderObservable.clear();
  17016. this.detachControl();
  17017. // Release sounds & sounds tracks
  17018. if (BABYLON.AudioEngine) {
  17019. this.disposeSounds();
  17020. }
  17021. // Detach cameras
  17022. var canvas = this._engine.getRenderingCanvas();
  17023. var index;
  17024. for (index = 0; index < this.cameras.length; index++) {
  17025. this.cameras[index].detachControl(canvas);
  17026. }
  17027. // Release lights
  17028. while (this.lights.length) {
  17029. this.lights[0].dispose();
  17030. }
  17031. // Release meshes
  17032. while (this.meshes.length) {
  17033. this.meshes[0].dispose(true);
  17034. }
  17035. // Release cameras
  17036. while (this.cameras.length) {
  17037. this.cameras[0].dispose();
  17038. }
  17039. // Release materials
  17040. while (this.materials.length) {
  17041. this.materials[0].dispose();
  17042. }
  17043. // Release particles
  17044. while (this.particleSystems.length) {
  17045. this.particleSystems[0].dispose();
  17046. }
  17047. // Release sprites
  17048. while (this.spriteManagers.length) {
  17049. this.spriteManagers[0].dispose();
  17050. }
  17051. // Release layers
  17052. while (this.layers.length) {
  17053. this.layers[0].dispose();
  17054. }
  17055. while (this.highlightLayers.length) {
  17056. this.highlightLayers[0].dispose();
  17057. }
  17058. // Release textures
  17059. while (this.textures.length) {
  17060. this.textures[0].dispose();
  17061. }
  17062. // Release UBO
  17063. this._sceneUbo.dispose();
  17064. // Post-processes
  17065. this.postProcessManager.dispose();
  17066. // Physics
  17067. if (this._physicsEngine) {
  17068. this.disablePhysicsEngine();
  17069. }
  17070. // Remove from engine
  17071. index = this._engine.scenes.indexOf(this);
  17072. if (index > -1) {
  17073. this._engine.scenes.splice(index, 1);
  17074. }
  17075. this._engine.wipeCaches();
  17076. this._engine = null;
  17077. };
  17078. Object.defineProperty(Scene.prototype, "isDisposed", {
  17079. get: function () {
  17080. return !this._engine;
  17081. },
  17082. enumerable: true,
  17083. configurable: true
  17084. });
  17085. // Release sounds & sounds tracks
  17086. Scene.prototype.disposeSounds = function () {
  17087. this.mainSoundTrack.dispose();
  17088. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  17089. this.soundTracks[scIndex].dispose();
  17090. }
  17091. };
  17092. // Octrees
  17093. Scene.prototype.getWorldExtends = function () {
  17094. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  17095. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  17096. for (var index = 0; index < this.meshes.length; index++) {
  17097. var mesh = this.meshes[index];
  17098. mesh.computeWorldMatrix(true);
  17099. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  17100. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  17101. BABYLON.Tools.CheckExtends(minBox, min, max);
  17102. BABYLON.Tools.CheckExtends(maxBox, min, max);
  17103. }
  17104. return {
  17105. min: min,
  17106. max: max
  17107. };
  17108. };
  17109. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  17110. if (maxCapacity === void 0) { maxCapacity = 64; }
  17111. if (maxDepth === void 0) { maxDepth = 2; }
  17112. if (!this._selectionOctree) {
  17113. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  17114. }
  17115. var worldExtends = this.getWorldExtends();
  17116. // Update octree
  17117. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  17118. return this._selectionOctree;
  17119. };
  17120. // Picking
  17121. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  17122. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  17123. var engine = this._engine;
  17124. if (!camera) {
  17125. if (!this.activeCamera)
  17126. throw new Error("Active camera not set");
  17127. camera = this.activeCamera;
  17128. }
  17129. var cameraViewport = camera.viewport;
  17130. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  17131. // Moving coordinates to local viewport world
  17132. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  17133. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  17134. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  17135. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  17136. };
  17137. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  17138. if (!BABYLON.PickingInfo) {
  17139. return null;
  17140. }
  17141. var engine = this._engine;
  17142. if (!camera) {
  17143. if (!this.activeCamera)
  17144. throw new Error("Active camera not set");
  17145. camera = this.activeCamera;
  17146. }
  17147. var cameraViewport = camera.viewport;
  17148. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  17149. var identity = BABYLON.Matrix.Identity();
  17150. // Moving coordinates to local viewport world
  17151. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  17152. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  17153. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  17154. };
  17155. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  17156. if (!BABYLON.PickingInfo) {
  17157. return null;
  17158. }
  17159. var pickingInfo = null;
  17160. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  17161. var mesh = this.meshes[meshIndex];
  17162. if (predicate) {
  17163. if (!predicate(mesh)) {
  17164. continue;
  17165. }
  17166. }
  17167. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  17168. continue;
  17169. }
  17170. var world = mesh.getWorldMatrix();
  17171. var ray = rayFunction(world);
  17172. var result = mesh.intersects(ray, fastCheck);
  17173. if (!result || !result.hit)
  17174. continue;
  17175. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  17176. continue;
  17177. pickingInfo = result;
  17178. if (fastCheck) {
  17179. break;
  17180. }
  17181. }
  17182. return pickingInfo || new BABYLON.PickingInfo();
  17183. };
  17184. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  17185. if (!BABYLON.PickingInfo) {
  17186. return null;
  17187. }
  17188. var pickingInfos = new Array();
  17189. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  17190. var mesh = this.meshes[meshIndex];
  17191. if (predicate) {
  17192. if (!predicate(mesh)) {
  17193. continue;
  17194. }
  17195. }
  17196. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  17197. continue;
  17198. }
  17199. var world = mesh.getWorldMatrix();
  17200. var ray = rayFunction(world);
  17201. var result = mesh.intersects(ray, false);
  17202. if (!result || !result.hit)
  17203. continue;
  17204. pickingInfos.push(result);
  17205. }
  17206. return pickingInfos;
  17207. };
  17208. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  17209. if (!BABYLON.PickingInfo) {
  17210. return null;
  17211. }
  17212. var pickingInfo = null;
  17213. camera = camera || this.activeCamera;
  17214. if (this.spriteManagers.length > 0) {
  17215. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  17216. var spriteManager = this.spriteManagers[spriteIndex];
  17217. if (!spriteManager.isPickable) {
  17218. continue;
  17219. }
  17220. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  17221. if (!result || !result.hit)
  17222. continue;
  17223. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  17224. continue;
  17225. pickingInfo = result;
  17226. if (fastCheck) {
  17227. break;
  17228. }
  17229. }
  17230. }
  17231. return pickingInfo || new BABYLON.PickingInfo();
  17232. };
  17233. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  17234. /// <param name="x">X position on screen</param>
  17235. /// <param name="y">Y position on screen</param>
  17236. /// <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>
  17237. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  17238. /// <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>
  17239. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  17240. var _this = this;
  17241. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  17242. };
  17243. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  17244. /// <param name="x">X position on screen</param>
  17245. /// <param name="y">Y position on screen</param>
  17246. /// <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>
  17247. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  17248. /// <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>
  17249. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  17250. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  17251. };
  17252. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  17253. var _this = this;
  17254. return this._internalPick(function (world) {
  17255. if (!_this._pickWithRayInverseMatrix) {
  17256. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  17257. }
  17258. world.invertToRef(_this._pickWithRayInverseMatrix);
  17259. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  17260. }, predicate, fastCheck);
  17261. };
  17262. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  17263. /// <param name="x">X position on screen</param>
  17264. /// <param name="y">Y position on screen</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. /// <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>
  17267. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  17268. var _this = this;
  17269. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate);
  17270. };
  17271. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  17272. /// <param name="ray">Ray to use</param>
  17273. /// <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>
  17274. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  17275. var _this = this;
  17276. return this._internalMultiPick(function (world) {
  17277. if (!_this._pickWithRayInverseMatrix) {
  17278. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  17279. }
  17280. world.invertToRef(_this._pickWithRayInverseMatrix);
  17281. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  17282. }, predicate);
  17283. };
  17284. Scene.prototype.setPointerOverMesh = function (mesh) {
  17285. if (this._pointerOverMesh === mesh) {
  17286. return;
  17287. }
  17288. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  17289. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  17290. }
  17291. this._pointerOverMesh = mesh;
  17292. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  17293. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  17294. }
  17295. };
  17296. Scene.prototype.getPointerOverMesh = function () {
  17297. return this._pointerOverMesh;
  17298. };
  17299. Scene.prototype.setPointerOverSprite = function (sprite) {
  17300. if (this._pointerOverSprite === sprite) {
  17301. return;
  17302. }
  17303. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  17304. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  17305. }
  17306. this._pointerOverSprite = sprite;
  17307. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  17308. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  17309. }
  17310. };
  17311. Scene.prototype.getPointerOverSprite = function () {
  17312. return this._pointerOverSprite;
  17313. };
  17314. // Physics
  17315. Scene.prototype.getPhysicsEngine = function () {
  17316. return this._physicsEngine;
  17317. };
  17318. /**
  17319. * Enables physics to the current scene
  17320. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  17321. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  17322. * @return {boolean} was the physics engine initialized
  17323. */
  17324. Scene.prototype.enablePhysics = function (gravity, plugin) {
  17325. if (this._physicsEngine) {
  17326. return true;
  17327. }
  17328. try {
  17329. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  17330. return true;
  17331. }
  17332. catch (e) {
  17333. BABYLON.Tools.Error(e.message);
  17334. return false;
  17335. }
  17336. };
  17337. Scene.prototype.disablePhysicsEngine = function () {
  17338. if (!this._physicsEngine) {
  17339. return;
  17340. }
  17341. this._physicsEngine.dispose();
  17342. this._physicsEngine = undefined;
  17343. };
  17344. Scene.prototype.isPhysicsEnabled = function () {
  17345. return this._physicsEngine !== undefined;
  17346. };
  17347. Scene.prototype.deleteCompoundImpostor = function (compound) {
  17348. var mesh = compound.parts[0].mesh;
  17349. mesh.physicsImpostor.dispose();
  17350. mesh.physicsImpostor = null;
  17351. };
  17352. // Misc.
  17353. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera) {
  17354. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  17355. // Light
  17356. if (this.lights.length === 0) {
  17357. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  17358. }
  17359. // Camera
  17360. if (!this.activeCamera) {
  17361. // Compute position
  17362. var worldExtends = this.getWorldExtends();
  17363. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  17364. var camera;
  17365. if (createArcRotateCamera) {
  17366. camera = new BABYLON.ArcRotateCamera("default camera", 0, 0, 10, BABYLON.Vector3.Zero(), this);
  17367. camera.setPosition(new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z)));
  17368. camera.lowerRadiusLimit = 0.5;
  17369. camera.setTarget(worldCenter);
  17370. }
  17371. else {
  17372. camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  17373. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  17374. camera.setTarget(worldCenter);
  17375. }
  17376. camera.minZ = 0.1;
  17377. var maxDist = worldExtends.max.subtract(worldExtends.min).length();
  17378. camera.wheelPrecision = 100.0 / maxDist;
  17379. this.activeCamera = camera;
  17380. }
  17381. };
  17382. // Tags
  17383. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  17384. if (tagsQuery === undefined) {
  17385. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  17386. return list;
  17387. }
  17388. var listByTags = [];
  17389. forEach = forEach || (function (item) { return; });
  17390. for (var i in list) {
  17391. var item = list[i];
  17392. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  17393. listByTags.push(item);
  17394. forEach(item);
  17395. }
  17396. }
  17397. return listByTags;
  17398. };
  17399. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  17400. return this._getByTags(this.meshes, tagsQuery, forEach);
  17401. };
  17402. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  17403. return this._getByTags(this.cameras, tagsQuery, forEach);
  17404. };
  17405. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  17406. return this._getByTags(this.lights, tagsQuery, forEach);
  17407. };
  17408. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  17409. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  17410. };
  17411. /**
  17412. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  17413. * This allowed control for front to back rendering or reversly depending of the special needs.
  17414. *
  17415. * @param renderingGroupId The rendering group id corresponding to its index
  17416. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  17417. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  17418. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  17419. */
  17420. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  17421. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  17422. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  17423. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  17424. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  17425. };
  17426. /**
  17427. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  17428. *
  17429. * @param renderingGroupId The rendering group id corresponding to its index
  17430. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  17431. * @param depth Automatically clears depth between groups if true and autoClear is true.
  17432. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  17433. */
  17434. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  17435. if (depth === void 0) { depth = true; }
  17436. if (stencil === void 0) { stencil = true; }
  17437. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  17438. };
  17439. /**
  17440. * Will flag all materials as dirty to trigger new shader compilation
  17441. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  17442. */
  17443. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  17444. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  17445. var material = _a[_i];
  17446. if (predicate && !predicate(material)) {
  17447. continue;
  17448. }
  17449. material.markAsDirty(flag);
  17450. }
  17451. };
  17452. return Scene;
  17453. }());
  17454. // Statics
  17455. Scene._FOGMODE_NONE = 0;
  17456. Scene._FOGMODE_EXP = 1;
  17457. Scene._FOGMODE_EXP2 = 2;
  17458. Scene._FOGMODE_LINEAR = 3;
  17459. Scene.MinDeltaTime = 1.0;
  17460. Scene.MaxDeltaTime = 1000.0;
  17461. Scene.DragMovementThreshold = 10; // in pixels
  17462. Scene.LongPressDelay = 500; // in milliseconds
  17463. Scene.DoubleClickDelay = 300; // in milliseconds
  17464. Scene.ExclusiveDoubleClickMode = false; // If you need to check double click without raising a single click at first click, enable this flag
  17465. BABYLON.Scene = Scene;
  17466. })(BABYLON || (BABYLON = {}));
  17467. //# sourceMappingURL=babylon.scene.js.map
  17468. var BABYLON;
  17469. (function (BABYLON) {
  17470. var Buffer = (function () {
  17471. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  17472. if (engine instanceof BABYLON.Mesh) {
  17473. this._engine = engine.getScene().getEngine();
  17474. }
  17475. else {
  17476. this._engine = engine;
  17477. }
  17478. this._updatable = updatable;
  17479. this._data = data;
  17480. this._strideSize = stride;
  17481. if (!postponeInternalCreation) {
  17482. this.create();
  17483. }
  17484. this._instanced = instanced;
  17485. }
  17486. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  17487. // a lot of these parameters are ignored as they are overriden by the buffer
  17488. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  17489. };
  17490. // Properties
  17491. Buffer.prototype.isUpdatable = function () {
  17492. return this._updatable;
  17493. };
  17494. Buffer.prototype.getData = function () {
  17495. return this._data;
  17496. };
  17497. Buffer.prototype.getBuffer = function () {
  17498. return this._buffer;
  17499. };
  17500. Buffer.prototype.getStrideSize = function () {
  17501. return this._strideSize;
  17502. };
  17503. Buffer.prototype.getIsInstanced = function () {
  17504. return this._instanced;
  17505. };
  17506. // Methods
  17507. Buffer.prototype.create = function (data) {
  17508. if (!data && this._buffer) {
  17509. return; // nothing to do
  17510. }
  17511. data = data || this._data;
  17512. if (!this._buffer) {
  17513. if (this._updatable) {
  17514. this._buffer = this._engine.createDynamicVertexBuffer(data);
  17515. this._data = data;
  17516. }
  17517. else {
  17518. this._buffer = this._engine.createVertexBuffer(data);
  17519. }
  17520. }
  17521. else if (this._updatable) {
  17522. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  17523. this._data = data;
  17524. }
  17525. };
  17526. Buffer.prototype.update = function (data) {
  17527. this.create(data);
  17528. };
  17529. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  17530. if (!this._buffer) {
  17531. return;
  17532. }
  17533. if (this._updatable) {
  17534. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  17535. this._data = null;
  17536. }
  17537. };
  17538. Buffer.prototype.dispose = function () {
  17539. if (!this._buffer) {
  17540. return;
  17541. }
  17542. if (this._engine._releaseBuffer(this._buffer)) {
  17543. this._buffer = null;
  17544. }
  17545. };
  17546. return Buffer;
  17547. }());
  17548. BABYLON.Buffer = Buffer;
  17549. })(BABYLON || (BABYLON = {}));
  17550. //# sourceMappingURL=babylon.buffer.js.map
  17551. var BABYLON;
  17552. (function (BABYLON) {
  17553. var VertexBuffer = (function () {
  17554. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  17555. if (!stride) {
  17556. // Deduce stride from kind
  17557. switch (kind) {
  17558. case VertexBuffer.PositionKind:
  17559. stride = 3;
  17560. break;
  17561. case VertexBuffer.NormalKind:
  17562. stride = 3;
  17563. break;
  17564. case VertexBuffer.UVKind:
  17565. case VertexBuffer.UV2Kind:
  17566. case VertexBuffer.UV3Kind:
  17567. case VertexBuffer.UV4Kind:
  17568. case VertexBuffer.UV5Kind:
  17569. case VertexBuffer.UV6Kind:
  17570. stride = 2;
  17571. break;
  17572. case VertexBuffer.TangentKind:
  17573. case VertexBuffer.ColorKind:
  17574. stride = 4;
  17575. break;
  17576. case VertexBuffer.MatricesIndicesKind:
  17577. case VertexBuffer.MatricesIndicesExtraKind:
  17578. stride = 4;
  17579. break;
  17580. case VertexBuffer.MatricesWeightsKind:
  17581. case VertexBuffer.MatricesWeightsExtraKind:
  17582. stride = 4;
  17583. break;
  17584. }
  17585. }
  17586. if (data instanceof BABYLON.Buffer) {
  17587. if (!stride) {
  17588. stride = data.getStrideSize();
  17589. }
  17590. this._buffer = data;
  17591. this._ownsBuffer = false;
  17592. }
  17593. else {
  17594. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  17595. this._ownsBuffer = true;
  17596. }
  17597. this._stride = stride;
  17598. this._offset = offset ? offset : 0;
  17599. this._size = size ? size : stride;
  17600. this._kind = kind;
  17601. }
  17602. /**
  17603. * Returns the kind of the VertexBuffer (string).
  17604. */
  17605. VertexBuffer.prototype.getKind = function () {
  17606. return this._kind;
  17607. };
  17608. // Properties
  17609. /**
  17610. * Boolean : is the VertexBuffer updatable ?
  17611. */
  17612. VertexBuffer.prototype.isUpdatable = function () {
  17613. return this._buffer.isUpdatable();
  17614. };
  17615. /**
  17616. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  17617. */
  17618. VertexBuffer.prototype.getData = function () {
  17619. return this._buffer.getData();
  17620. };
  17621. /**
  17622. * Returns the WebGLBuffer associated to the VertexBuffer.
  17623. */
  17624. VertexBuffer.prototype.getBuffer = function () {
  17625. return this._buffer.getBuffer();
  17626. };
  17627. /**
  17628. * Returns the stride of the VertexBuffer (integer).
  17629. */
  17630. VertexBuffer.prototype.getStrideSize = function () {
  17631. return this._stride;
  17632. };
  17633. /**
  17634. * Returns the offset (integer).
  17635. */
  17636. VertexBuffer.prototype.getOffset = function () {
  17637. return this._offset;
  17638. };
  17639. /**
  17640. * Returns the VertexBuffer total size (integer).
  17641. */
  17642. VertexBuffer.prototype.getSize = function () {
  17643. return this._size;
  17644. };
  17645. /**
  17646. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  17647. */
  17648. VertexBuffer.prototype.getIsInstanced = function () {
  17649. return this._buffer.getIsInstanced();
  17650. };
  17651. // Methods
  17652. /**
  17653. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  17654. * Returns the created WebGLBuffer.
  17655. */
  17656. VertexBuffer.prototype.create = function (data) {
  17657. return this._buffer.create(data);
  17658. };
  17659. /**
  17660. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  17661. * Returns the updated WebGLBuffer.
  17662. */
  17663. VertexBuffer.prototype.update = function (data) {
  17664. return this._buffer.update(data);
  17665. };
  17666. /**
  17667. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  17668. * Returns the directly updated WebGLBuffer.
  17669. */
  17670. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  17671. return this._buffer.updateDirectly(data, offset);
  17672. };
  17673. /**
  17674. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  17675. */
  17676. VertexBuffer.prototype.dispose = function () {
  17677. if (this._ownsBuffer) {
  17678. this._buffer.dispose();
  17679. }
  17680. };
  17681. Object.defineProperty(VertexBuffer, "PositionKind", {
  17682. get: function () {
  17683. return VertexBuffer._PositionKind;
  17684. },
  17685. enumerable: true,
  17686. configurable: true
  17687. });
  17688. Object.defineProperty(VertexBuffer, "NormalKind", {
  17689. get: function () {
  17690. return VertexBuffer._NormalKind;
  17691. },
  17692. enumerable: true,
  17693. configurable: true
  17694. });
  17695. Object.defineProperty(VertexBuffer, "TangentKind", {
  17696. get: function () {
  17697. return VertexBuffer._TangentKind;
  17698. },
  17699. enumerable: true,
  17700. configurable: true
  17701. });
  17702. Object.defineProperty(VertexBuffer, "UVKind", {
  17703. get: function () {
  17704. return VertexBuffer._UVKind;
  17705. },
  17706. enumerable: true,
  17707. configurable: true
  17708. });
  17709. Object.defineProperty(VertexBuffer, "UV2Kind", {
  17710. get: function () {
  17711. return VertexBuffer._UV2Kind;
  17712. },
  17713. enumerable: true,
  17714. configurable: true
  17715. });
  17716. Object.defineProperty(VertexBuffer, "UV3Kind", {
  17717. get: function () {
  17718. return VertexBuffer._UV3Kind;
  17719. },
  17720. enumerable: true,
  17721. configurable: true
  17722. });
  17723. Object.defineProperty(VertexBuffer, "UV4Kind", {
  17724. get: function () {
  17725. return VertexBuffer._UV4Kind;
  17726. },
  17727. enumerable: true,
  17728. configurable: true
  17729. });
  17730. Object.defineProperty(VertexBuffer, "UV5Kind", {
  17731. get: function () {
  17732. return VertexBuffer._UV5Kind;
  17733. },
  17734. enumerable: true,
  17735. configurable: true
  17736. });
  17737. Object.defineProperty(VertexBuffer, "UV6Kind", {
  17738. get: function () {
  17739. return VertexBuffer._UV6Kind;
  17740. },
  17741. enumerable: true,
  17742. configurable: true
  17743. });
  17744. Object.defineProperty(VertexBuffer, "ColorKind", {
  17745. get: function () {
  17746. return VertexBuffer._ColorKind;
  17747. },
  17748. enumerable: true,
  17749. configurable: true
  17750. });
  17751. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  17752. get: function () {
  17753. return VertexBuffer._MatricesIndicesKind;
  17754. },
  17755. enumerable: true,
  17756. configurable: true
  17757. });
  17758. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  17759. get: function () {
  17760. return VertexBuffer._MatricesWeightsKind;
  17761. },
  17762. enumerable: true,
  17763. configurable: true
  17764. });
  17765. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  17766. get: function () {
  17767. return VertexBuffer._MatricesIndicesExtraKind;
  17768. },
  17769. enumerable: true,
  17770. configurable: true
  17771. });
  17772. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  17773. get: function () {
  17774. return VertexBuffer._MatricesWeightsExtraKind;
  17775. },
  17776. enumerable: true,
  17777. configurable: true
  17778. });
  17779. return VertexBuffer;
  17780. }());
  17781. // Enums
  17782. VertexBuffer._PositionKind = "position";
  17783. VertexBuffer._NormalKind = "normal";
  17784. VertexBuffer._TangentKind = "tangent";
  17785. VertexBuffer._UVKind = "uv";
  17786. VertexBuffer._UV2Kind = "uv2";
  17787. VertexBuffer._UV3Kind = "uv3";
  17788. VertexBuffer._UV4Kind = "uv4";
  17789. VertexBuffer._UV5Kind = "uv5";
  17790. VertexBuffer._UV6Kind = "uv6";
  17791. VertexBuffer._ColorKind = "color";
  17792. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  17793. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  17794. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  17795. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  17796. BABYLON.VertexBuffer = VertexBuffer;
  17797. })(BABYLON || (BABYLON = {}));
  17798. //# sourceMappingURL=babylon.vertexBuffer.js.map
  17799. var BABYLON;
  17800. (function (BABYLON) {
  17801. var BaseTexture = (function () {
  17802. function BaseTexture(scene) {
  17803. this._hasAlpha = false;
  17804. this.getAlphaFromRGB = false;
  17805. this.level = 1;
  17806. this.coordinatesIndex = 0;
  17807. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  17808. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  17809. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  17810. this.anisotropicFilteringLevel = 4;
  17811. this.isCube = false;
  17812. this.isRenderTarget = false;
  17813. this.animations = new Array();
  17814. /**
  17815. * An event triggered when the texture is disposed.
  17816. * @type {BABYLON.Observable}
  17817. */
  17818. this.onDisposeObservable = new BABYLON.Observable();
  17819. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  17820. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  17821. this._scene.textures.push(this);
  17822. this._uid = null;
  17823. }
  17824. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  17825. get: function () {
  17826. return this._hasAlpha;
  17827. },
  17828. set: function (value) {
  17829. if (this._hasAlpha === value) {
  17830. return;
  17831. }
  17832. this._hasAlpha = value;
  17833. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  17834. },
  17835. enumerable: true,
  17836. configurable: true
  17837. });
  17838. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  17839. get: function () {
  17840. return this._coordinatesMode;
  17841. },
  17842. set: function (value) {
  17843. if (this._coordinatesMode === value) {
  17844. return;
  17845. }
  17846. this._coordinatesMode = value;
  17847. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  17848. },
  17849. enumerable: true,
  17850. configurable: true
  17851. });
  17852. Object.defineProperty(BaseTexture.prototype, "uid", {
  17853. get: function () {
  17854. if (!this._uid) {
  17855. this._uid = BABYLON.Tools.RandomId();
  17856. }
  17857. return this._uid;
  17858. },
  17859. enumerable: true,
  17860. configurable: true
  17861. });
  17862. BaseTexture.prototype.toString = function () {
  17863. return this.name;
  17864. };
  17865. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  17866. set: function (callback) {
  17867. if (this._onDisposeObserver) {
  17868. this.onDisposeObservable.remove(this._onDisposeObserver);
  17869. }
  17870. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17871. },
  17872. enumerable: true,
  17873. configurable: true
  17874. });
  17875. BaseTexture.prototype.getScene = function () {
  17876. return this._scene;
  17877. };
  17878. BaseTexture.prototype.getTextureMatrix = function () {
  17879. return null;
  17880. };
  17881. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  17882. return null;
  17883. };
  17884. BaseTexture.prototype.getInternalTexture = function () {
  17885. return this._texture;
  17886. };
  17887. BaseTexture.prototype.isReady = function () {
  17888. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  17889. return true;
  17890. }
  17891. if (this._texture) {
  17892. return this._texture.isReady;
  17893. }
  17894. return false;
  17895. };
  17896. BaseTexture.prototype.getSize = function () {
  17897. if (this._texture._width) {
  17898. return new BABYLON.Size(this._texture._width, this._texture._height);
  17899. }
  17900. if (this._texture._size) {
  17901. return new BABYLON.Size(this._texture._size, this._texture._size);
  17902. }
  17903. return BABYLON.Size.Zero();
  17904. };
  17905. BaseTexture.prototype.getBaseSize = function () {
  17906. if (!this.isReady() || !this._texture)
  17907. return BABYLON.Size.Zero();
  17908. if (this._texture._size) {
  17909. return new BABYLON.Size(this._texture._size, this._texture._size);
  17910. }
  17911. return new BABYLON.Size(this._texture._baseWidth, this._texture._baseHeight);
  17912. };
  17913. BaseTexture.prototype.scale = function (ratio) {
  17914. };
  17915. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  17916. get: function () {
  17917. return false;
  17918. },
  17919. enumerable: true,
  17920. configurable: true
  17921. });
  17922. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  17923. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  17924. for (var index = 0; index < texturesCache.length; index++) {
  17925. var texturesCacheEntry = texturesCache[index];
  17926. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  17927. texturesCache.splice(index, 1);
  17928. return;
  17929. }
  17930. }
  17931. };
  17932. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  17933. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  17934. for (var index = 0; index < texturesCache.length; index++) {
  17935. var texturesCacheEntry = texturesCache[index];
  17936. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  17937. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  17938. texturesCacheEntry.references++;
  17939. return texturesCacheEntry;
  17940. }
  17941. }
  17942. }
  17943. return null;
  17944. };
  17945. BaseTexture.prototype.delayLoad = function () {
  17946. };
  17947. BaseTexture.prototype.clone = function () {
  17948. return null;
  17949. };
  17950. BaseTexture.prototype.releaseInternalTexture = function () {
  17951. if (this._texture) {
  17952. this._scene.getEngine().releaseInternalTexture(this._texture);
  17953. delete this._texture;
  17954. }
  17955. };
  17956. BaseTexture.prototype.dispose = function () {
  17957. // Animations
  17958. this.getScene().stopAnimation(this);
  17959. // Remove from scene
  17960. this._scene._removePendingData(this);
  17961. var index = this._scene.textures.indexOf(this);
  17962. if (index >= 0) {
  17963. this._scene.textures.splice(index, 1);
  17964. }
  17965. if (this._texture === undefined) {
  17966. return;
  17967. }
  17968. // Release
  17969. this.releaseInternalTexture();
  17970. // Callback
  17971. this.onDisposeObservable.notifyObservers(this);
  17972. this.onDisposeObservable.clear();
  17973. };
  17974. BaseTexture.prototype.serialize = function () {
  17975. if (!this.name) {
  17976. return null;
  17977. }
  17978. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  17979. // Animations
  17980. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  17981. return serializationObject;
  17982. };
  17983. return BaseTexture;
  17984. }());
  17985. __decorate([
  17986. BABYLON.serialize()
  17987. ], BaseTexture.prototype, "name", void 0);
  17988. __decorate([
  17989. BABYLON.serialize("hasAlpha")
  17990. ], BaseTexture.prototype, "_hasAlpha", void 0);
  17991. __decorate([
  17992. BABYLON.serialize()
  17993. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  17994. __decorate([
  17995. BABYLON.serialize()
  17996. ], BaseTexture.prototype, "level", void 0);
  17997. __decorate([
  17998. BABYLON.serialize()
  17999. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  18000. __decorate([
  18001. BABYLON.serialize("coordinatesMode")
  18002. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  18003. __decorate([
  18004. BABYLON.serialize()
  18005. ], BaseTexture.prototype, "wrapU", void 0);
  18006. __decorate([
  18007. BABYLON.serialize()
  18008. ], BaseTexture.prototype, "wrapV", void 0);
  18009. __decorate([
  18010. BABYLON.serialize()
  18011. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  18012. __decorate([
  18013. BABYLON.serialize()
  18014. ], BaseTexture.prototype, "isCube", void 0);
  18015. __decorate([
  18016. BABYLON.serialize()
  18017. ], BaseTexture.prototype, "isRenderTarget", void 0);
  18018. BABYLON.BaseTexture = BaseTexture;
  18019. })(BABYLON || (BABYLON = {}));
  18020. //# sourceMappingURL=babylon.baseTexture.js.map
  18021. var BABYLON;
  18022. (function (BABYLON) {
  18023. var Texture = (function (_super) {
  18024. __extends(Texture, _super);
  18025. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  18026. if (noMipmap === void 0) { noMipmap = false; }
  18027. if (invertY === void 0) { invertY = true; }
  18028. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  18029. if (onLoad === void 0) { onLoad = null; }
  18030. if (onError === void 0) { onError = null; }
  18031. if (buffer === void 0) { buffer = null; }
  18032. if (deleteBuffer === void 0) { deleteBuffer = false; }
  18033. var _this = _super.call(this, scene) || this;
  18034. _this.uOffset = 0;
  18035. _this.vOffset = 0;
  18036. _this.uScale = 1.0;
  18037. _this.vScale = 1.0;
  18038. _this.uAng = 0;
  18039. _this.vAng = 0;
  18040. _this.wAng = 0;
  18041. _this.name = url;
  18042. _this.url = url;
  18043. _this._noMipmap = noMipmap;
  18044. _this._invertY = invertY;
  18045. _this._samplingMode = samplingMode;
  18046. _this._buffer = buffer;
  18047. _this._deleteBuffer = deleteBuffer;
  18048. _this._format = format;
  18049. if (!url) {
  18050. return _this;
  18051. }
  18052. _this._texture = _this._getFromCache(url, noMipmap, samplingMode);
  18053. var load = function () {
  18054. if (_this._onLoadObservarble && _this._onLoadObservarble.hasObservers()) {
  18055. _this.onLoadObservable.notifyObservers(true);
  18056. }
  18057. if (onLoad) {
  18058. onLoad();
  18059. }
  18060. };
  18061. if (!_this._texture) {
  18062. if (!scene.useDelayedTextureLoading) {
  18063. _this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, null, _this._format);
  18064. if (deleteBuffer) {
  18065. delete _this._buffer;
  18066. }
  18067. }
  18068. else {
  18069. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  18070. _this._delayedOnLoad = load;
  18071. _this._delayedOnError = onError;
  18072. }
  18073. }
  18074. else {
  18075. if (_this._texture.isReady) {
  18076. BABYLON.Tools.SetImmediate(function () { return load(); });
  18077. }
  18078. else {
  18079. _this._texture.onLoadedCallbacks.push(load);
  18080. }
  18081. }
  18082. return _this;
  18083. }
  18084. Object.defineProperty(Texture.prototype, "noMipmap", {
  18085. get: function () {
  18086. return this._noMipmap;
  18087. },
  18088. enumerable: true,
  18089. configurable: true
  18090. });
  18091. Texture.prototype.delayLoad = function () {
  18092. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  18093. return;
  18094. }
  18095. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  18096. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  18097. if (!this._texture) {
  18098. 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);
  18099. if (this._deleteBuffer) {
  18100. delete this._buffer;
  18101. }
  18102. }
  18103. };
  18104. Texture.prototype.updateSamplingMode = function (samplingMode) {
  18105. if (!this._texture) {
  18106. return;
  18107. }
  18108. this._samplingMode = samplingMode;
  18109. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  18110. };
  18111. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  18112. x *= this.uScale;
  18113. y *= this.vScale;
  18114. x -= 0.5 * this.uScale;
  18115. y -= 0.5 * this.vScale;
  18116. z -= 0.5;
  18117. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  18118. t.x += 0.5 * this.uScale + this.uOffset;
  18119. t.y += 0.5 * this.vScale + this.vOffset;
  18120. t.z += 0.5;
  18121. };
  18122. Texture.prototype.getTextureMatrix = function () {
  18123. if (this.uOffset === this._cachedUOffset &&
  18124. this.vOffset === this._cachedVOffset &&
  18125. this.uScale === this._cachedUScale &&
  18126. this.vScale === this._cachedVScale &&
  18127. this.uAng === this._cachedUAng &&
  18128. this.vAng === this._cachedVAng &&
  18129. this.wAng === this._cachedWAng) {
  18130. return this._cachedTextureMatrix;
  18131. }
  18132. this._cachedUOffset = this.uOffset;
  18133. this._cachedVOffset = this.vOffset;
  18134. this._cachedUScale = this.uScale;
  18135. this._cachedVScale = this.vScale;
  18136. this._cachedUAng = this.uAng;
  18137. this._cachedVAng = this.vAng;
  18138. this._cachedWAng = this.wAng;
  18139. if (!this._cachedTextureMatrix) {
  18140. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  18141. this._rowGenerationMatrix = new BABYLON.Matrix();
  18142. this._t0 = BABYLON.Vector3.Zero();
  18143. this._t1 = BABYLON.Vector3.Zero();
  18144. this._t2 = BABYLON.Vector3.Zero();
  18145. }
  18146. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  18147. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  18148. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  18149. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  18150. this._t1.subtractInPlace(this._t0);
  18151. this._t2.subtractInPlace(this._t0);
  18152. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  18153. this._cachedTextureMatrix.m[0] = this._t1.x;
  18154. this._cachedTextureMatrix.m[1] = this._t1.y;
  18155. this._cachedTextureMatrix.m[2] = this._t1.z;
  18156. this._cachedTextureMatrix.m[4] = this._t2.x;
  18157. this._cachedTextureMatrix.m[5] = this._t2.y;
  18158. this._cachedTextureMatrix.m[6] = this._t2.z;
  18159. this._cachedTextureMatrix.m[8] = this._t0.x;
  18160. this._cachedTextureMatrix.m[9] = this._t0.y;
  18161. this._cachedTextureMatrix.m[10] = this._t0.z;
  18162. return this._cachedTextureMatrix;
  18163. };
  18164. Texture.prototype.getReflectionTextureMatrix = function () {
  18165. if (this.uOffset === this._cachedUOffset &&
  18166. this.vOffset === this._cachedVOffset &&
  18167. this.uScale === this._cachedUScale &&
  18168. this.vScale === this._cachedVScale &&
  18169. this.coordinatesMode === this._cachedCoordinatesMode) {
  18170. return this._cachedTextureMatrix;
  18171. }
  18172. if (!this._cachedTextureMatrix) {
  18173. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  18174. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  18175. }
  18176. this._cachedCoordinatesMode = this.coordinatesMode;
  18177. switch (this.coordinatesMode) {
  18178. case Texture.PLANAR_MODE:
  18179. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  18180. this._cachedTextureMatrix[0] = this.uScale;
  18181. this._cachedTextureMatrix[5] = this.vScale;
  18182. this._cachedTextureMatrix[12] = this.uOffset;
  18183. this._cachedTextureMatrix[13] = this.vOffset;
  18184. break;
  18185. case Texture.PROJECTION_MODE:
  18186. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  18187. this._projectionModeMatrix.m[0] = 0.5;
  18188. this._projectionModeMatrix.m[5] = -0.5;
  18189. this._projectionModeMatrix.m[10] = 0.0;
  18190. this._projectionModeMatrix.m[12] = 0.5;
  18191. this._projectionModeMatrix.m[13] = 0.5;
  18192. this._projectionModeMatrix.m[14] = 1.0;
  18193. this._projectionModeMatrix.m[15] = 1.0;
  18194. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  18195. break;
  18196. default:
  18197. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  18198. break;
  18199. }
  18200. return this._cachedTextureMatrix;
  18201. };
  18202. Texture.prototype.clone = function () {
  18203. var _this = this;
  18204. return BABYLON.SerializationHelper.Clone(function () {
  18205. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  18206. }, this);
  18207. };
  18208. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  18209. get: function () {
  18210. if (!this._onLoadObservarble) {
  18211. this._onLoadObservarble = new BABYLON.Observable();
  18212. }
  18213. return this._onLoadObservarble;
  18214. },
  18215. enumerable: true,
  18216. configurable: true
  18217. });
  18218. // Statics
  18219. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  18220. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  18221. if (onLoad === void 0) { onLoad = null; }
  18222. if (onError === void 0) { onError = null; }
  18223. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  18224. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  18225. };
  18226. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  18227. if (parsedTexture.customType) {
  18228. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  18229. // Update Sampling Mode
  18230. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  18231. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  18232. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  18233. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  18234. }
  18235. }
  18236. return parsedCustomTexture;
  18237. }
  18238. if (parsedTexture.isCube) {
  18239. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  18240. }
  18241. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  18242. return null;
  18243. }
  18244. var texture = BABYLON.SerializationHelper.Parse(function () {
  18245. if (parsedTexture.mirrorPlane) {
  18246. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  18247. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  18248. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  18249. return mirrorTexture;
  18250. }
  18251. else if (parsedTexture.isRenderTarget) {
  18252. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  18253. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  18254. return renderTargetTexture;
  18255. }
  18256. else {
  18257. var texture;
  18258. if (parsedTexture.base64String) {
  18259. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  18260. }
  18261. else {
  18262. texture = new Texture(rootUrl + parsedTexture.name, scene);
  18263. }
  18264. return texture;
  18265. }
  18266. }, parsedTexture, scene);
  18267. // Update Sampling Mode
  18268. if (parsedTexture.samplingMode) {
  18269. var sampling = parsedTexture.samplingMode;
  18270. if (texture._samplingMode !== sampling) {
  18271. texture.updateSamplingMode(sampling);
  18272. }
  18273. }
  18274. // Animations
  18275. if (parsedTexture.animations) {
  18276. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  18277. var parsedAnimation = parsedTexture.animations[animationIndex];
  18278. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  18279. }
  18280. }
  18281. return texture;
  18282. };
  18283. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  18284. if (deleteBuffer === void 0) { deleteBuffer = false; }
  18285. if (noMipmap === void 0) { noMipmap = false; }
  18286. if (invertY === void 0) { invertY = true; }
  18287. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  18288. if (onLoad === void 0) { onLoad = null; }
  18289. if (onError === void 0) { onError = null; }
  18290. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  18291. if (name.substr(0, 5) !== "data:") {
  18292. name = "data:" + name;
  18293. }
  18294. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  18295. };
  18296. return Texture;
  18297. }(BABYLON.BaseTexture));
  18298. // Constants
  18299. Texture.NEAREST_SAMPLINGMODE = 1;
  18300. Texture.BILINEAR_SAMPLINGMODE = 2;
  18301. Texture.TRILINEAR_SAMPLINGMODE = 3;
  18302. Texture.EXPLICIT_MODE = 0;
  18303. Texture.SPHERICAL_MODE = 1;
  18304. Texture.PLANAR_MODE = 2;
  18305. Texture.CUBIC_MODE = 3;
  18306. Texture.PROJECTION_MODE = 4;
  18307. Texture.SKYBOX_MODE = 5;
  18308. Texture.INVCUBIC_MODE = 6;
  18309. Texture.EQUIRECTANGULAR_MODE = 7;
  18310. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  18311. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  18312. Texture.CLAMP_ADDRESSMODE = 0;
  18313. Texture.WRAP_ADDRESSMODE = 1;
  18314. Texture.MIRROR_ADDRESSMODE = 2;
  18315. __decorate([
  18316. BABYLON.serialize()
  18317. ], Texture.prototype, "url", void 0);
  18318. __decorate([
  18319. BABYLON.serialize()
  18320. ], Texture.prototype, "uOffset", void 0);
  18321. __decorate([
  18322. BABYLON.serialize()
  18323. ], Texture.prototype, "vOffset", void 0);
  18324. __decorate([
  18325. BABYLON.serialize()
  18326. ], Texture.prototype, "uScale", void 0);
  18327. __decorate([
  18328. BABYLON.serialize()
  18329. ], Texture.prototype, "vScale", void 0);
  18330. __decorate([
  18331. BABYLON.serialize()
  18332. ], Texture.prototype, "uAng", void 0);
  18333. __decorate([
  18334. BABYLON.serialize()
  18335. ], Texture.prototype, "vAng", void 0);
  18336. __decorate([
  18337. BABYLON.serialize()
  18338. ], Texture.prototype, "wAng", void 0);
  18339. BABYLON.Texture = Texture;
  18340. })(BABYLON || (BABYLON = {}));
  18341. //# sourceMappingURL=babylon.texture.js.map
  18342. var BABYLON;
  18343. (function (BABYLON) {
  18344. var _InstancesBatch = (function () {
  18345. function _InstancesBatch() {
  18346. this.mustReturn = false;
  18347. this.visibleInstances = new Array();
  18348. this.renderSelf = new Array();
  18349. }
  18350. return _InstancesBatch;
  18351. }());
  18352. BABYLON._InstancesBatch = _InstancesBatch;
  18353. var Mesh = (function (_super) {
  18354. __extends(Mesh, _super);
  18355. /**
  18356. * @constructor
  18357. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  18358. * @param {Scene} scene The scene to add this mesh to.
  18359. * @param {Node} parent The parent of this mesh, if it has one
  18360. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  18361. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  18362. * When false, achieved by calling a clone(), also passing False.
  18363. * This will make creation of children, recursive.
  18364. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  18365. */
  18366. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  18367. if (parent === void 0) { parent = null; }
  18368. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  18369. var _this = _super.call(this, name, scene) || this;
  18370. // Events
  18371. /**
  18372. * An event triggered before rendering the mesh
  18373. * @type {BABYLON.Observable}
  18374. */
  18375. _this.onBeforeRenderObservable = new BABYLON.Observable();
  18376. /**
  18377. * An event triggered after rendering the mesh
  18378. * @type {BABYLON.Observable}
  18379. */
  18380. _this.onAfterRenderObservable = new BABYLON.Observable();
  18381. /**
  18382. * An event triggered before drawing the mesh
  18383. * @type {BABYLON.Observable}
  18384. */
  18385. _this.onBeforeDrawObservable = new BABYLON.Observable();
  18386. // Members
  18387. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  18388. _this.instances = new Array();
  18389. _this._LODLevels = new Array();
  18390. _this._visibleInstances = {};
  18391. _this._renderIdForInstances = new Array();
  18392. _this._batchCache = new _InstancesBatch();
  18393. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  18394. _this._sideOrientation = Mesh._DEFAULTSIDE;
  18395. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  18396. // Will be used to save a source mesh reference, If any
  18397. _this._source = null;
  18398. if (source) {
  18399. // Source mesh
  18400. _this._source = source;
  18401. // Geometry
  18402. if (source._geometry) {
  18403. source._geometry.applyToMesh(_this);
  18404. }
  18405. // Deep copy
  18406. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId"], ["_poseMatrix"]);
  18407. // Parent
  18408. _this.parent = source.parent;
  18409. // Pivot
  18410. _this.setPivotMatrix(source.getPivotMatrix());
  18411. _this.id = name + "." + source.id;
  18412. // Material
  18413. _this.material = source.material;
  18414. var index;
  18415. if (!doNotCloneChildren) {
  18416. // Children
  18417. for (index = 0; index < scene.meshes.length; index++) {
  18418. var mesh = scene.meshes[index];
  18419. if (mesh.parent === source) {
  18420. // doNotCloneChildren is always going to be False
  18421. var newChild = mesh.clone(name + "." + mesh.name, _this, doNotCloneChildren);
  18422. }
  18423. }
  18424. }
  18425. // Physics clone
  18426. var physicsEngine = _this.getScene().getPhysicsEngine();
  18427. if (clonePhysicsImpostor && physicsEngine) {
  18428. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  18429. if (impostor) {
  18430. _this.physicsImpostor = impostor.clone(_this);
  18431. }
  18432. }
  18433. // Particles
  18434. for (index = 0; index < scene.particleSystems.length; index++) {
  18435. var system = scene.particleSystems[index];
  18436. if (system.emitter === source) {
  18437. system.clone(system.name, _this);
  18438. }
  18439. }
  18440. _this.computeWorldMatrix(true);
  18441. }
  18442. // Parent
  18443. if (parent !== null) {
  18444. _this.parent = parent;
  18445. }
  18446. return _this;
  18447. }
  18448. Object.defineProperty(Mesh, "FRONTSIDE", {
  18449. /**
  18450. * Mesh side orientation : usually the external or front surface
  18451. */
  18452. get: function () {
  18453. return Mesh._FRONTSIDE;
  18454. },
  18455. enumerable: true,
  18456. configurable: true
  18457. });
  18458. Object.defineProperty(Mesh, "BACKSIDE", {
  18459. /**
  18460. * Mesh side orientation : usually the internal or back surface
  18461. */
  18462. get: function () {
  18463. return Mesh._BACKSIDE;
  18464. },
  18465. enumerable: true,
  18466. configurable: true
  18467. });
  18468. Object.defineProperty(Mesh, "DOUBLESIDE", {
  18469. /**
  18470. * Mesh side orientation : both internal and external or front and back surfaces
  18471. */
  18472. get: function () {
  18473. return Mesh._DOUBLESIDE;
  18474. },
  18475. enumerable: true,
  18476. configurable: true
  18477. });
  18478. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  18479. /**
  18480. * Mesh side orientation : by default, `FRONTSIDE`
  18481. */
  18482. get: function () {
  18483. return Mesh._DEFAULTSIDE;
  18484. },
  18485. enumerable: true,
  18486. configurable: true
  18487. });
  18488. Object.defineProperty(Mesh, "NO_CAP", {
  18489. /**
  18490. * Mesh cap setting : no cap
  18491. */
  18492. get: function () {
  18493. return Mesh._NO_CAP;
  18494. },
  18495. enumerable: true,
  18496. configurable: true
  18497. });
  18498. Object.defineProperty(Mesh, "CAP_START", {
  18499. /**
  18500. * Mesh cap setting : one cap at the beginning of the mesh
  18501. */
  18502. get: function () {
  18503. return Mesh._CAP_START;
  18504. },
  18505. enumerable: true,
  18506. configurable: true
  18507. });
  18508. Object.defineProperty(Mesh, "CAP_END", {
  18509. /**
  18510. * Mesh cap setting : one cap at the end of the mesh
  18511. */
  18512. get: function () {
  18513. return Mesh._CAP_END;
  18514. },
  18515. enumerable: true,
  18516. configurable: true
  18517. });
  18518. Object.defineProperty(Mesh, "CAP_ALL", {
  18519. /**
  18520. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  18521. */
  18522. get: function () {
  18523. return Mesh._CAP_ALL;
  18524. },
  18525. enumerable: true,
  18526. configurable: true
  18527. });
  18528. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  18529. set: function (callback) {
  18530. if (this._onBeforeDrawObserver) {
  18531. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  18532. }
  18533. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  18534. },
  18535. enumerable: true,
  18536. configurable: true
  18537. });
  18538. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  18539. get: function () {
  18540. return this._morphTargetManager;
  18541. },
  18542. set: function (value) {
  18543. if (this._morphTargetManager === value) {
  18544. return;
  18545. }
  18546. this._morphTargetManager = value;
  18547. this._syncGeometryWithMorphTargetManager();
  18548. },
  18549. enumerable: true,
  18550. configurable: true
  18551. });
  18552. Object.defineProperty(Mesh.prototype, "source", {
  18553. get: function () {
  18554. return this._source;
  18555. },
  18556. enumerable: true,
  18557. configurable: true
  18558. });
  18559. // Methods
  18560. /**
  18561. * Returns the string "Mesh".
  18562. */
  18563. Mesh.prototype.getClassName = function () {
  18564. return "Mesh";
  18565. };
  18566. /**
  18567. * Returns a string.
  18568. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  18569. */
  18570. Mesh.prototype.toString = function (fullDetails) {
  18571. var ret = _super.prototype.toString.call(this, fullDetails);
  18572. ret += ", n vertices: " + this.getTotalVertices();
  18573. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  18574. if (this.animations) {
  18575. for (var i = 0; i < this.animations.length; i++) {
  18576. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  18577. }
  18578. }
  18579. if (fullDetails) {
  18580. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  18581. }
  18582. return ret;
  18583. };
  18584. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  18585. /**
  18586. * True if the mesh has some Levels Of Details (LOD).
  18587. * Returns a boolean.
  18588. */
  18589. get: function () {
  18590. return this._LODLevels.length > 0;
  18591. },
  18592. enumerable: true,
  18593. configurable: true
  18594. });
  18595. Mesh.prototype._sortLODLevels = function () {
  18596. this._LODLevels.sort(function (a, b) {
  18597. if (a.distance < b.distance) {
  18598. return 1;
  18599. }
  18600. if (a.distance > b.distance) {
  18601. return -1;
  18602. }
  18603. return 0;
  18604. });
  18605. };
  18606. /**
  18607. * Add a mesh as LOD level triggered at the given distance.
  18608. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  18609. * @param {number} distance The distance from the center of the object to show this level
  18610. * @param {Mesh} mesh The mesh to be added as LOD level
  18611. * @return {Mesh} This mesh (for chaining)
  18612. */
  18613. Mesh.prototype.addLODLevel = function (distance, mesh) {
  18614. if (mesh && mesh._masterMesh) {
  18615. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  18616. return this;
  18617. }
  18618. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  18619. this._LODLevels.push(level);
  18620. if (mesh) {
  18621. mesh._masterMesh = this;
  18622. }
  18623. this._sortLODLevels();
  18624. return this;
  18625. };
  18626. /**
  18627. * Returns the LOD level mesh at the passed distance or null if not found.
  18628. * It is related to the method `addLODLevel(distance, mesh)`.
  18629. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  18630. * Returns an object Mesh or `null`.
  18631. */
  18632. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  18633. for (var index = 0; index < this._LODLevels.length; index++) {
  18634. var level = this._LODLevels[index];
  18635. if (level.distance === distance) {
  18636. return level.mesh;
  18637. }
  18638. }
  18639. return null;
  18640. };
  18641. /**
  18642. * Remove a mesh from the LOD array
  18643. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  18644. * @param {Mesh} mesh The mesh to be removed.
  18645. * @return {Mesh} This mesh (for chaining)
  18646. */
  18647. Mesh.prototype.removeLODLevel = function (mesh) {
  18648. for (var index = 0; index < this._LODLevels.length; index++) {
  18649. if (this._LODLevels[index].mesh === mesh) {
  18650. this._LODLevels.splice(index, 1);
  18651. if (mesh) {
  18652. mesh._masterMesh = null;
  18653. }
  18654. }
  18655. }
  18656. this._sortLODLevels();
  18657. return this;
  18658. };
  18659. /**
  18660. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  18661. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  18662. */
  18663. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  18664. if (!this._LODLevels || this._LODLevels.length === 0) {
  18665. return this;
  18666. }
  18667. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  18668. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  18669. if (this.onLODLevelSelection) {
  18670. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  18671. }
  18672. return this;
  18673. }
  18674. for (var index = 0; index < this._LODLevels.length; index++) {
  18675. var level = this._LODLevels[index];
  18676. if (level.distance < distanceToCamera) {
  18677. if (level.mesh) {
  18678. level.mesh._preActivate();
  18679. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  18680. }
  18681. if (this.onLODLevelSelection) {
  18682. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  18683. }
  18684. return level.mesh;
  18685. }
  18686. }
  18687. if (this.onLODLevelSelection) {
  18688. this.onLODLevelSelection(distanceToCamera, this, this);
  18689. }
  18690. return this;
  18691. };
  18692. Object.defineProperty(Mesh.prototype, "geometry", {
  18693. /**
  18694. * Returns the mesh internal Geometry object.
  18695. */
  18696. get: function () {
  18697. return this._geometry;
  18698. },
  18699. enumerable: true,
  18700. configurable: true
  18701. });
  18702. /**
  18703. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  18704. */
  18705. Mesh.prototype.getTotalVertices = function () {
  18706. if (!this._geometry) {
  18707. return 0;
  18708. }
  18709. return this._geometry.getTotalVertices();
  18710. };
  18711. /**
  18712. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  18713. * 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.
  18714. * Returns null if the mesh has no geometry or no vertex buffer.
  18715. * Possible `kind` values :
  18716. * - BABYLON.VertexBuffer.PositionKind
  18717. * - BABYLON.VertexBuffer.UVKind
  18718. * - BABYLON.VertexBuffer.UV2Kind
  18719. * - BABYLON.VertexBuffer.UV3Kind
  18720. * - BABYLON.VertexBuffer.UV4Kind
  18721. * - BABYLON.VertexBuffer.UV5Kind
  18722. * - BABYLON.VertexBuffer.UV6Kind
  18723. * - BABYLON.VertexBuffer.ColorKind
  18724. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18725. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18726. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18727. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18728. */
  18729. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  18730. if (!this._geometry) {
  18731. return null;
  18732. }
  18733. return this._geometry.getVerticesData(kind, copyWhenShared);
  18734. };
  18735. /**
  18736. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  18737. * Returns `undefined` if the mesh has no geometry.
  18738. * Possible `kind` values :
  18739. * - BABYLON.VertexBuffer.PositionKind
  18740. * - BABYLON.VertexBuffer.UVKind
  18741. * - BABYLON.VertexBuffer.UV2Kind
  18742. * - BABYLON.VertexBuffer.UV3Kind
  18743. * - BABYLON.VertexBuffer.UV4Kind
  18744. * - BABYLON.VertexBuffer.UV5Kind
  18745. * - BABYLON.VertexBuffer.UV6Kind
  18746. * - BABYLON.VertexBuffer.ColorKind
  18747. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18748. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18749. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18750. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18751. */
  18752. Mesh.prototype.getVertexBuffer = function (kind) {
  18753. if (!this._geometry) {
  18754. return undefined;
  18755. }
  18756. return this._geometry.getVertexBuffer(kind);
  18757. };
  18758. /**
  18759. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  18760. * Possible `kind` values :
  18761. * - BABYLON.VertexBuffer.PositionKind
  18762. * - BABYLON.VertexBuffer.UVKind
  18763. * - BABYLON.VertexBuffer.UV2Kind
  18764. * - BABYLON.VertexBuffer.UV3Kind
  18765. * - BABYLON.VertexBuffer.UV4Kind
  18766. * - BABYLON.VertexBuffer.UV5Kind
  18767. * - BABYLON.VertexBuffer.UV6Kind
  18768. * - BABYLON.VertexBuffer.ColorKind
  18769. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18770. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18771. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18772. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18773. */
  18774. Mesh.prototype.isVerticesDataPresent = function (kind) {
  18775. if (!this._geometry) {
  18776. if (this._delayInfo) {
  18777. return this._delayInfo.indexOf(kind) !== -1;
  18778. }
  18779. return false;
  18780. }
  18781. return this._geometry.isVerticesDataPresent(kind);
  18782. };
  18783. /**
  18784. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  18785. * Possible `kind` values :
  18786. * - BABYLON.VertexBuffer.PositionKind
  18787. * - BABYLON.VertexBuffer.UVKind
  18788. * - BABYLON.VertexBuffer.UV2Kind
  18789. * - BABYLON.VertexBuffer.UV3Kind
  18790. * - BABYLON.VertexBuffer.UV4Kind
  18791. * - BABYLON.VertexBuffer.UV5Kind
  18792. * - BABYLON.VertexBuffer.UV6Kind
  18793. * - BABYLON.VertexBuffer.ColorKind
  18794. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18795. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18796. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18797. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18798. */
  18799. Mesh.prototype.getVerticesDataKinds = function () {
  18800. if (!this._geometry) {
  18801. var result = [];
  18802. if (this._delayInfo) {
  18803. this._delayInfo.forEach(function (kind, index, array) {
  18804. result.push(kind);
  18805. });
  18806. }
  18807. return result;
  18808. }
  18809. return this._geometry.getVerticesDataKinds();
  18810. };
  18811. /**
  18812. * Returns a positive integer : the total number of indices in this mesh geometry.
  18813. * Returns zero if the mesh has no geometry.
  18814. */
  18815. Mesh.prototype.getTotalIndices = function () {
  18816. if (!this._geometry) {
  18817. return 0;
  18818. }
  18819. return this._geometry.getTotalIndices();
  18820. };
  18821. /**
  18822. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  18823. * 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.
  18824. * Returns an empty array if the mesh has no geometry.
  18825. */
  18826. Mesh.prototype.getIndices = function (copyWhenShared) {
  18827. if (!this._geometry) {
  18828. return [];
  18829. }
  18830. return this._geometry.getIndices(copyWhenShared);
  18831. };
  18832. Object.defineProperty(Mesh.prototype, "isBlocked", {
  18833. get: function () {
  18834. return this._masterMesh !== null && this._masterMesh !== undefined;
  18835. },
  18836. enumerable: true,
  18837. configurable: true
  18838. });
  18839. /**
  18840. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  18841. */
  18842. Mesh.prototype.isReady = function () {
  18843. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  18844. return false;
  18845. }
  18846. return _super.prototype.isReady.call(this);
  18847. };
  18848. /**
  18849. * Boolean : true if the mesh has been disposed.
  18850. */
  18851. Mesh.prototype.isDisposed = function () {
  18852. return this._isDisposed;
  18853. };
  18854. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  18855. get: function () {
  18856. return this._sideOrientation;
  18857. },
  18858. /**
  18859. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  18860. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  18861. */
  18862. set: function (sideO) {
  18863. this._sideOrientation = sideO;
  18864. },
  18865. enumerable: true,
  18866. configurable: true
  18867. });
  18868. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  18869. /**
  18870. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  18871. * This property is pertinent only for updatable parametric shapes.
  18872. */
  18873. get: function () {
  18874. return this._areNormalsFrozen;
  18875. },
  18876. enumerable: true,
  18877. configurable: true
  18878. });
  18879. /**
  18880. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  18881. * It has no effect at all on other shapes.
  18882. * It prevents the mesh normals from being recomputed on next `positions` array update.
  18883. * Returns the Mesh.
  18884. */
  18885. Mesh.prototype.freezeNormals = function () {
  18886. this._areNormalsFrozen = true;
  18887. return this;
  18888. };
  18889. /**
  18890. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  18891. * It has no effect at all on other shapes.
  18892. * It reactivates the mesh normals computation if it was previously frozen.
  18893. * Returns the Mesh.
  18894. */
  18895. Mesh.prototype.unfreezeNormals = function () {
  18896. this._areNormalsFrozen = false;
  18897. return this;
  18898. };
  18899. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  18900. /**
  18901. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  18902. */
  18903. set: function (count) {
  18904. this._overridenInstanceCount = count;
  18905. },
  18906. enumerable: true,
  18907. configurable: true
  18908. });
  18909. // Methods
  18910. Mesh.prototype._preActivate = function () {
  18911. var sceneRenderId = this.getScene().getRenderId();
  18912. if (this._preActivateId === sceneRenderId) {
  18913. return this;
  18914. }
  18915. this._preActivateId = sceneRenderId;
  18916. this._visibleInstances = null;
  18917. return this;
  18918. };
  18919. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  18920. if (this._visibleInstances) {
  18921. this._visibleInstances.intermediateDefaultRenderId = renderId;
  18922. }
  18923. return this;
  18924. };
  18925. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  18926. if (!this._visibleInstances) {
  18927. this._visibleInstances = {};
  18928. this._visibleInstances.defaultRenderId = renderId;
  18929. this._visibleInstances.selfDefaultRenderId = this._renderId;
  18930. }
  18931. if (!this._visibleInstances[renderId]) {
  18932. this._visibleInstances[renderId] = new Array();
  18933. }
  18934. this._visibleInstances[renderId].push(instance);
  18935. return this;
  18936. };
  18937. /**
  18938. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  18939. * This means the mesh underlying bounding box and sphere are recomputed.
  18940. * Returns the Mesh.
  18941. */
  18942. Mesh.prototype.refreshBoundingInfo = function () {
  18943. if (this._boundingInfo.isLocked) {
  18944. return;
  18945. }
  18946. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18947. if (data) {
  18948. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  18949. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  18950. }
  18951. if (this.subMeshes) {
  18952. for (var index = 0; index < this.subMeshes.length; index++) {
  18953. this.subMeshes[index].refreshBoundingInfo();
  18954. }
  18955. }
  18956. this._updateBoundingInfo();
  18957. return this;
  18958. };
  18959. Mesh.prototype._createGlobalSubMesh = function () {
  18960. var totalVertices = this.getTotalVertices();
  18961. if (!totalVertices || !this.getIndices()) {
  18962. return null;
  18963. }
  18964. this.releaseSubMeshes();
  18965. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  18966. };
  18967. Mesh.prototype.subdivide = function (count) {
  18968. if (count < 1) {
  18969. return;
  18970. }
  18971. var totalIndices = this.getTotalIndices();
  18972. var subdivisionSize = (totalIndices / count) | 0;
  18973. var offset = 0;
  18974. // Ensure that subdivisionSize is a multiple of 3
  18975. while (subdivisionSize % 3 !== 0) {
  18976. subdivisionSize++;
  18977. }
  18978. this.releaseSubMeshes();
  18979. for (var index = 0; index < count; index++) {
  18980. if (offset >= totalIndices) {
  18981. break;
  18982. }
  18983. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  18984. offset += subdivisionSize;
  18985. }
  18986. this.synchronizeInstances();
  18987. };
  18988. /**
  18989. * Sets the vertex data of the mesh geometry for the requested `kind`.
  18990. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  18991. * The `data` are either a numeric array either a Float32Array.
  18992. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  18993. * 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).
  18994. * Note that a new underlying VertexBuffer object is created each call.
  18995. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  18996. *
  18997. * Possible `kind` values :
  18998. * - BABYLON.VertexBuffer.PositionKind
  18999. * - BABYLON.VertexBuffer.UVKind
  19000. * - BABYLON.VertexBuffer.UV2Kind
  19001. * - BABYLON.VertexBuffer.UV3Kind
  19002. * - BABYLON.VertexBuffer.UV4Kind
  19003. * - BABYLON.VertexBuffer.UV5Kind
  19004. * - BABYLON.VertexBuffer.UV6Kind
  19005. * - BABYLON.VertexBuffer.ColorKind
  19006. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19007. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19008. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19009. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19010. *
  19011. * Returns the Mesh.
  19012. */
  19013. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  19014. if (!this._geometry) {
  19015. var vertexData = new BABYLON.VertexData();
  19016. vertexData.set(data, kind);
  19017. var scene = this.getScene();
  19018. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  19019. }
  19020. else {
  19021. this._geometry.setVerticesData(kind, data, updatable, stride);
  19022. }
  19023. return this;
  19024. };
  19025. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  19026. if (updatable === void 0) { updatable = true; }
  19027. if (this.getVertexBuffer(kind).isUpdatable() === updatable) {
  19028. return;
  19029. }
  19030. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  19031. };
  19032. /**
  19033. * Sets the mesh VertexBuffer.
  19034. * Returns the Mesh.
  19035. */
  19036. Mesh.prototype.setVerticesBuffer = function (buffer) {
  19037. if (!this._geometry) {
  19038. var scene = this.getScene();
  19039. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene).applyToMesh(this);
  19040. }
  19041. this._geometry.setVerticesBuffer(buffer);
  19042. return this;
  19043. };
  19044. /**
  19045. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  19046. * If the mesh has no geometry, it is simply returned as it is.
  19047. * The `data` are either a numeric array either a Float32Array.
  19048. * No new underlying VertexBuffer object is created.
  19049. * 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.
  19050. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  19051. *
  19052. * Possible `kind` values :
  19053. * - BABYLON.VertexBuffer.PositionKind
  19054. * - BABYLON.VertexBuffer.UVKind
  19055. * - BABYLON.VertexBuffer.UV2Kind
  19056. * - BABYLON.VertexBuffer.UV3Kind
  19057. * - BABYLON.VertexBuffer.UV4Kind
  19058. * - BABYLON.VertexBuffer.UV5Kind
  19059. * - BABYLON.VertexBuffer.UV6Kind
  19060. * - BABYLON.VertexBuffer.ColorKind
  19061. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19062. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19063. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19064. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19065. *
  19066. * Returns the Mesh.
  19067. */
  19068. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  19069. if (!this._geometry) {
  19070. return;
  19071. }
  19072. if (!makeItUnique) {
  19073. this._geometry.updateVerticesData(kind, data, updateExtends);
  19074. }
  19075. else {
  19076. this.makeGeometryUnique();
  19077. this.updateVerticesData(kind, data, updateExtends, false);
  19078. }
  19079. return this;
  19080. };
  19081. /**
  19082. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  19083. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  19084. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  19085. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  19086. * Returns the Mesh.
  19087. */
  19088. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  19089. if (computeNormals === void 0) { computeNormals = true; }
  19090. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19091. positionFunction(positions);
  19092. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  19093. if (computeNormals) {
  19094. var indices = this.getIndices();
  19095. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19096. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  19097. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  19098. }
  19099. return this;
  19100. };
  19101. /**
  19102. * Creates a un-shared specific occurence of the geometry for the mesh.
  19103. * Returns the Mesh.
  19104. */
  19105. Mesh.prototype.makeGeometryUnique = function () {
  19106. if (!this._geometry) {
  19107. return;
  19108. }
  19109. var oldGeometry = this._geometry;
  19110. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  19111. oldGeometry.releaseForMesh(this, true);
  19112. geometry.applyToMesh(this);
  19113. return this;
  19114. };
  19115. /**
  19116. * Sets the mesh indices.
  19117. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  19118. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  19119. * This method creates a new index buffer each call.
  19120. * Returns the Mesh.
  19121. */
  19122. Mesh.prototype.setIndices = function (indices, totalVertices) {
  19123. if (!this._geometry) {
  19124. var vertexData = new BABYLON.VertexData();
  19125. vertexData.indices = indices;
  19126. var scene = this.getScene();
  19127. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  19128. }
  19129. else {
  19130. this._geometry.setIndices(indices, totalVertices);
  19131. }
  19132. return this;
  19133. };
  19134. /**
  19135. * Invert the geometry to move from a right handed system to a left handed one.
  19136. * Returns the Mesh.
  19137. */
  19138. Mesh.prototype.toLeftHanded = function () {
  19139. if (!this._geometry) {
  19140. return;
  19141. }
  19142. this._geometry.toLeftHanded();
  19143. return this;
  19144. };
  19145. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  19146. var engine = this.getScene().getEngine();
  19147. // Wireframe
  19148. var indexToBind;
  19149. if (this._unIndexed) {
  19150. indexToBind = null;
  19151. }
  19152. else {
  19153. switch (fillMode) {
  19154. case BABYLON.Material.PointFillMode:
  19155. indexToBind = null;
  19156. break;
  19157. case BABYLON.Material.WireFrameFillMode:
  19158. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  19159. break;
  19160. default:
  19161. case BABYLON.Material.TriangleFillMode:
  19162. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  19163. break;
  19164. }
  19165. }
  19166. // VBOs
  19167. this._geometry._bind(effect, indexToBind);
  19168. return this;
  19169. };
  19170. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  19171. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  19172. return this;
  19173. }
  19174. this.onBeforeDrawObservable.notifyObservers(this);
  19175. var engine = this.getScene().getEngine();
  19176. // Draw order
  19177. switch (fillMode) {
  19178. case BABYLON.Material.PointFillMode:
  19179. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  19180. break;
  19181. case BABYLON.Material.WireFrameFillMode:
  19182. if (this._unIndexed) {
  19183. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  19184. }
  19185. else {
  19186. engine.draw(false, 0, instancesCount > 0 ? subMesh.linesIndexCount / 2 : subMesh.linesIndexCount, instancesCount);
  19187. }
  19188. break;
  19189. default:
  19190. if (this._unIndexed) {
  19191. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  19192. }
  19193. else {
  19194. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  19195. }
  19196. }
  19197. return this;
  19198. };
  19199. /**
  19200. * Registers for this mesh a javascript function called just before the rendering process.
  19201. * This function is passed the current mesh.
  19202. * Return the Mesh.
  19203. */
  19204. Mesh.prototype.registerBeforeRender = function (func) {
  19205. this.onBeforeRenderObservable.add(func);
  19206. return this;
  19207. };
  19208. /**
  19209. * Disposes a previously registered javascript function called before the rendering.
  19210. * This function is passed the current mesh.
  19211. * Returns the Mesh.
  19212. */
  19213. Mesh.prototype.unregisterBeforeRender = function (func) {
  19214. this.onBeforeRenderObservable.removeCallback(func);
  19215. return this;
  19216. };
  19217. /**
  19218. * Registers for this mesh a javascript function called just after the rendering is complete.
  19219. * This function is passed the current mesh.
  19220. * Returns the Mesh.
  19221. */
  19222. Mesh.prototype.registerAfterRender = function (func) {
  19223. this.onAfterRenderObservable.add(func);
  19224. return this;
  19225. };
  19226. /**
  19227. * Disposes a previously registered javascript function called after the rendering.
  19228. * This function is passed the current mesh.
  19229. * Return the Mesh.
  19230. */
  19231. Mesh.prototype.unregisterAfterRender = function (func) {
  19232. this.onAfterRenderObservable.removeCallback(func);
  19233. return this;
  19234. };
  19235. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  19236. var scene = this.getScene();
  19237. this._batchCache.mustReturn = false;
  19238. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  19239. this._batchCache.visibleInstances[subMeshId] = null;
  19240. if (this._visibleInstances) {
  19241. var currentRenderId = scene.getRenderId();
  19242. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  19243. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  19244. var selfRenderId = this._renderId;
  19245. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  19246. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  19247. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  19248. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  19249. }
  19250. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  19251. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  19252. this._batchCache.mustReturn = true;
  19253. return this._batchCache;
  19254. }
  19255. if (currentRenderId !== selfRenderId) {
  19256. this._batchCache.renderSelf[subMeshId] = false;
  19257. }
  19258. }
  19259. this._renderIdForInstances[subMeshId] = currentRenderId;
  19260. }
  19261. return this._batchCache;
  19262. };
  19263. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  19264. var visibleInstances = batch.visibleInstances[subMesh._id];
  19265. var matricesCount = visibleInstances.length + 1;
  19266. var bufferSize = matricesCount * 16 * 4;
  19267. var currentInstancesBufferSize = this._instancesBufferSize;
  19268. var instancesBuffer = this._instancesBuffer;
  19269. while (this._instancesBufferSize < bufferSize) {
  19270. this._instancesBufferSize *= 2;
  19271. }
  19272. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  19273. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  19274. }
  19275. var offset = 0;
  19276. var instancesCount = 0;
  19277. var world = this.getWorldMatrix();
  19278. if (batch.renderSelf[subMesh._id]) {
  19279. world.copyToArray(this._instancesData, offset);
  19280. offset += 16;
  19281. instancesCount++;
  19282. }
  19283. if (visibleInstances) {
  19284. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  19285. var instance = visibleInstances[instanceIndex];
  19286. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  19287. offset += 16;
  19288. instancesCount++;
  19289. }
  19290. }
  19291. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  19292. if (instancesBuffer) {
  19293. instancesBuffer.dispose();
  19294. }
  19295. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  19296. this._instancesBuffer = instancesBuffer;
  19297. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  19298. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  19299. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  19300. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  19301. }
  19302. else {
  19303. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  19304. }
  19305. this.geometry._bind(effect);
  19306. this._draw(subMesh, fillMode, instancesCount);
  19307. engine.unbindInstanceAttributes();
  19308. return this;
  19309. };
  19310. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  19311. var scene = this.getScene();
  19312. var engine = scene.getEngine();
  19313. if (hardwareInstancedRendering) {
  19314. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  19315. }
  19316. else {
  19317. if (batch.renderSelf[subMesh._id]) {
  19318. // Draw
  19319. if (onBeforeDraw) {
  19320. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  19321. }
  19322. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  19323. }
  19324. if (batch.visibleInstances[subMesh._id]) {
  19325. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  19326. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  19327. // World
  19328. var world = instance.getWorldMatrix();
  19329. if (onBeforeDraw) {
  19330. onBeforeDraw(true, world, effectiveMaterial);
  19331. }
  19332. // Draw
  19333. this._draw(subMesh, fillMode);
  19334. }
  19335. }
  19336. }
  19337. return this;
  19338. };
  19339. /**
  19340. * Triggers the draw call for the mesh.
  19341. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  19342. * Returns the Mesh.
  19343. */
  19344. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  19345. var scene = this.getScene();
  19346. // Managing instances
  19347. var batch = this._getInstancesRenderList(subMesh._id);
  19348. if (batch.mustReturn) {
  19349. return this;
  19350. }
  19351. // Checking geometry state
  19352. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  19353. return this;
  19354. }
  19355. var callbackIndex;
  19356. this.onBeforeRenderObservable.notifyObservers(this);
  19357. var engine = scene.getEngine();
  19358. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  19359. // Material
  19360. var effectiveMaterial = subMesh.getMaterial();
  19361. if (!effectiveMaterial) {
  19362. return this;
  19363. }
  19364. if (effectiveMaterial.storeEffectOnSubMeshes) {
  19365. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  19366. return this;
  19367. }
  19368. }
  19369. else if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  19370. return this;
  19371. }
  19372. // Outline - step 1
  19373. var savedDepthWrite = engine.getDepthWrite();
  19374. if (this.renderOutline) {
  19375. engine.setDepthWrite(false);
  19376. scene.getOutlineRenderer().render(subMesh, batch);
  19377. engine.setDepthWrite(savedDepthWrite);
  19378. }
  19379. var effect;
  19380. if (effectiveMaterial.storeEffectOnSubMeshes) {
  19381. effect = subMesh.effect;
  19382. }
  19383. else {
  19384. effect = effectiveMaterial.getEffect();
  19385. }
  19386. effectiveMaterial._preBind(effect);
  19387. // Bind
  19388. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  19389. this._bind(subMesh, effect, fillMode);
  19390. var world = this.getWorldMatrix();
  19391. if (effectiveMaterial.storeEffectOnSubMeshes) {
  19392. effectiveMaterial.bindForSubMesh(world, this, subMesh);
  19393. }
  19394. else {
  19395. effectiveMaterial.bind(world, this);
  19396. }
  19397. // Alpha mode
  19398. if (enableAlphaMode) {
  19399. engine.setAlphaMode(effectiveMaterial.alphaMode);
  19400. }
  19401. // Draw
  19402. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, effectiveMaterial);
  19403. // Unbind
  19404. effectiveMaterial.unbind();
  19405. // Outline - step 2
  19406. if (this.renderOutline && savedDepthWrite) {
  19407. engine.setDepthWrite(true);
  19408. engine.setColorWrite(false);
  19409. scene.getOutlineRenderer().render(subMesh, batch);
  19410. engine.setColorWrite(true);
  19411. }
  19412. // Overlay
  19413. if (this.renderOverlay) {
  19414. var currentMode = engine.getAlphaMode();
  19415. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  19416. scene.getOutlineRenderer().render(subMesh, batch, true);
  19417. engine.setAlphaMode(currentMode);
  19418. }
  19419. this.onAfterRenderObservable.notifyObservers(this);
  19420. return this;
  19421. };
  19422. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  19423. if (isInstance) {
  19424. effectiveMaterial.bindOnlyWorldMatrix(world);
  19425. }
  19426. return this;
  19427. };
  19428. /**
  19429. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  19430. */
  19431. Mesh.prototype.getEmittedParticleSystems = function () {
  19432. var results = new Array();
  19433. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  19434. var particleSystem = this.getScene().particleSystems[index];
  19435. if (particleSystem.emitter === this) {
  19436. results.push(particleSystem);
  19437. }
  19438. }
  19439. return results;
  19440. };
  19441. /**
  19442. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  19443. */
  19444. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  19445. var results = new Array();
  19446. var descendants = this.getDescendants();
  19447. descendants.push(this);
  19448. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  19449. var particleSystem = this.getScene().particleSystems[index];
  19450. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  19451. results.push(particleSystem);
  19452. }
  19453. }
  19454. return results;
  19455. };
  19456. Mesh.prototype._checkDelayState = function () {
  19457. var scene = this.getScene();
  19458. if (this._geometry) {
  19459. this._geometry.load(scene);
  19460. }
  19461. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  19462. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  19463. this._queueLoad(this, scene);
  19464. }
  19465. return this;
  19466. };
  19467. Mesh.prototype._queueLoad = function (mesh, scene) {
  19468. var _this = this;
  19469. scene._addPendingData(mesh);
  19470. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  19471. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  19472. if (data instanceof ArrayBuffer) {
  19473. _this._delayLoadingFunction(data, _this);
  19474. }
  19475. else {
  19476. _this._delayLoadingFunction(JSON.parse(data), _this);
  19477. }
  19478. _this.instances.forEach(function (instance) {
  19479. instance._syncSubMeshes();
  19480. });
  19481. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  19482. scene._removePendingData(_this);
  19483. }, function () { }, scene.database, getBinaryData);
  19484. return this;
  19485. };
  19486. /**
  19487. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  19488. */
  19489. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  19490. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  19491. return false;
  19492. }
  19493. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  19494. return false;
  19495. }
  19496. this._checkDelayState();
  19497. return true;
  19498. };
  19499. /**
  19500. * Sets the mesh material by the material or multiMaterial `id` property.
  19501. * The material `id` is a string identifying the material or the multiMaterial.
  19502. * This method returns the Mesh.
  19503. */
  19504. Mesh.prototype.setMaterialByID = function (id) {
  19505. var materials = this.getScene().materials;
  19506. var index;
  19507. for (index = 0; index < materials.length; index++) {
  19508. if (materials[index].id === id) {
  19509. this.material = materials[index];
  19510. return this;
  19511. }
  19512. }
  19513. // Multi
  19514. var multiMaterials = this.getScene().multiMaterials;
  19515. for (index = 0; index < multiMaterials.length; index++) {
  19516. if (multiMaterials[index].id === id) {
  19517. this.material = multiMaterials[index];
  19518. return this;
  19519. }
  19520. }
  19521. return this;
  19522. };
  19523. /**
  19524. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  19525. */
  19526. Mesh.prototype.getAnimatables = function () {
  19527. var results = [];
  19528. if (this.material) {
  19529. results.push(this.material);
  19530. }
  19531. if (this.skeleton) {
  19532. results.push(this.skeleton);
  19533. }
  19534. return results;
  19535. };
  19536. /**
  19537. * Modifies the mesh geometry according to the passed transformation matrix.
  19538. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  19539. * The mesh normals are modified accordingly the same transformation.
  19540. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  19541. * Note that, under the hood, this method sets a new VertexBuffer each call.
  19542. * Returns the Mesh.
  19543. */
  19544. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  19545. // Position
  19546. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  19547. return this;
  19548. }
  19549. var submeshes = this.subMeshes.splice(0);
  19550. this._resetPointsArrayCache();
  19551. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19552. var temp = [];
  19553. var index;
  19554. for (index = 0; index < data.length; index += 3) {
  19555. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  19556. }
  19557. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  19558. // Normals
  19559. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  19560. return this;
  19561. }
  19562. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19563. temp = [];
  19564. for (index = 0; index < data.length; index += 3) {
  19565. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  19566. }
  19567. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  19568. // flip faces?
  19569. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  19570. this.flipFaces();
  19571. }
  19572. // Restore submeshes
  19573. this.releaseSubMeshes();
  19574. this.subMeshes = submeshes;
  19575. return this;
  19576. };
  19577. /**
  19578. * Modifies the mesh geometry according to its own current World Matrix.
  19579. * The mesh World Matrix is then reset.
  19580. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  19581. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  19582. * Note that, under the hood, this method sets a new VertexBuffer each call.
  19583. * Returns the Mesh.
  19584. */
  19585. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  19586. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  19587. this.scaling.copyFromFloats(1, 1, 1);
  19588. this.position.copyFromFloats(0, 0, 0);
  19589. this.rotation.copyFromFloats(0, 0, 0);
  19590. //only if quaternion is already set
  19591. if (this.rotationQuaternion) {
  19592. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  19593. }
  19594. this._worldMatrix = BABYLON.Matrix.Identity();
  19595. return this;
  19596. };
  19597. // Cache
  19598. Mesh.prototype._resetPointsArrayCache = function () {
  19599. this._positions = null;
  19600. return this;
  19601. };
  19602. Mesh.prototype._generatePointsArray = function () {
  19603. if (this._positions)
  19604. return true;
  19605. this._positions = [];
  19606. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19607. if (!data) {
  19608. return false;
  19609. }
  19610. for (var index = 0; index < data.length; index += 3) {
  19611. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  19612. }
  19613. return true;
  19614. };
  19615. /**
  19616. * Returns a new Mesh object generated from the current mesh properties.
  19617. * This method must not get confused with createInstance().
  19618. * The parameter `name` is a string, the name given to the new mesh.
  19619. * The optional parameter `newParent` can be any Node object (default `null`).
  19620. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  19621. * 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.
  19622. */
  19623. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  19624. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  19625. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  19626. };
  19627. /**
  19628. * Disposes the mesh.
  19629. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  19630. */
  19631. Mesh.prototype.dispose = function (doNotRecurse) {
  19632. var _this = this;
  19633. this.morphTargetManager = undefined;
  19634. if (this._geometry) {
  19635. this._geometry.releaseForMesh(this, true);
  19636. }
  19637. // Sources
  19638. var meshes = this.getScene().meshes;
  19639. meshes.forEach(function (mesh) {
  19640. if (mesh._source && mesh._source === _this) {
  19641. mesh._source = null;
  19642. }
  19643. });
  19644. this._source = null;
  19645. // Instances
  19646. if (this._instancesBuffer) {
  19647. this._instancesBuffer.dispose();
  19648. this._instancesBuffer = null;
  19649. }
  19650. while (this.instances.length) {
  19651. this.instances[0].dispose();
  19652. }
  19653. // Highlight layers.
  19654. var highlightLayers = this.getScene().highlightLayers;
  19655. for (var i = 0; i < highlightLayers.length; i++) {
  19656. var highlightLayer = highlightLayers[i];
  19657. if (highlightLayer) {
  19658. highlightLayer.removeMesh(this);
  19659. highlightLayer.removeExcludedMesh(this);
  19660. }
  19661. }
  19662. _super.prototype.dispose.call(this, doNotRecurse);
  19663. };
  19664. /**
  19665. * Modifies the mesh geometry according to a displacement map.
  19666. * 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.
  19667. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  19668. * This method returns nothing.
  19669. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  19670. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  19671. * 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.
  19672. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  19673. * The parameter `uvScale` is an optional vector2 used to scale UV.
  19674. *
  19675. * Returns the Mesh.
  19676. */
  19677. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  19678. var _this = this;
  19679. var scene = this.getScene();
  19680. var onload = function (img) {
  19681. // Getting height map data
  19682. var canvas = document.createElement("canvas");
  19683. var context = canvas.getContext("2d");
  19684. var heightMapWidth = img.width;
  19685. var heightMapHeight = img.height;
  19686. canvas.width = heightMapWidth;
  19687. canvas.height = heightMapHeight;
  19688. context.drawImage(img, 0, 0);
  19689. // Create VertexData from map data
  19690. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  19691. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  19692. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  19693. //execute success callback, if set
  19694. if (onSuccess) {
  19695. onSuccess(_this);
  19696. }
  19697. };
  19698. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  19699. return this;
  19700. };
  19701. /**
  19702. * Modifies the mesh geometry according to a displacementMap buffer.
  19703. * 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.
  19704. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  19705. * This method returns nothing.
  19706. * 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.
  19707. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  19708. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  19709. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  19710. * The parameter `uvScale` is an optional vector2 used to scale UV.
  19711. *
  19712. * Returns the Mesh.
  19713. */
  19714. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  19715. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  19716. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  19717. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  19718. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  19719. return this;
  19720. }
  19721. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19722. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19723. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  19724. var position = BABYLON.Vector3.Zero();
  19725. var normal = BABYLON.Vector3.Zero();
  19726. var uv = BABYLON.Vector2.Zero();
  19727. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  19728. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  19729. for (var index = 0; index < positions.length; index += 3) {
  19730. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  19731. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  19732. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  19733. // Compute height
  19734. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  19735. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  19736. var pos = (u + v * heightMapWidth) * 4;
  19737. var r = buffer[pos] / 255.0;
  19738. var g = buffer[pos + 1] / 255.0;
  19739. var b = buffer[pos + 2] / 255.0;
  19740. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  19741. normal.normalize();
  19742. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  19743. position = position.add(normal);
  19744. position.toArray(positions, index);
  19745. }
  19746. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  19747. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  19748. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  19749. return this;
  19750. };
  19751. /**
  19752. * Modify the mesh to get a flat shading rendering.
  19753. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  19754. * This method returns the Mesh.
  19755. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  19756. */
  19757. Mesh.prototype.convertToFlatShadedMesh = function () {
  19758. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  19759. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  19760. var kinds = this.getVerticesDataKinds();
  19761. var vbs = [];
  19762. var data = [];
  19763. var newdata = [];
  19764. var updatableNormals = false;
  19765. var kindIndex;
  19766. var kind;
  19767. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19768. kind = kinds[kindIndex];
  19769. var vertexBuffer = this.getVertexBuffer(kind);
  19770. if (kind === BABYLON.VertexBuffer.NormalKind) {
  19771. updatableNormals = vertexBuffer.isUpdatable();
  19772. kinds.splice(kindIndex, 1);
  19773. kindIndex--;
  19774. continue;
  19775. }
  19776. vbs[kind] = vertexBuffer;
  19777. data[kind] = vbs[kind].getData();
  19778. newdata[kind] = [];
  19779. }
  19780. // Save previous submeshes
  19781. var previousSubmeshes = this.subMeshes.slice(0);
  19782. var indices = this.getIndices();
  19783. var totalIndices = this.getTotalIndices();
  19784. // Generating unique vertices per face
  19785. var index;
  19786. for (index = 0; index < totalIndices; index++) {
  19787. var vertexIndex = indices[index];
  19788. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19789. kind = kinds[kindIndex];
  19790. var stride = vbs[kind].getStrideSize();
  19791. for (var offset = 0; offset < stride; offset++) {
  19792. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  19793. }
  19794. }
  19795. }
  19796. // Updating faces & normal
  19797. var normals = [];
  19798. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  19799. for (index = 0; index < totalIndices; index += 3) {
  19800. indices[index] = index;
  19801. indices[index + 1] = index + 1;
  19802. indices[index + 2] = index + 2;
  19803. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  19804. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  19805. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  19806. var p1p2 = p1.subtract(p2);
  19807. var p3p2 = p3.subtract(p2);
  19808. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  19809. // Store same normals for every vertex
  19810. for (var localIndex = 0; localIndex < 3; localIndex++) {
  19811. normals.push(normal.x);
  19812. normals.push(normal.y);
  19813. normals.push(normal.z);
  19814. }
  19815. }
  19816. this.setIndices(indices);
  19817. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  19818. // Updating vertex buffers
  19819. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19820. kind = kinds[kindIndex];
  19821. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  19822. }
  19823. // Updating submeshes
  19824. this.releaseSubMeshes();
  19825. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  19826. var previousOne = previousSubmeshes[submeshIndex];
  19827. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  19828. }
  19829. this.synchronizeInstances();
  19830. return this;
  19831. };
  19832. /**
  19833. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  19834. * In other words, more vertices, no more indices and a single bigger VBO.
  19835. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  19836. * Returns the Mesh.
  19837. */
  19838. Mesh.prototype.convertToUnIndexedMesh = function () {
  19839. /// <summary>Remove indices by unfolding faces into buffers</summary>
  19840. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  19841. var kinds = this.getVerticesDataKinds();
  19842. var vbs = [];
  19843. var data = [];
  19844. var newdata = [];
  19845. var updatableNormals = false;
  19846. var kindIndex;
  19847. var kind;
  19848. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19849. kind = kinds[kindIndex];
  19850. var vertexBuffer = this.getVertexBuffer(kind);
  19851. vbs[kind] = vertexBuffer;
  19852. data[kind] = vbs[kind].getData();
  19853. newdata[kind] = [];
  19854. }
  19855. // Save previous submeshes
  19856. var previousSubmeshes = this.subMeshes.slice(0);
  19857. var indices = this.getIndices();
  19858. var totalIndices = this.getTotalIndices();
  19859. // Generating unique vertices per face
  19860. var index;
  19861. for (index = 0; index < totalIndices; index++) {
  19862. var vertexIndex = indices[index];
  19863. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19864. kind = kinds[kindIndex];
  19865. var stride = vbs[kind].getStrideSize();
  19866. for (var offset = 0; offset < stride; offset++) {
  19867. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  19868. }
  19869. }
  19870. }
  19871. // Updating indices
  19872. for (index = 0; index < totalIndices; index += 3) {
  19873. indices[index] = index;
  19874. indices[index + 1] = index + 1;
  19875. indices[index + 2] = index + 2;
  19876. }
  19877. this.setIndices(indices);
  19878. // Updating vertex buffers
  19879. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19880. kind = kinds[kindIndex];
  19881. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  19882. }
  19883. // Updating submeshes
  19884. this.releaseSubMeshes();
  19885. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  19886. var previousOne = previousSubmeshes[submeshIndex];
  19887. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  19888. }
  19889. this._unIndexed = true;
  19890. this.synchronizeInstances();
  19891. return this;
  19892. };
  19893. /**
  19894. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  19895. * This method returns the Mesh.
  19896. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  19897. */
  19898. Mesh.prototype.flipFaces = function (flipNormals) {
  19899. if (flipNormals === void 0) { flipNormals = false; }
  19900. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  19901. var i;
  19902. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  19903. for (i = 0; i < vertex_data.normals.length; i++) {
  19904. vertex_data.normals[i] *= -1;
  19905. }
  19906. }
  19907. var temp;
  19908. for (i = 0; i < vertex_data.indices.length; i += 3) {
  19909. // reassign indices
  19910. temp = vertex_data.indices[i + 1];
  19911. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  19912. vertex_data.indices[i + 2] = temp;
  19913. }
  19914. vertex_data.applyToMesh(this);
  19915. return this;
  19916. };
  19917. // Instances
  19918. /**
  19919. * Creates a new InstancedMesh object from the mesh model.
  19920. * An instance shares the same properties and the same material than its model.
  19921. * Only these properties of each instance can then be set individually :
  19922. * - position
  19923. * - rotation
  19924. * - rotationQuaternion
  19925. * - setPivotMatrix
  19926. * - scaling
  19927. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  19928. * Warning : this method is not supported for Line mesh and LineSystem
  19929. */
  19930. Mesh.prototype.createInstance = function (name) {
  19931. return new BABYLON.InstancedMesh(name, this);
  19932. };
  19933. /**
  19934. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  19935. * After this call, all the mesh instances have the same submeshes than the current mesh.
  19936. * This method returns the Mesh.
  19937. */
  19938. Mesh.prototype.synchronizeInstances = function () {
  19939. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  19940. var instance = this.instances[instanceIndex];
  19941. instance._syncSubMeshes();
  19942. }
  19943. return this;
  19944. };
  19945. /**
  19946. * Simplify the mesh according to the given array of settings.
  19947. * Function will return immediately and will simplify async. It returns the Mesh.
  19948. * @param settings a collection of simplification settings.
  19949. * @param parallelProcessing should all levels calculate parallel or one after the other.
  19950. * @param type the type of simplification to run.
  19951. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  19952. */
  19953. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  19954. if (parallelProcessing === void 0) { parallelProcessing = true; }
  19955. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  19956. this.getScene().simplificationQueue.addTask({
  19957. settings: settings,
  19958. parallelProcessing: parallelProcessing,
  19959. mesh: this,
  19960. simplificationType: simplificationType,
  19961. successCallback: successCallback
  19962. });
  19963. return this;
  19964. };
  19965. /**
  19966. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  19967. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  19968. * This should be used together with the simplification to avoid disappearing triangles.
  19969. * Returns the Mesh.
  19970. * @param successCallback an optional success callback to be called after the optimization finished.
  19971. */
  19972. Mesh.prototype.optimizeIndices = function (successCallback) {
  19973. var _this = this;
  19974. var indices = this.getIndices();
  19975. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19976. var vectorPositions = [];
  19977. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  19978. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  19979. }
  19980. var dupes = [];
  19981. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  19982. var realPos = vectorPositions.length - 1 - iteration;
  19983. var testedPosition = vectorPositions[realPos];
  19984. for (var j = 0; j < realPos; ++j) {
  19985. var againstPosition = vectorPositions[j];
  19986. if (testedPosition.equals(againstPosition)) {
  19987. dupes[realPos] = j;
  19988. break;
  19989. }
  19990. }
  19991. }, function () {
  19992. for (var i = 0; i < indices.length; ++i) {
  19993. indices[i] = dupes[indices[i]] || indices[i];
  19994. }
  19995. //indices are now reordered
  19996. var originalSubMeshes = _this.subMeshes.slice(0);
  19997. _this.setIndices(indices);
  19998. _this.subMeshes = originalSubMeshes;
  19999. if (successCallback) {
  20000. successCallback(_this);
  20001. }
  20002. });
  20003. return this;
  20004. };
  20005. Mesh.prototype.serialize = function (serializationObject) {
  20006. serializationObject.name = this.name;
  20007. serializationObject.id = this.id;
  20008. serializationObject.type = this.getClassName();
  20009. if (BABYLON.Tags.HasTags(this)) {
  20010. serializationObject.tags = BABYLON.Tags.GetTags(this);
  20011. }
  20012. serializationObject.position = this.position.asArray();
  20013. if (this.rotationQuaternion) {
  20014. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  20015. }
  20016. else if (this.rotation) {
  20017. serializationObject.rotation = this.rotation.asArray();
  20018. }
  20019. serializationObject.scaling = this.scaling.asArray();
  20020. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  20021. serializationObject.isEnabled = this.isEnabled();
  20022. serializationObject.isVisible = this.isVisible;
  20023. serializationObject.infiniteDistance = this.infiniteDistance;
  20024. serializationObject.pickable = this.isPickable;
  20025. serializationObject.receiveShadows = this.receiveShadows;
  20026. serializationObject.billboardMode = this.billboardMode;
  20027. serializationObject.visibility = this.visibility;
  20028. serializationObject.checkCollisions = this.checkCollisions;
  20029. serializationObject.isBlocker = this.isBlocker;
  20030. // Parent
  20031. if (this.parent) {
  20032. serializationObject.parentId = this.parent.id;
  20033. }
  20034. // Geometry
  20035. var geometry = this._geometry;
  20036. if (geometry) {
  20037. var geometryId = geometry.id;
  20038. serializationObject.geometryId = geometryId;
  20039. // SubMeshes
  20040. serializationObject.subMeshes = [];
  20041. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20042. var subMesh = this.subMeshes[subIndex];
  20043. serializationObject.subMeshes.push({
  20044. materialIndex: subMesh.materialIndex,
  20045. verticesStart: subMesh.verticesStart,
  20046. verticesCount: subMesh.verticesCount,
  20047. indexStart: subMesh.indexStart,
  20048. indexCount: subMesh.indexCount
  20049. });
  20050. }
  20051. }
  20052. // Material
  20053. if (this.material) {
  20054. serializationObject.materialId = this.material.id;
  20055. }
  20056. else {
  20057. this.material = null;
  20058. }
  20059. // Morph targets
  20060. if (this.morphTargetManager) {
  20061. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  20062. }
  20063. // Skeleton
  20064. if (this.skeleton) {
  20065. serializationObject.skeletonId = this.skeleton.id;
  20066. }
  20067. // Physics
  20068. //TODO implement correct serialization for physics impostors.
  20069. if (this.getPhysicsImpostor()) {
  20070. var impostor = this.getPhysicsImpostor();
  20071. serializationObject.physicsMass = impostor.getParam("mass");
  20072. serializationObject.physicsFriction = impostor.getParam("friction");
  20073. serializationObject.physicsRestitution = impostor.getParam("mass");
  20074. serializationObject.physicsImpostor = this.getPhysicsImpostor().type;
  20075. }
  20076. // Metadata
  20077. if (this.metadata) {
  20078. serializationObject.metadata = this.metadata;
  20079. }
  20080. // Instances
  20081. serializationObject.instances = [];
  20082. for (var index = 0; index < this.instances.length; index++) {
  20083. var instance = this.instances[index];
  20084. var serializationInstance = {
  20085. name: instance.name,
  20086. position: instance.position.asArray(),
  20087. scaling: instance.scaling.asArray()
  20088. };
  20089. if (instance.rotationQuaternion) {
  20090. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  20091. }
  20092. else if (instance.rotation) {
  20093. serializationInstance.rotation = instance.rotation.asArray();
  20094. }
  20095. serializationObject.instances.push(serializationInstance);
  20096. // Animations
  20097. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  20098. serializationInstance.ranges = instance.serializeAnimationRanges();
  20099. }
  20100. //
  20101. // Animations
  20102. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  20103. serializationObject.ranges = this.serializeAnimationRanges();
  20104. // Layer mask
  20105. serializationObject.layerMask = this.layerMask;
  20106. // Alpha
  20107. serializationObject.alphaIndex = this.alphaIndex;
  20108. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  20109. // Overlay
  20110. serializationObject.overlayAlpha = this.overlayAlpha;
  20111. serializationObject.overlayColor = this.overlayColor.asArray();
  20112. serializationObject.renderOverlay = this.renderOverlay;
  20113. // Fog
  20114. serializationObject.applyFog = this.applyFog;
  20115. // Action Manager
  20116. if (this.actionManager) {
  20117. serializationObject.actions = this.actionManager.serialize(this.name);
  20118. }
  20119. };
  20120. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  20121. if (!this.geometry) {
  20122. return;
  20123. }
  20124. this._markSubMeshesAsAttributesDirty();
  20125. if (this._morphTargetManager && this._morphTargetManager.vertexCount) {
  20126. if (this._morphTargetManager.vertexCount !== this.getTotalVertices()) {
  20127. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  20128. this.morphTargetManager = undefined;
  20129. return;
  20130. }
  20131. for (var index = 0; index < this.morphTargetManager.numInfluencers; index++) {
  20132. var morphTarget = this.morphTargetManager.getActiveTarget(index);
  20133. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, morphTarget.getPositions(), false, 3);
  20134. if (morphTarget.hasNormals) {
  20135. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, morphTarget.getNormals(), false, 3);
  20136. }
  20137. if (morphTarget.hasTangents) {
  20138. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, morphTarget.getTangents(), false, 3);
  20139. }
  20140. }
  20141. }
  20142. else {
  20143. var index = 0;
  20144. // Positions
  20145. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  20146. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  20147. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  20148. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  20149. }
  20150. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  20151. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  20152. }
  20153. index++;
  20154. }
  20155. }
  20156. };
  20157. // Statics
  20158. /**
  20159. * Returns a new Mesh object what is a deep copy of the passed mesh.
  20160. * The parameter `parsedMesh` is the mesh to be copied.
  20161. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  20162. */
  20163. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  20164. var mesh;
  20165. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  20166. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  20167. }
  20168. else {
  20169. mesh = new Mesh(parsedMesh.name, scene);
  20170. }
  20171. mesh.id = parsedMesh.id;
  20172. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  20173. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  20174. if (parsedMesh.metadata !== undefined) {
  20175. mesh.metadata = parsedMesh.metadata;
  20176. }
  20177. if (parsedMesh.rotationQuaternion) {
  20178. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  20179. }
  20180. else if (parsedMesh.rotation) {
  20181. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  20182. }
  20183. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  20184. if (parsedMesh.localMatrix) {
  20185. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  20186. }
  20187. else if (parsedMesh.pivotMatrix) {
  20188. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  20189. }
  20190. mesh.setEnabled(parsedMesh.isEnabled);
  20191. mesh.isVisible = parsedMesh.isVisible;
  20192. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  20193. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  20194. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  20195. if (parsedMesh.applyFog !== undefined) {
  20196. mesh.applyFog = parsedMesh.applyFog;
  20197. }
  20198. if (parsedMesh.pickable !== undefined) {
  20199. mesh.isPickable = parsedMesh.pickable;
  20200. }
  20201. if (parsedMesh.alphaIndex !== undefined) {
  20202. mesh.alphaIndex = parsedMesh.alphaIndex;
  20203. }
  20204. mesh.receiveShadows = parsedMesh.receiveShadows;
  20205. mesh.billboardMode = parsedMesh.billboardMode;
  20206. if (parsedMesh.visibility !== undefined) {
  20207. mesh.visibility = parsedMesh.visibility;
  20208. }
  20209. mesh.checkCollisions = parsedMesh.checkCollisions;
  20210. if (parsedMesh.isBlocker !== undefined) {
  20211. mesh.isBlocker = parsedMesh.isBlocker;
  20212. }
  20213. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  20214. // freezeWorldMatrix
  20215. if (parsedMesh.freezeWorldMatrix) {
  20216. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  20217. }
  20218. // Parent
  20219. if (parsedMesh.parentId) {
  20220. mesh._waitingParentId = parsedMesh.parentId;
  20221. }
  20222. // Actions
  20223. if (parsedMesh.actions !== undefined) {
  20224. mesh._waitingActions = parsedMesh.actions;
  20225. }
  20226. // Overlay
  20227. if (parsedMesh.overlayAlpha !== undefined) {
  20228. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  20229. }
  20230. if (parsedMesh.overlayColor !== undefined) {
  20231. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  20232. }
  20233. if (parsedMesh.renderOverlay !== undefined) {
  20234. mesh.renderOverlay = parsedMesh.renderOverlay;
  20235. }
  20236. // Geometry
  20237. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  20238. if (parsedMesh.delayLoadingFile) {
  20239. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20240. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  20241. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  20242. if (parsedMesh._binaryInfo) {
  20243. mesh._binaryInfo = parsedMesh._binaryInfo;
  20244. }
  20245. mesh._delayInfo = [];
  20246. if (parsedMesh.hasUVs) {
  20247. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  20248. }
  20249. if (parsedMesh.hasUVs2) {
  20250. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  20251. }
  20252. if (parsedMesh.hasUVs3) {
  20253. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  20254. }
  20255. if (parsedMesh.hasUVs4) {
  20256. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  20257. }
  20258. if (parsedMesh.hasUVs5) {
  20259. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  20260. }
  20261. if (parsedMesh.hasUVs6) {
  20262. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  20263. }
  20264. if (parsedMesh.hasColors) {
  20265. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  20266. }
  20267. if (parsedMesh.hasMatricesIndices) {
  20268. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  20269. }
  20270. if (parsedMesh.hasMatricesWeights) {
  20271. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  20272. }
  20273. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  20274. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  20275. mesh._checkDelayState();
  20276. }
  20277. }
  20278. else {
  20279. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  20280. }
  20281. // Material
  20282. if (parsedMesh.materialId) {
  20283. mesh.setMaterialByID(parsedMesh.materialId);
  20284. }
  20285. else {
  20286. mesh.material = null;
  20287. }
  20288. // Morph targets
  20289. if (parsedMesh.morphTargetManagerId > -1) {
  20290. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  20291. }
  20292. // Skeleton
  20293. if (parsedMesh.skeletonId > -1) {
  20294. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  20295. if (parsedMesh.numBoneInfluencers) {
  20296. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  20297. }
  20298. }
  20299. // Animations
  20300. if (parsedMesh.animations) {
  20301. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  20302. var parsedAnimation = parsedMesh.animations[animationIndex];
  20303. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20304. }
  20305. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  20306. }
  20307. if (parsedMesh.autoAnimate) {
  20308. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  20309. }
  20310. // Layer Mask
  20311. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  20312. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  20313. }
  20314. else {
  20315. mesh.layerMask = 0x0FFFFFFF;
  20316. }
  20317. // Physics
  20318. if (parsedMesh.physicsImpostor) {
  20319. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  20320. mass: parsedMesh.physicsMass,
  20321. friction: parsedMesh.physicsFriction,
  20322. restitution: parsedMesh.physicsRestitution
  20323. }, scene);
  20324. }
  20325. // Instances
  20326. if (parsedMesh.instances) {
  20327. for (var index = 0; index < parsedMesh.instances.length; index++) {
  20328. var parsedInstance = parsedMesh.instances[index];
  20329. var instance = mesh.createInstance(parsedInstance.name);
  20330. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  20331. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  20332. if (parsedInstance.parentId) {
  20333. instance._waitingParentId = parsedInstance.parentId;
  20334. }
  20335. if (parsedInstance.rotationQuaternion) {
  20336. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  20337. }
  20338. else if (parsedInstance.rotation) {
  20339. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  20340. }
  20341. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  20342. instance.checkCollisions = mesh.checkCollisions;
  20343. if (parsedMesh.animations) {
  20344. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  20345. parsedAnimation = parsedMesh.animations[animationIndex];
  20346. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20347. }
  20348. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  20349. }
  20350. }
  20351. }
  20352. return mesh;
  20353. };
  20354. /**
  20355. * Creates a ribbon mesh.
  20356. * Please consider using the same method from the MeshBuilder class instead.
  20357. * 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.
  20358. *
  20359. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  20360. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  20361. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  20362. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  20363. * 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.
  20364. * 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.
  20365. * 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
  20366. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20367. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20368. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20369. */
  20370. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  20371. return BABYLON.MeshBuilder.CreateRibbon(name, {
  20372. pathArray: pathArray,
  20373. closeArray: closeArray,
  20374. closePath: closePath,
  20375. offset: offset,
  20376. updatable: updatable,
  20377. sideOrientation: sideOrientation,
  20378. instance: instance
  20379. }, scene);
  20380. };
  20381. /**
  20382. * Creates a plane polygonal mesh. By default, this is a disc.
  20383. * Please consider using the same method from the MeshBuilder class instead.
  20384. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  20385. * 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.
  20386. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20387. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20388. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20389. */
  20390. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  20391. var options = {
  20392. radius: radius,
  20393. tessellation: tessellation,
  20394. sideOrientation: sideOrientation,
  20395. updatable: updatable
  20396. };
  20397. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  20398. };
  20399. /**
  20400. * Creates a box mesh.
  20401. * Please consider using the same method from the MeshBuilder class instead.
  20402. * The parameter `size` sets the size (float) of each box side (default 1).
  20403. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20404. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20405. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20406. */
  20407. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  20408. var options = {
  20409. size: size,
  20410. sideOrientation: sideOrientation,
  20411. updatable: updatable
  20412. };
  20413. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  20414. };
  20415. /**
  20416. * Creates a sphere mesh.
  20417. * Please consider using the same method from the MeshBuilder class instead.
  20418. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  20419. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  20420. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20421. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20422. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20423. */
  20424. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  20425. var options = {
  20426. segments: segments,
  20427. diameterX: diameter,
  20428. diameterY: diameter,
  20429. diameterZ: diameter,
  20430. sideOrientation: sideOrientation,
  20431. updatable: updatable
  20432. };
  20433. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  20434. };
  20435. /**
  20436. * Creates a cylinder or a cone mesh.
  20437. * Please consider using the same method from the MeshBuilder class instead.
  20438. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  20439. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  20440. * 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.
  20441. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  20442. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  20443. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20444. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20445. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20446. */
  20447. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  20448. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  20449. if (scene !== undefined) {
  20450. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  20451. updatable = scene;
  20452. }
  20453. scene = subdivisions;
  20454. subdivisions = 1;
  20455. }
  20456. var options = {
  20457. height: height,
  20458. diameterTop: diameterTop,
  20459. diameterBottom: diameterBottom,
  20460. tessellation: tessellation,
  20461. subdivisions: subdivisions,
  20462. sideOrientation: sideOrientation,
  20463. updatable: updatable
  20464. };
  20465. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  20466. };
  20467. // Torus (Code from SharpDX.org)
  20468. /**
  20469. * Creates a torus mesh.
  20470. * Please consider using the same method from the MeshBuilder class instead.
  20471. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  20472. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  20473. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  20474. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20475. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20476. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20477. */
  20478. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  20479. var options = {
  20480. diameter: diameter,
  20481. thickness: thickness,
  20482. tessellation: tessellation,
  20483. sideOrientation: sideOrientation,
  20484. updatable: updatable
  20485. };
  20486. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  20487. };
  20488. /**
  20489. * Creates a torus knot mesh.
  20490. * Please consider using the same method from the MeshBuilder class instead.
  20491. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  20492. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  20493. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  20494. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  20495. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20496. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20497. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20498. */
  20499. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  20500. var options = {
  20501. radius: radius,
  20502. tube: tube,
  20503. radialSegments: radialSegments,
  20504. tubularSegments: tubularSegments,
  20505. p: p,
  20506. q: q,
  20507. sideOrientation: sideOrientation,
  20508. updatable: updatable
  20509. };
  20510. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  20511. };
  20512. /**
  20513. * Creates a line mesh.
  20514. * Please consider using the same method from the MeshBuilder class instead.
  20515. * 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.
  20516. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  20517. * The parameter `points` is an array successive Vector3.
  20518. * 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
  20519. * When updating an instance, remember that only point positions can change, not the number of points.
  20520. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20521. */
  20522. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  20523. var options = {
  20524. points: points,
  20525. updatable: updatable,
  20526. instance: instance
  20527. };
  20528. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  20529. };
  20530. /**
  20531. * Creates a dashed line mesh.
  20532. * Please consider using the same method from the MeshBuilder class instead.
  20533. * 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.
  20534. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  20535. * The parameter `points` is an array successive Vector3.
  20536. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  20537. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  20538. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  20539. * 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
  20540. * When updating an instance, remember that only point positions can change, not the number of points.
  20541. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20542. */
  20543. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  20544. var options = {
  20545. points: points,
  20546. dashSize: dashSize,
  20547. gapSize: gapSize,
  20548. dashNb: dashNb,
  20549. updatable: updatable,
  20550. instance: instance
  20551. };
  20552. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  20553. };
  20554. /**
  20555. * Creates an extruded shape mesh.
  20556. * 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.
  20557. * Please consider using the same method from the MeshBuilder class instead.
  20558. *
  20559. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  20560. * 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
  20561. * extruded along the Z axis.
  20562. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  20563. * 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.
  20564. * The parameter `scale` (float, default 1) is the value to scale the shape.
  20565. * 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
  20566. * 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
  20567. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  20568. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20569. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20570. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20571. */
  20572. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  20573. var options = {
  20574. shape: shape,
  20575. path: path,
  20576. scale: scale,
  20577. rotation: rotation,
  20578. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  20579. sideOrientation: sideOrientation,
  20580. instance: instance,
  20581. updatable: updatable
  20582. };
  20583. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  20584. };
  20585. /**
  20586. * Creates an custom extruded shape mesh.
  20587. * 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.
  20588. * Please consider using the same method from the MeshBuilder class instead.
  20589. *
  20590. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  20591. * 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
  20592. * extruded along the Z axis.
  20593. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  20594. * 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
  20595. * and the distance of this point from the begining of the path :
  20596. * ```javascript
  20597. * var rotationFunction = function(i, distance) {
  20598. * // do things
  20599. * return rotationValue; }
  20600. * ```
  20601. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  20602. * 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
  20603. * and the distance of this point from the begining of the path :
  20604. * ```javascript
  20605. * var scaleFunction = function(i, distance) {
  20606. * // do things
  20607. * return scaleValue;}
  20608. * ```
  20609. * It must returns a float value that will be the scale value applied to the shape on each path point.
  20610. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  20611. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  20612. * 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
  20613. * 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
  20614. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  20615. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20616. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20617. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20618. */
  20619. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  20620. var options = {
  20621. shape: shape,
  20622. path: path,
  20623. scaleFunction: scaleFunction,
  20624. rotationFunction: rotationFunction,
  20625. ribbonCloseArray: ribbonCloseArray,
  20626. ribbonClosePath: ribbonClosePath,
  20627. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  20628. sideOrientation: sideOrientation,
  20629. instance: instance,
  20630. updatable: updatable
  20631. };
  20632. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  20633. };
  20634. /**
  20635. * Creates lathe mesh.
  20636. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  20637. * Please consider using the same method from the MeshBuilder class instead.
  20638. * 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
  20639. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  20640. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  20641. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  20642. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20643. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20644. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20645. */
  20646. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  20647. var options = {
  20648. shape: shape,
  20649. radius: radius,
  20650. tessellation: tessellation,
  20651. sideOrientation: sideOrientation,
  20652. updatable: updatable
  20653. };
  20654. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  20655. };
  20656. /**
  20657. * Creates a plane mesh.
  20658. * Please consider using the same method from the MeshBuilder class instead.
  20659. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  20660. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20661. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20662. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20663. */
  20664. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  20665. var options = {
  20666. size: size,
  20667. width: size,
  20668. height: size,
  20669. sideOrientation: sideOrientation,
  20670. updatable: updatable
  20671. };
  20672. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  20673. };
  20674. /**
  20675. * Creates a ground mesh.
  20676. * Please consider using the same method from the MeshBuilder class instead.
  20677. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  20678. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  20679. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20680. */
  20681. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  20682. var options = {
  20683. width: width,
  20684. height: height,
  20685. subdivisions: subdivisions,
  20686. updatable: updatable
  20687. };
  20688. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  20689. };
  20690. /**
  20691. * Creates a tiled ground mesh.
  20692. * Please consider using the same method from the MeshBuilder class instead.
  20693. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  20694. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  20695. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  20696. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  20697. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  20698. * numbers of subdivisions on the ground width and height of each tile.
  20699. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20700. */
  20701. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  20702. var options = {
  20703. xmin: xmin,
  20704. zmin: zmin,
  20705. xmax: xmax,
  20706. zmax: zmax,
  20707. subdivisions: subdivisions,
  20708. precision: precision,
  20709. updatable: updatable
  20710. };
  20711. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  20712. };
  20713. /**
  20714. * Creates a ground mesh from a height map.
  20715. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  20716. * Please consider using the same method from the MeshBuilder class instead.
  20717. * The parameter `url` sets the URL of the height map image resource.
  20718. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  20719. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  20720. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  20721. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  20722. * 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).
  20723. * This function is passed the newly built mesh :
  20724. * ```javascript
  20725. * function(mesh) { // do things
  20726. * return; }
  20727. * ```
  20728. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20729. */
  20730. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  20731. var options = {
  20732. width: width,
  20733. height: height,
  20734. subdivisions: subdivisions,
  20735. minHeight: minHeight,
  20736. maxHeight: maxHeight,
  20737. updatable: updatable,
  20738. onReady: onReady
  20739. };
  20740. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  20741. };
  20742. /**
  20743. * Creates a tube mesh.
  20744. * 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.
  20745. * Please consider using the same method from the MeshBuilder class instead.
  20746. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  20747. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  20748. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  20749. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  20750. * 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.
  20751. * It must return a radius value (positive float) :
  20752. * ```javascript
  20753. * var radiusFunction = function(i, distance) {
  20754. * // do things
  20755. * return radius; }
  20756. * ```
  20757. * 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
  20758. * 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
  20759. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20760. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20761. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20762. */
  20763. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  20764. var options = {
  20765. path: path,
  20766. radius: radius,
  20767. tessellation: tessellation,
  20768. radiusFunction: radiusFunction,
  20769. arc: 1,
  20770. cap: cap,
  20771. updatable: updatable,
  20772. sideOrientation: sideOrientation,
  20773. instance: instance
  20774. };
  20775. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  20776. };
  20777. /**
  20778. * Creates a polyhedron mesh.
  20779. * Please consider using the same method from the MeshBuilder class instead.
  20780. * 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
  20781. * to choose the wanted type.
  20782. * The parameter `size` (positive float, default 1) sets the polygon size.
  20783. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  20784. * 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`.
  20785. * 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
  20786. * 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)`).
  20787. * 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
  20788. * 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.
  20789. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20790. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20791. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20792. */
  20793. Mesh.CreatePolyhedron = function (name, options, scene) {
  20794. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  20795. };
  20796. /**
  20797. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  20798. * Please consider using the same method from the MeshBuilder class instead.
  20799. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  20800. * 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`).
  20801. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  20802. * 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.
  20803. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20804. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20805. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20806. */
  20807. Mesh.CreateIcoSphere = function (name, options, scene) {
  20808. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  20809. };
  20810. /**
  20811. * Creates a decal mesh.
  20812. * Please consider using the same method from the MeshBuilder class instead.
  20813. * 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.
  20814. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  20815. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  20816. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  20817. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  20818. */
  20819. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  20820. var options = {
  20821. position: position,
  20822. normal: normal,
  20823. size: size,
  20824. angle: angle
  20825. };
  20826. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  20827. };
  20828. // Skeletons
  20829. /**
  20830. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  20831. */
  20832. Mesh.prototype.setPositionsForCPUSkinning = function () {
  20833. var source;
  20834. if (!this._sourcePositions) {
  20835. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20836. this._sourcePositions = new Float32Array(source);
  20837. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  20838. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  20839. }
  20840. }
  20841. return this._sourcePositions;
  20842. };
  20843. /**
  20844. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  20845. */
  20846. Mesh.prototype.setNormalsForCPUSkinning = function () {
  20847. var source;
  20848. if (!this._sourceNormals) {
  20849. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20850. this._sourceNormals = new Float32Array(source);
  20851. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  20852. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  20853. }
  20854. }
  20855. return this._sourceNormals;
  20856. };
  20857. /**
  20858. * Updates the vertex buffer by applying transformation from the bones.
  20859. * Returns the Mesh.
  20860. *
  20861. * @param {skeleton} skeleton to apply
  20862. */
  20863. Mesh.prototype.applySkeleton = function (skeleton) {
  20864. if (!this.geometry) {
  20865. return this;
  20866. }
  20867. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  20868. return this;
  20869. }
  20870. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  20871. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  20872. return this;
  20873. }
  20874. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20875. return this;
  20876. }
  20877. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  20878. return this;
  20879. }
  20880. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  20881. return this;
  20882. }
  20883. if (!this._sourcePositions) {
  20884. var submeshes = this.subMeshes.slice();
  20885. this.setPositionsForCPUSkinning();
  20886. this.subMeshes = submeshes;
  20887. }
  20888. if (!this._sourceNormals) {
  20889. this.setNormalsForCPUSkinning();
  20890. }
  20891. // positionsData checks for not being Float32Array will only pass at most once
  20892. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20893. if (!(positionsData instanceof Float32Array)) {
  20894. positionsData = new Float32Array(positionsData);
  20895. }
  20896. // normalsData checks for not being Float32Array will only pass at most once
  20897. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20898. if (!(normalsData instanceof Float32Array)) {
  20899. normalsData = new Float32Array(normalsData);
  20900. }
  20901. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  20902. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  20903. var needExtras = this.numBoneInfluencers > 4;
  20904. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  20905. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  20906. var skeletonMatrices = skeleton.getTransformMatrices(this);
  20907. var tempVector3 = BABYLON.Vector3.Zero();
  20908. var finalMatrix = new BABYLON.Matrix();
  20909. var tempMatrix = new BABYLON.Matrix();
  20910. var matWeightIdx = 0;
  20911. var inf;
  20912. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  20913. var weight;
  20914. for (inf = 0; inf < 4; inf++) {
  20915. weight = matricesWeightsData[matWeightIdx + inf];
  20916. if (weight > 0) {
  20917. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  20918. finalMatrix.addToSelf(tempMatrix);
  20919. }
  20920. else
  20921. break;
  20922. }
  20923. if (needExtras) {
  20924. for (inf = 0; inf < 4; inf++) {
  20925. weight = matricesWeightsExtraData[matWeightIdx + inf];
  20926. if (weight > 0) {
  20927. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  20928. finalMatrix.addToSelf(tempMatrix);
  20929. }
  20930. else
  20931. break;
  20932. }
  20933. }
  20934. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  20935. tempVector3.toArray(positionsData, index);
  20936. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  20937. tempVector3.toArray(normalsData, index);
  20938. finalMatrix.reset();
  20939. }
  20940. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  20941. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  20942. return this;
  20943. };
  20944. // Tools
  20945. /**
  20946. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  20947. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  20948. */
  20949. Mesh.MinMax = function (meshes) {
  20950. var minVector = null;
  20951. var maxVector = null;
  20952. meshes.forEach(function (mesh, index, array) {
  20953. var boundingBox = mesh.getBoundingInfo().boundingBox;
  20954. if (!minVector) {
  20955. minVector = boundingBox.minimumWorld;
  20956. maxVector = boundingBox.maximumWorld;
  20957. }
  20958. else {
  20959. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  20960. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  20961. }
  20962. });
  20963. return {
  20964. min: minVector,
  20965. max: maxVector
  20966. };
  20967. };
  20968. /**
  20969. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  20970. */
  20971. Mesh.Center = function (meshesOrMinMaxVector) {
  20972. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  20973. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  20974. };
  20975. /**
  20976. * Merge the array of meshes into a single mesh for performance reasons.
  20977. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  20978. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  20979. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  20980. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  20981. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  20982. */
  20983. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  20984. if (disposeSource === void 0) { disposeSource = true; }
  20985. var index;
  20986. if (!allow32BitsIndices) {
  20987. var totalVertices = 0;
  20988. // Counting vertices
  20989. for (index = 0; index < meshes.length; index++) {
  20990. if (meshes[index]) {
  20991. totalVertices += meshes[index].getTotalVertices();
  20992. if (totalVertices > 65536) {
  20993. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  20994. return null;
  20995. }
  20996. }
  20997. }
  20998. }
  20999. // Merge
  21000. var vertexData;
  21001. var otherVertexData;
  21002. var indiceArray = new Array();
  21003. var source;
  21004. for (index = 0; index < meshes.length; index++) {
  21005. if (meshes[index]) {
  21006. meshes[index].computeWorldMatrix(true);
  21007. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  21008. otherVertexData.transform(meshes[index].getWorldMatrix());
  21009. if (vertexData) {
  21010. vertexData.merge(otherVertexData);
  21011. }
  21012. else {
  21013. vertexData = otherVertexData;
  21014. source = meshes[index];
  21015. }
  21016. if (subdivideWithSubMeshes) {
  21017. indiceArray.push(meshes[index].getTotalIndices());
  21018. }
  21019. }
  21020. }
  21021. if (!meshSubclass) {
  21022. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  21023. }
  21024. vertexData.applyToMesh(meshSubclass);
  21025. // Setting properties
  21026. meshSubclass.material = source.material;
  21027. meshSubclass.checkCollisions = source.checkCollisions;
  21028. // Cleaning
  21029. if (disposeSource) {
  21030. for (index = 0; index < meshes.length; index++) {
  21031. if (meshes[index]) {
  21032. meshes[index].dispose();
  21033. }
  21034. }
  21035. }
  21036. // Subdivide
  21037. if (subdivideWithSubMeshes) {
  21038. //-- Suppresions du submesh global
  21039. meshSubclass.releaseSubMeshes();
  21040. index = 0;
  21041. var offset = 0;
  21042. //-- aplique la subdivision en fonction du tableau d'indices
  21043. while (index < indiceArray.length) {
  21044. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  21045. offset += indiceArray[index];
  21046. index++;
  21047. }
  21048. }
  21049. return meshSubclass;
  21050. };
  21051. return Mesh;
  21052. }(BABYLON.AbstractMesh));
  21053. // Consts
  21054. Mesh._FRONTSIDE = 0;
  21055. Mesh._BACKSIDE = 1;
  21056. Mesh._DOUBLESIDE = 2;
  21057. Mesh._DEFAULTSIDE = 0;
  21058. Mesh._NO_CAP = 0;
  21059. Mesh._CAP_START = 1;
  21060. Mesh._CAP_END = 2;
  21061. Mesh._CAP_ALL = 3;
  21062. BABYLON.Mesh = Mesh;
  21063. })(BABYLON || (BABYLON = {}));
  21064. //# sourceMappingURL=babylon.mesh.js.map
  21065. var BABYLON;
  21066. (function (BABYLON) {
  21067. var SubMesh = (function () {
  21068. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  21069. if (createBoundingBox === void 0) { createBoundingBox = true; }
  21070. this.materialIndex = materialIndex;
  21071. this.verticesStart = verticesStart;
  21072. this.verticesCount = verticesCount;
  21073. this.indexStart = indexStart;
  21074. this.indexCount = indexCount;
  21075. this._renderId = 0;
  21076. this._mesh = mesh;
  21077. this._renderingMesh = renderingMesh || mesh;
  21078. mesh.subMeshes.push(this);
  21079. this._trianglePlanes = [];
  21080. this._id = mesh.subMeshes.length - 1;
  21081. if (createBoundingBox) {
  21082. this.refreshBoundingInfo();
  21083. mesh.computeWorldMatrix(true);
  21084. }
  21085. }
  21086. Object.defineProperty(SubMesh.prototype, "effect", {
  21087. get: function () {
  21088. return this._materialEffect;
  21089. },
  21090. enumerable: true,
  21091. configurable: true
  21092. });
  21093. SubMesh.prototype.setEffect = function (effect, defines) {
  21094. if (this._materialEffect === effect) {
  21095. return;
  21096. }
  21097. this._materialDefines = defines;
  21098. this._materialEffect = effect;
  21099. };
  21100. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  21101. get: function () {
  21102. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  21103. },
  21104. enumerable: true,
  21105. configurable: true
  21106. });
  21107. /**
  21108. * Returns the submesh BoudingInfo object.
  21109. */
  21110. SubMesh.prototype.getBoundingInfo = function () {
  21111. if (this.IsGlobal) {
  21112. return this._mesh.getBoundingInfo();
  21113. }
  21114. return this._boundingInfo;
  21115. };
  21116. /**
  21117. * Sets the submesh BoundingInfo.
  21118. * Return the SubMesh.
  21119. */
  21120. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  21121. this._boundingInfo = boundingInfo;
  21122. return this;
  21123. };
  21124. /**
  21125. * Returns the mesh of the current submesh.
  21126. */
  21127. SubMesh.prototype.getMesh = function () {
  21128. return this._mesh;
  21129. };
  21130. /**
  21131. * Returns the rendering mesh of the submesh.
  21132. */
  21133. SubMesh.prototype.getRenderingMesh = function () {
  21134. return this._renderingMesh;
  21135. };
  21136. /**
  21137. * Returns the submesh material.
  21138. */
  21139. SubMesh.prototype.getMaterial = function () {
  21140. var rootMaterial = this._renderingMesh.material;
  21141. if (rootMaterial && rootMaterial.getSubMaterial) {
  21142. var multiMaterial = rootMaterial;
  21143. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  21144. if (this._currentMaterial !== effectiveMaterial) {
  21145. this._currentMaterial = effectiveMaterial;
  21146. if (this._materialDefines) {
  21147. this._materialDefines.markAllAsDirty();
  21148. }
  21149. }
  21150. return effectiveMaterial;
  21151. }
  21152. if (!rootMaterial) {
  21153. return this._mesh.getScene().defaultMaterial;
  21154. }
  21155. return rootMaterial;
  21156. };
  21157. // Methods
  21158. /**
  21159. * Sets a new updated BoundingInfo object to the submesh.
  21160. * Returns the SubMesh.
  21161. */
  21162. SubMesh.prototype.refreshBoundingInfo = function () {
  21163. this._lastColliderWorldVertices = null;
  21164. if (this.IsGlobal) {
  21165. return;
  21166. }
  21167. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21168. if (!data) {
  21169. this._boundingInfo = this._mesh._boundingInfo;
  21170. return;
  21171. }
  21172. var indices = this._renderingMesh.getIndices();
  21173. var extend;
  21174. //is this the only submesh?
  21175. if (this.indexStart === 0 && this.indexCount === indices.length) {
  21176. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  21177. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  21178. }
  21179. else {
  21180. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  21181. }
  21182. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  21183. return this;
  21184. };
  21185. SubMesh.prototype._checkCollision = function (collider) {
  21186. return this.getBoundingInfo()._checkCollision(collider);
  21187. };
  21188. /**
  21189. * Updates the submesh BoundingInfo.
  21190. * Returns the Submesh.
  21191. */
  21192. SubMesh.prototype.updateBoundingInfo = function (world) {
  21193. if (!this.getBoundingInfo()) {
  21194. this.refreshBoundingInfo();
  21195. }
  21196. this.getBoundingInfo().update(world);
  21197. return this;
  21198. };
  21199. /**
  21200. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  21201. * Boolean returned.
  21202. */
  21203. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  21204. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  21205. };
  21206. /**
  21207. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  21208. * Boolean returned.
  21209. */
  21210. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  21211. return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes);
  21212. };
  21213. /**
  21214. * Renders the submesh.
  21215. * Returns it.
  21216. */
  21217. SubMesh.prototype.render = function (enableAlphaMode) {
  21218. this._renderingMesh.render(this, enableAlphaMode);
  21219. return this;
  21220. };
  21221. /**
  21222. * Returns a new Index Buffer.
  21223. * Type returned : WebGLBuffer.
  21224. */
  21225. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  21226. if (!this._linesIndexBuffer) {
  21227. var linesIndices = [];
  21228. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  21229. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  21230. }
  21231. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  21232. this.linesIndexCount = linesIndices.length;
  21233. }
  21234. return this._linesIndexBuffer;
  21235. };
  21236. /**
  21237. * True is the passed Ray intersects the submesh bounding box.
  21238. * Boolean returned.
  21239. */
  21240. SubMesh.prototype.canIntersects = function (ray) {
  21241. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  21242. };
  21243. /**
  21244. * Returns an object IntersectionInfo.
  21245. */
  21246. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  21247. var intersectInfo = null;
  21248. // LineMesh first as it's also a Mesh...
  21249. if (this._mesh instanceof BABYLON.LinesMesh) {
  21250. var lineMesh = this._mesh;
  21251. // Line test
  21252. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  21253. var p0 = positions[indices[index]];
  21254. var p1 = positions[indices[index + 1]];
  21255. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  21256. if (length < 0) {
  21257. continue;
  21258. }
  21259. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  21260. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  21261. if (fastCheck) {
  21262. break;
  21263. }
  21264. }
  21265. }
  21266. }
  21267. else {
  21268. // Triangles test
  21269. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  21270. var p0 = positions[indices[index]];
  21271. var p1 = positions[indices[index + 1]];
  21272. var p2 = positions[indices[index + 2]];
  21273. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  21274. if (currentIntersectInfo) {
  21275. if (currentIntersectInfo.distance < 0) {
  21276. continue;
  21277. }
  21278. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  21279. intersectInfo = currentIntersectInfo;
  21280. intersectInfo.faceId = index / 3;
  21281. if (fastCheck) {
  21282. break;
  21283. }
  21284. }
  21285. }
  21286. }
  21287. }
  21288. return intersectInfo;
  21289. };
  21290. // Clone
  21291. /**
  21292. * Creates a new Submesh from the passed Mesh.
  21293. */
  21294. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  21295. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  21296. if (!this.IsGlobal) {
  21297. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  21298. }
  21299. return result;
  21300. };
  21301. // Dispose
  21302. /**
  21303. * Disposes the Submesh.
  21304. * Returns nothing.
  21305. */
  21306. SubMesh.prototype.dispose = function () {
  21307. if (this._linesIndexBuffer) {
  21308. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  21309. this._linesIndexBuffer = null;
  21310. }
  21311. // Remove from mesh
  21312. var index = this._mesh.subMeshes.indexOf(this);
  21313. this._mesh.subMeshes.splice(index, 1);
  21314. };
  21315. // Statics
  21316. /**
  21317. * Creates a new Submesh from the passed parameters :
  21318. * - materialIndex (integer) : the index of the main mesh material.
  21319. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  21320. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  21321. * - mesh (Mesh) : the main mesh to create the submesh from.
  21322. * - renderingMesh (optional Mesh) : rendering mesh.
  21323. */
  21324. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  21325. var minVertexIndex = Number.MAX_VALUE;
  21326. var maxVertexIndex = -Number.MAX_VALUE;
  21327. renderingMesh = renderingMesh || mesh;
  21328. var indices = renderingMesh.getIndices();
  21329. for (var index = startIndex; index < startIndex + indexCount; index++) {
  21330. var vertexIndex = indices[index];
  21331. if (vertexIndex < minVertexIndex)
  21332. minVertexIndex = vertexIndex;
  21333. if (vertexIndex > maxVertexIndex)
  21334. maxVertexIndex = vertexIndex;
  21335. }
  21336. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  21337. };
  21338. return SubMesh;
  21339. }());
  21340. BABYLON.SubMesh = SubMesh;
  21341. })(BABYLON || (BABYLON = {}));
  21342. //# sourceMappingURL=babylon.subMesh.js.map
  21343. var BABYLON;
  21344. (function (BABYLON) {
  21345. var EffectFallbacks = (function () {
  21346. function EffectFallbacks() {
  21347. this._defines = {};
  21348. this._currentRank = 32;
  21349. this._maxRank = -1;
  21350. }
  21351. EffectFallbacks.prototype.addFallback = function (rank, define) {
  21352. if (!this._defines[rank]) {
  21353. if (rank < this._currentRank) {
  21354. this._currentRank = rank;
  21355. }
  21356. if (rank > this._maxRank) {
  21357. this._maxRank = rank;
  21358. }
  21359. this._defines[rank] = new Array();
  21360. }
  21361. this._defines[rank].push(define);
  21362. };
  21363. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  21364. this._meshRank = rank;
  21365. this._mesh = mesh;
  21366. if (rank < this._currentRank) {
  21367. this._currentRank = rank;
  21368. }
  21369. if (rank > this._maxRank) {
  21370. this._maxRank = rank;
  21371. }
  21372. };
  21373. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  21374. get: function () {
  21375. return this._currentRank <= this._maxRank;
  21376. },
  21377. enumerable: true,
  21378. configurable: true
  21379. });
  21380. EffectFallbacks.prototype.reduce = function (currentDefines) {
  21381. // First we try to switch to CPU skinning
  21382. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  21383. this._mesh.computeBonesUsingShaders = false;
  21384. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  21385. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  21386. var scene = this._mesh.getScene();
  21387. for (var index = 0; index < scene.meshes.length; index++) {
  21388. var otherMesh = scene.meshes[index];
  21389. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  21390. otherMesh.computeBonesUsingShaders = false;
  21391. }
  21392. }
  21393. }
  21394. else {
  21395. var currentFallbacks = this._defines[this._currentRank];
  21396. if (currentFallbacks) {
  21397. for (var index = 0; index < currentFallbacks.length; index++) {
  21398. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  21399. }
  21400. }
  21401. this._currentRank++;
  21402. }
  21403. return currentDefines;
  21404. };
  21405. return EffectFallbacks;
  21406. }());
  21407. BABYLON.EffectFallbacks = EffectFallbacks;
  21408. var EffectCreationOptions = (function () {
  21409. function EffectCreationOptions() {
  21410. }
  21411. return EffectCreationOptions;
  21412. }());
  21413. BABYLON.EffectCreationOptions = EffectCreationOptions;
  21414. var Effect = (function () {
  21415. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  21416. var _this = this;
  21417. this.uniqueId = 0;
  21418. this._uniformBuffersNames = {};
  21419. this._isReady = false;
  21420. this._compilationError = "";
  21421. this._valueCache = {};
  21422. this.name = baseName;
  21423. if (attributesNamesOrOptions.attributes) {
  21424. var options = attributesNamesOrOptions;
  21425. this._engine = uniformsNamesOrEngine;
  21426. this._attributesNames = options.attributes;
  21427. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  21428. this._samplers = options.samplers;
  21429. this.defines = options.defines;
  21430. this.onError = options.onError;
  21431. this.onCompiled = options.onCompiled;
  21432. this._fallbacks = options.fallbacks;
  21433. this._indexParameters = options.indexParameters;
  21434. if (options.uniformBuffersNames) {
  21435. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  21436. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  21437. }
  21438. }
  21439. }
  21440. else {
  21441. this._engine = engine;
  21442. this.defines = defines;
  21443. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  21444. this._samplers = samplers;
  21445. this._attributesNames = attributesNamesOrOptions;
  21446. this.onError = onError;
  21447. this.onCompiled = onCompiled;
  21448. this._indexParameters = indexParameters;
  21449. this._fallbacks = fallbacks;
  21450. }
  21451. this.uniqueId = Effect._uniqueIdSeed++;
  21452. var vertexSource;
  21453. var fragmentSource;
  21454. if (baseName.vertexElement) {
  21455. vertexSource = document.getElementById(baseName.vertexElement);
  21456. if (!vertexSource) {
  21457. vertexSource = baseName.vertexElement;
  21458. }
  21459. }
  21460. else {
  21461. vertexSource = baseName.vertex || baseName;
  21462. }
  21463. if (baseName.fragmentElement) {
  21464. fragmentSource = document.getElementById(baseName.fragmentElement);
  21465. if (!fragmentSource) {
  21466. fragmentSource = baseName.fragmentElement;
  21467. }
  21468. }
  21469. else {
  21470. fragmentSource = baseName.fragment || baseName;
  21471. }
  21472. this._loadVertexShader(vertexSource, function (vertexCode) {
  21473. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  21474. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  21475. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  21476. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  21477. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  21478. _this._prepareEffect(migratedVertexCode, migratedFragmentCode, _this._attributesNames, _this.defines, _this._fallbacks);
  21479. });
  21480. });
  21481. });
  21482. });
  21483. });
  21484. });
  21485. }
  21486. Object.defineProperty(Effect.prototype, "key", {
  21487. get: function () {
  21488. return this._key;
  21489. },
  21490. enumerable: true,
  21491. configurable: true
  21492. });
  21493. // Properties
  21494. Effect.prototype.isReady = function () {
  21495. return this._isReady;
  21496. };
  21497. Effect.prototype.getProgram = function () {
  21498. return this._program;
  21499. };
  21500. Effect.prototype.getAttributesNames = function () {
  21501. return this._attributesNames;
  21502. };
  21503. Effect.prototype.getAttributeLocation = function (index) {
  21504. return this._attributes[index];
  21505. };
  21506. Effect.prototype.getAttributeLocationByName = function (name) {
  21507. var index = this._attributesNames.indexOf(name);
  21508. return this._attributes[index];
  21509. };
  21510. Effect.prototype.getAttributesCount = function () {
  21511. return this._attributes.length;
  21512. };
  21513. Effect.prototype.getUniformIndex = function (uniformName) {
  21514. return this._uniformsNames.indexOf(uniformName);
  21515. };
  21516. Effect.prototype.getUniform = function (uniformName) {
  21517. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  21518. };
  21519. Effect.prototype.getSamplers = function () {
  21520. return this._samplers;
  21521. };
  21522. Effect.prototype.getCompilationError = function () {
  21523. return this._compilationError;
  21524. };
  21525. Effect.prototype.getVertexShaderSource = function () {
  21526. return this._evaluateDefinesOnString(this._engine.getVertexShaderSource(this._program));
  21527. };
  21528. Effect.prototype.getFragmentShaderSource = function () {
  21529. return this._evaluateDefinesOnString(this._engine.getFragmentShaderSource(this._program));
  21530. };
  21531. // Methods
  21532. Effect.prototype._loadVertexShader = function (vertex, callback) {
  21533. // DOM element ?
  21534. if (vertex instanceof HTMLElement) {
  21535. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  21536. callback(vertexCode);
  21537. return;
  21538. }
  21539. // Base64 encoded ?
  21540. if (vertex.substr(0, 7) === "base64:") {
  21541. var vertexBinary = window.atob(vertex.substr(7));
  21542. callback(vertexBinary);
  21543. return;
  21544. }
  21545. // Is in local store ?
  21546. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  21547. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  21548. return;
  21549. }
  21550. var vertexShaderUrl;
  21551. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  21552. vertexShaderUrl = vertex;
  21553. }
  21554. else {
  21555. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  21556. }
  21557. // Vertex shader
  21558. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  21559. };
  21560. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  21561. // DOM element ?
  21562. if (fragment instanceof HTMLElement) {
  21563. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  21564. callback(fragmentCode);
  21565. return;
  21566. }
  21567. // Base64 encoded ?
  21568. if (fragment.substr(0, 7) === "base64:") {
  21569. var fragmentBinary = window.atob(fragment.substr(7));
  21570. callback(fragmentBinary);
  21571. return;
  21572. }
  21573. // Is in local store ?
  21574. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  21575. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  21576. return;
  21577. }
  21578. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  21579. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  21580. return;
  21581. }
  21582. var fragmentShaderUrl;
  21583. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  21584. fragmentShaderUrl = fragment;
  21585. }
  21586. else {
  21587. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  21588. }
  21589. // Fragment shader
  21590. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  21591. };
  21592. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  21593. // Rebuild shaders source code
  21594. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  21595. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  21596. vertexCode = prefix + vertexCode;
  21597. fragmentCode = prefix + fragmentCode;
  21598. // Number lines of shaders source code
  21599. var i = 2;
  21600. var regex = /\n/gm;
  21601. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  21602. i = 2;
  21603. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  21604. // Dump shaders name and formatted source code
  21605. if (this.name.vertexElement) {
  21606. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  21607. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  21608. }
  21609. else if (this.name.vertex) {
  21610. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  21611. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  21612. }
  21613. else {
  21614. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  21615. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  21616. }
  21617. };
  21618. ;
  21619. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  21620. var preparedSourceCode = this._processPrecision(sourceCode);
  21621. if (this._engine.webGLVersion == 1) {
  21622. callback(preparedSourceCode);
  21623. return;
  21624. }
  21625. // Already converted
  21626. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  21627. callback(preparedSourceCode);
  21628. return;
  21629. }
  21630. // Remove extensions
  21631. // #extension GL_OES_standard_derivatives : enable
  21632. // #extension GL_EXT_shader_texture_lod : enable
  21633. // #extension GL_EXT_frag_depth : enable
  21634. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth).+enable/g;
  21635. var result = preparedSourceCode.replace(regex, "");
  21636. // Migrate to GLSL v300
  21637. result = result.replace(/varying\s/g, isFragment ? "in " : "out ");
  21638. result = result.replace(/attribute[ \t]/g, "in ");
  21639. result = result.replace(/[ \t]attribute/g, " in");
  21640. if (isFragment) {
  21641. result = result.replace(/texture2DLodEXT\(/g, "textureLod(");
  21642. result = result.replace(/textureCubeLodEXT\(/g, "textureLod(");
  21643. result = result.replace(/texture2D\(/g, "texture(");
  21644. result = result.replace(/textureCube\(/g, "texture(");
  21645. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  21646. result = result.replace(/gl_FragColor/g, "glFragColor");
  21647. result = result.replace(/void\s+?main\(/g, "out vec4 glFragColor;\nvoid main(");
  21648. }
  21649. callback(result);
  21650. };
  21651. Effect.prototype._processIncludes = function (sourceCode, callback) {
  21652. var _this = this;
  21653. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  21654. var match = regex.exec(sourceCode);
  21655. var returnValue = new String(sourceCode);
  21656. while (match != null) {
  21657. var includeFile = match[1];
  21658. // Uniform declaration
  21659. if (includeFile.indexOf("__decl__") !== -1) {
  21660. includeFile = includeFile.replace(/__decl__/, "");
  21661. if (this._engine.webGLVersion != 1) {
  21662. includeFile = includeFile.replace(/Vertex/, "Ubo");
  21663. includeFile = includeFile.replace(/Fragment/, "Ubo");
  21664. }
  21665. includeFile = includeFile + "Declaration";
  21666. }
  21667. if (Effect.IncludesShadersStore[includeFile]) {
  21668. // Substitution
  21669. var includeContent = Effect.IncludesShadersStore[includeFile];
  21670. if (match[2]) {
  21671. var splits = match[3].split(",");
  21672. for (var index = 0; index < splits.length; index += 2) {
  21673. var source = new RegExp(splits[index], "g");
  21674. var dest = splits[index + 1];
  21675. includeContent = includeContent.replace(source, dest);
  21676. }
  21677. }
  21678. if (match[4]) {
  21679. var indexString = match[5];
  21680. if (indexString.indexOf("..") !== -1) {
  21681. var indexSplits = indexString.split("..");
  21682. var minIndex = parseInt(indexSplits[0]);
  21683. var maxIndex = parseInt(indexSplits[1]);
  21684. var sourceIncludeContent = includeContent.slice(0);
  21685. includeContent = "";
  21686. if (isNaN(maxIndex)) {
  21687. maxIndex = this._indexParameters[indexSplits[1]];
  21688. }
  21689. for (var i = minIndex; i < maxIndex; i++) {
  21690. if (this._engine.webGLVersion === 1) {
  21691. // Ubo replacement
  21692. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  21693. return p1 + "{X}";
  21694. });
  21695. }
  21696. includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
  21697. }
  21698. }
  21699. else {
  21700. if (this._engine.webGLVersion === 1) {
  21701. // Ubo replacement
  21702. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  21703. return p1 + "{X}";
  21704. });
  21705. }
  21706. includeContent = includeContent.replace(/\{X\}/g, indexString);
  21707. }
  21708. }
  21709. // Replace
  21710. returnValue = returnValue.replace(match[0], includeContent);
  21711. }
  21712. else {
  21713. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  21714. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  21715. Effect.IncludesShadersStore[includeFile] = fileContent;
  21716. _this._processIncludes(returnValue, callback);
  21717. });
  21718. return;
  21719. }
  21720. match = regex.exec(sourceCode);
  21721. }
  21722. callback(returnValue);
  21723. };
  21724. Effect.prototype._processPrecision = function (source) {
  21725. if (source.indexOf("precision highp float") === -1) {
  21726. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  21727. source = "precision mediump float;\n" + source;
  21728. }
  21729. else {
  21730. source = "precision highp float;\n" + source;
  21731. }
  21732. }
  21733. else {
  21734. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  21735. source = source.replace("precision highp float", "precision mediump float");
  21736. }
  21737. }
  21738. return source;
  21739. };
  21740. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  21741. try {
  21742. var engine = this._engine;
  21743. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  21744. if (engine.webGLVersion > 1) {
  21745. for (var name in this._uniformBuffersNames) {
  21746. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  21747. }
  21748. }
  21749. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  21750. this._attributes = engine.getAttributes(this._program, attributesNames);
  21751. var index;
  21752. for (index = 0; index < this._samplers.length; index++) {
  21753. var sampler = this.getUniform(this._samplers[index]);
  21754. if (sampler == null) {
  21755. this._samplers.splice(index, 1);
  21756. index--;
  21757. }
  21758. }
  21759. engine.bindSamplers(this);
  21760. this._compilationError = "";
  21761. this._isReady = true;
  21762. if (this.onCompiled) {
  21763. this.onCompiled(this);
  21764. }
  21765. }
  21766. catch (e) {
  21767. this._compilationError = e.message;
  21768. // Let's go through fallbacks then
  21769. BABYLON.Tools.Error("Unable to compile effect:");
  21770. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  21771. return " " + uniform;
  21772. }));
  21773. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  21774. return " " + attribute;
  21775. }));
  21776. this._dumpShadersSource(vertexSourceCode, fragmentSourceCode, defines);
  21777. BABYLON.Tools.Error("Error: " + this._compilationError);
  21778. if (fallbacks && fallbacks.isMoreFallbacks) {
  21779. BABYLON.Tools.Error("Trying next fallback.");
  21780. defines = fallbacks.reduce(defines);
  21781. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  21782. }
  21783. else {
  21784. if (this.onError) {
  21785. this.onError(this, this._compilationError);
  21786. }
  21787. }
  21788. }
  21789. };
  21790. Object.defineProperty(Effect.prototype, "isSupported", {
  21791. get: function () {
  21792. return this._compilationError === "";
  21793. },
  21794. enumerable: true,
  21795. configurable: true
  21796. });
  21797. Effect.prototype._bindTexture = function (channel, texture) {
  21798. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  21799. };
  21800. Effect.prototype.setTexture = function (channel, texture) {
  21801. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  21802. };
  21803. Effect.prototype.setTextureArray = function (channel, textures) {
  21804. if (this._samplers.indexOf(channel + "Ex") === -1) {
  21805. var initialPos = this._samplers.indexOf(channel);
  21806. for (var index = 1; index < textures.length; index++) {
  21807. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  21808. }
  21809. }
  21810. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  21811. };
  21812. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  21813. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  21814. };
  21815. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  21816. var cache = this._valueCache[uniformName];
  21817. var flag = matrix.updateFlag;
  21818. if (cache !== undefined && cache === flag) {
  21819. return false;
  21820. }
  21821. this._valueCache[uniformName] = flag;
  21822. return true;
  21823. };
  21824. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  21825. var cache = this._valueCache[uniformName];
  21826. if (!cache) {
  21827. cache = [x, y];
  21828. this._valueCache[uniformName] = cache;
  21829. return true;
  21830. }
  21831. var changed = false;
  21832. if (cache[0] !== x) {
  21833. cache[0] = x;
  21834. changed = true;
  21835. }
  21836. if (cache[1] !== y) {
  21837. cache[1] = y;
  21838. changed = true;
  21839. }
  21840. return changed;
  21841. };
  21842. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  21843. var cache = this._valueCache[uniformName];
  21844. if (!cache) {
  21845. cache = [x, y, z];
  21846. this._valueCache[uniformName] = cache;
  21847. return true;
  21848. }
  21849. var changed = false;
  21850. if (cache[0] !== x) {
  21851. cache[0] = x;
  21852. changed = true;
  21853. }
  21854. if (cache[1] !== y) {
  21855. cache[1] = y;
  21856. changed = true;
  21857. }
  21858. if (cache[2] !== z) {
  21859. cache[2] = z;
  21860. changed = true;
  21861. }
  21862. return changed;
  21863. };
  21864. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  21865. var cache = this._valueCache[uniformName];
  21866. if (!cache) {
  21867. cache = [x, y, z, w];
  21868. this._valueCache[uniformName] = cache;
  21869. return true;
  21870. }
  21871. var changed = false;
  21872. if (cache[0] !== x) {
  21873. cache[0] = x;
  21874. changed = true;
  21875. }
  21876. if (cache[1] !== y) {
  21877. cache[1] = y;
  21878. changed = true;
  21879. }
  21880. if (cache[2] !== z) {
  21881. cache[2] = z;
  21882. changed = true;
  21883. }
  21884. if (cache[3] !== w) {
  21885. cache[3] = w;
  21886. changed = true;
  21887. }
  21888. return changed;
  21889. };
  21890. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  21891. if (Effect._baseCache[this._uniformBuffersNames[name]] === buffer) {
  21892. return;
  21893. }
  21894. Effect._baseCache[this._uniformBuffersNames[name]] = buffer;
  21895. this._engine.bindUniformBufferBase(buffer, this._uniformBuffersNames[name]);
  21896. };
  21897. Effect.prototype.bindUniformBlock = function (blockName, index) {
  21898. this._engine.bindUniformBlock(this._program, blockName, index);
  21899. };
  21900. Effect.prototype.setIntArray = function (uniformName, array) {
  21901. this._valueCache[uniformName] = null;
  21902. this._engine.setIntArray(this.getUniform(uniformName), array);
  21903. return this;
  21904. };
  21905. Effect.prototype.setIntArray2 = function (uniformName, array) {
  21906. this._valueCache[uniformName] = null;
  21907. this._engine.setIntArray2(this.getUniform(uniformName), array);
  21908. return this;
  21909. };
  21910. Effect.prototype.setIntArray3 = function (uniformName, array) {
  21911. this._valueCache[uniformName] = null;
  21912. this._engine.setIntArray3(this.getUniform(uniformName), array);
  21913. return this;
  21914. };
  21915. Effect.prototype.setIntArray4 = function (uniformName, array) {
  21916. this._valueCache[uniformName] = null;
  21917. this._engine.setIntArray4(this.getUniform(uniformName), array);
  21918. return this;
  21919. };
  21920. Effect.prototype.setFloatArray = function (uniformName, array) {
  21921. this._valueCache[uniformName] = null;
  21922. this._engine.setFloatArray(this.getUniform(uniformName), array);
  21923. return this;
  21924. };
  21925. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  21926. this._valueCache[uniformName] = null;
  21927. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  21928. return this;
  21929. };
  21930. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  21931. this._valueCache[uniformName] = null;
  21932. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  21933. return this;
  21934. };
  21935. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  21936. this._valueCache[uniformName] = null;
  21937. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  21938. return this;
  21939. };
  21940. Effect.prototype.setArray = function (uniformName, array) {
  21941. this._valueCache[uniformName] = null;
  21942. this._engine.setArray(this.getUniform(uniformName), array);
  21943. return this;
  21944. };
  21945. Effect.prototype.setArray2 = function (uniformName, array) {
  21946. this._valueCache[uniformName] = null;
  21947. this._engine.setArray2(this.getUniform(uniformName), array);
  21948. return this;
  21949. };
  21950. Effect.prototype.setArray3 = function (uniformName, array) {
  21951. this._valueCache[uniformName] = null;
  21952. this._engine.setArray3(this.getUniform(uniformName), array);
  21953. return this;
  21954. };
  21955. Effect.prototype.setArray4 = function (uniformName, array) {
  21956. this._valueCache[uniformName] = null;
  21957. this._engine.setArray4(this.getUniform(uniformName), array);
  21958. return this;
  21959. };
  21960. Effect.prototype.setMatrices = function (uniformName, matrices) {
  21961. if (!matrices) {
  21962. return;
  21963. }
  21964. this._valueCache[uniformName] = null;
  21965. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  21966. return this;
  21967. };
  21968. Effect.prototype.setMatrix = function (uniformName, matrix) {
  21969. if (this._cacheMatrix(uniformName, matrix)) {
  21970. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  21971. }
  21972. return this;
  21973. };
  21974. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  21975. this._valueCache[uniformName] = null;
  21976. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  21977. return this;
  21978. };
  21979. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  21980. this._valueCache[uniformName] = null;
  21981. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  21982. return this;
  21983. };
  21984. Effect.prototype.setFloat = function (uniformName, value) {
  21985. var cache = this._valueCache[uniformName];
  21986. if (cache !== undefined && cache === value)
  21987. return this;
  21988. this._valueCache[uniformName] = value;
  21989. this._engine.setFloat(this.getUniform(uniformName), value);
  21990. return this;
  21991. };
  21992. Effect.prototype.setBool = function (uniformName, bool) {
  21993. var cache = this._valueCache[uniformName];
  21994. if (cache !== undefined && cache === bool)
  21995. return this;
  21996. this._valueCache[uniformName] = bool;
  21997. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  21998. return this;
  21999. };
  22000. Effect.prototype.setVector2 = function (uniformName, vector2) {
  22001. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  22002. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  22003. }
  22004. return this;
  22005. };
  22006. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  22007. if (this._cacheFloat2(uniformName, x, y)) {
  22008. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  22009. }
  22010. return this;
  22011. };
  22012. Effect.prototype.setVector3 = function (uniformName, vector3) {
  22013. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  22014. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  22015. }
  22016. return this;
  22017. };
  22018. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  22019. if (this._cacheFloat3(uniformName, x, y, z)) {
  22020. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  22021. }
  22022. return this;
  22023. };
  22024. Effect.prototype.setVector4 = function (uniformName, vector4) {
  22025. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  22026. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  22027. }
  22028. return this;
  22029. };
  22030. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  22031. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  22032. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  22033. }
  22034. return this;
  22035. };
  22036. Effect.prototype.setColor3 = function (uniformName, color3) {
  22037. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  22038. this._engine.setColor3(this.getUniform(uniformName), color3);
  22039. }
  22040. return this;
  22041. };
  22042. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  22043. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  22044. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  22045. }
  22046. return this;
  22047. };
  22048. Effect.prototype._recombineShader = function (node) {
  22049. if (node.define) {
  22050. if (node.condition) {
  22051. var defineIndex = this.defines.indexOf("#define " + node.define);
  22052. if (defineIndex === -1) {
  22053. return null;
  22054. }
  22055. var nextComma = this.defines.indexOf("\n", defineIndex);
  22056. var defineValue = this.defines.substr(defineIndex + 7, nextComma - defineIndex - 7).replace(node.define, "").trim();
  22057. var condition = defineValue + node.condition;
  22058. if (!eval(condition)) {
  22059. return null;
  22060. }
  22061. }
  22062. else if (node.ndef) {
  22063. if (this.defines.indexOf("#define " + node.define) !== -1) {
  22064. return null;
  22065. }
  22066. }
  22067. else if (this.defines.indexOf("#define " + node.define) === -1) {
  22068. return null;
  22069. }
  22070. }
  22071. var result = "";
  22072. for (var index = 0; index < node.children.length; index++) {
  22073. var line = node.children[index];
  22074. if (line.children) {
  22075. var combined = this._recombineShader(line);
  22076. if (combined !== null) {
  22077. result += combined + "\r\n";
  22078. }
  22079. continue;
  22080. }
  22081. if (line.length > 0) {
  22082. result += line + "\r\n";
  22083. }
  22084. }
  22085. return result;
  22086. };
  22087. Effect.prototype._evaluateDefinesOnString = function (shaderString) {
  22088. var root = {
  22089. children: []
  22090. };
  22091. var currentNode = root;
  22092. var lines = shaderString.split("\n");
  22093. for (var index = 0; index < lines.length; index++) {
  22094. var line = lines[index].trim();
  22095. // #ifdef
  22096. var pos = line.indexOf("#ifdef ");
  22097. if (pos !== -1) {
  22098. var define = line.substr(pos + 7);
  22099. var newNode = {
  22100. condition: null,
  22101. ndef: false,
  22102. define: define,
  22103. children: [],
  22104. parent: currentNode
  22105. };
  22106. currentNode.children.push(newNode);
  22107. currentNode = newNode;
  22108. continue;
  22109. }
  22110. // #ifndef
  22111. var pos = line.indexOf("#ifndef ");
  22112. if (pos !== -1) {
  22113. var define = line.substr(pos + 8);
  22114. newNode = {
  22115. condition: null,
  22116. define: define,
  22117. ndef: true,
  22118. children: [],
  22119. parent: currentNode
  22120. };
  22121. currentNode.children.push(newNode);
  22122. currentNode = newNode;
  22123. continue;
  22124. }
  22125. // #if
  22126. var pos = line.indexOf("#if ");
  22127. if (pos !== -1) {
  22128. var define = line.substr(pos + 4).trim();
  22129. var conditionPos = define.indexOf(" ");
  22130. newNode = {
  22131. condition: define.substr(conditionPos + 1),
  22132. define: define.substr(0, conditionPos),
  22133. ndef: false,
  22134. children: [],
  22135. parent: currentNode
  22136. };
  22137. currentNode.children.push(newNode);
  22138. currentNode = newNode;
  22139. continue;
  22140. }
  22141. // #endif
  22142. pos = line.indexOf("#endif");
  22143. if (pos !== -1) {
  22144. currentNode = currentNode.parent;
  22145. continue;
  22146. }
  22147. currentNode.children.push(line);
  22148. }
  22149. // Recombine
  22150. return this._recombineShader(root);
  22151. };
  22152. return Effect;
  22153. }());
  22154. Effect._uniqueIdSeed = 0;
  22155. Effect._baseCache = {};
  22156. // Statics
  22157. Effect.ShadersStore = {};
  22158. Effect.IncludesShadersStore = {};
  22159. BABYLON.Effect = Effect;
  22160. })(BABYLON || (BABYLON = {}));
  22161. //# sourceMappingURL=babylon.effect.js.map
  22162. var BABYLON;
  22163. (function (BABYLON) {
  22164. var MaterialHelper = (function () {
  22165. function MaterialHelper() {
  22166. }
  22167. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, defines) {
  22168. if (defines._areMiscDirty) {
  22169. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  22170. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  22171. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  22172. }
  22173. };
  22174. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances) {
  22175. var changed = false;
  22176. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  22177. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  22178. changed = true;
  22179. }
  22180. if (defines["ALPHATEST"] !== engine.getAlphaTesting()) {
  22181. defines["ALPHATEST"] = !defines["ALPHATEST"];
  22182. changed = true;
  22183. }
  22184. if (defines["INSTANCES"] !== useInstances) {
  22185. defines["INSTANCES"] = useInstances;
  22186. changed = true;
  22187. }
  22188. if (changed) {
  22189. defines.markAsUnprocessed();
  22190. }
  22191. };
  22192. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets) {
  22193. if (useMorphTargets === void 0) { useMorphTargets = false; }
  22194. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  22195. return;
  22196. }
  22197. defines._normals = defines._needNormals;
  22198. defines._uvs = defines._needUVs;
  22199. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  22200. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  22201. defines["TANGENT"] = true;
  22202. }
  22203. if (defines._needUVs) {
  22204. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  22205. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  22206. }
  22207. else {
  22208. defines["UV1"] = false;
  22209. defines["UV2"] = false;
  22210. }
  22211. if (useVertexColor) {
  22212. defines["VERTEXCOLOR"] = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  22213. defines["VERTEXALPHA"] = mesh.hasVertexAlpha;
  22214. }
  22215. if (useBones) {
  22216. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  22217. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  22218. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  22219. }
  22220. else {
  22221. defines["NUM_BONE_INFLUENCERS"] = 0;
  22222. defines["BonesPerMesh"] = 0;
  22223. }
  22224. }
  22225. if (useMorphTargets) {
  22226. if (mesh.morphTargetManager) {
  22227. var manager = mesh.morphTargetManager;
  22228. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  22229. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  22230. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  22231. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  22232. }
  22233. else {
  22234. defines["MORPHTARGETS_TANGENT"] = false;
  22235. defines["MORPHTARGETS_NORMAL"] = false;
  22236. defines["MORPHTARGETS"] = false;
  22237. defines["NUM_MORPH_INFLUENCERS"] = 0;
  22238. }
  22239. }
  22240. };
  22241. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  22242. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  22243. if (disableLighting === void 0) { disableLighting = false; }
  22244. if (!defines._areLightsDirty) {
  22245. return defines._needNormals;
  22246. }
  22247. var lightIndex = 0;
  22248. var needNormals = false;
  22249. var needRebuild = false;
  22250. var lightmapMode = false;
  22251. var shadowEnabled = false;
  22252. var specularEnabled = false;
  22253. if (scene.lightsEnabled && !disableLighting) {
  22254. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  22255. var light = _a[_i];
  22256. needNormals = true;
  22257. if (defines["LIGHT" + lightIndex] === undefined) {
  22258. needRebuild = true;
  22259. }
  22260. defines["LIGHT" + lightIndex] = true;
  22261. defines["SPOTLIGHT" + lightIndex] = false;
  22262. defines["HEMILIGHT" + lightIndex] = false;
  22263. defines["POINTLIGHT" + lightIndex] = false;
  22264. defines["DIRLIGHT" + lightIndex] = false;
  22265. var type;
  22266. if (light.getTypeID() === 2) {
  22267. type = "SPOTLIGHT" + lightIndex;
  22268. }
  22269. else if (light.getTypeID() === 3) {
  22270. type = "HEMILIGHT" + lightIndex;
  22271. }
  22272. else if (light.getTypeID() === 0) {
  22273. type = "POINTLIGHT" + lightIndex;
  22274. }
  22275. else {
  22276. type = "DIRLIGHT" + lightIndex;
  22277. }
  22278. defines[type] = true;
  22279. // Specular
  22280. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  22281. specularEnabled = true;
  22282. }
  22283. // Shadows
  22284. defines["SHADOW" + lightIndex] = false;
  22285. if (scene.shadowsEnabled) {
  22286. var shadowGenerator = light.getShadowGenerator();
  22287. if (mesh && mesh.receiveShadows && shadowGenerator) {
  22288. defines["SHADOW" + lightIndex] = true;
  22289. shadowEnabled = true;
  22290. defines["SHADOWPCF" + lightIndex] = false;
  22291. defines["SHADOWESM" + lightIndex] = false;
  22292. if (shadowGenerator.usePoissonSampling) {
  22293. defines["SHADOWPCF" + lightIndex] = true;
  22294. }
  22295. else if (shadowGenerator.useExponentialShadowMap || shadowGenerator.useBlurExponentialShadowMap) {
  22296. defines["SHADOWESM" + lightIndex] = true;
  22297. }
  22298. }
  22299. }
  22300. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  22301. lightmapMode = true;
  22302. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  22303. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  22304. }
  22305. else {
  22306. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  22307. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  22308. }
  22309. lightIndex++;
  22310. if (lightIndex === maxSimultaneousLights)
  22311. break;
  22312. }
  22313. }
  22314. defines["SPECULARTERM"] = specularEnabled;
  22315. defines["SHADOWS"] = shadowEnabled;
  22316. // Resetting all other lights if any
  22317. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  22318. if (defines["LIGHT" + index] !== undefined) {
  22319. defines["LIGHT" + index] = false;
  22320. }
  22321. }
  22322. var caps = scene.getEngine().getCaps();
  22323. if (defines["SHADOWFULLFLOAT"] === undefined) {
  22324. needRebuild = true;
  22325. }
  22326. defines["SHADOWFULLFLOAT"] = (shadowEnabled && caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender);
  22327. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  22328. if (needRebuild) {
  22329. defines.rebuild();
  22330. }
  22331. return needNormals;
  22332. };
  22333. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  22334. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  22335. var uniformsList, uniformBuffersList, samplersList, defines;
  22336. if (uniformsListOrOptions.uniformsNames) {
  22337. var options = uniformsListOrOptions;
  22338. uniformsList = options.uniformsNames;
  22339. uniformBuffersList = options.uniformBuffersNames;
  22340. samplersList = options.samplers;
  22341. defines = options.defines;
  22342. maxSimultaneousLights = options.maxSimultaneousLights;
  22343. }
  22344. else {
  22345. uniformsList = uniformsListOrOptions;
  22346. }
  22347. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  22348. if (!defines["LIGHT" + lightIndex]) {
  22349. break;
  22350. }
  22351. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex);
  22352. if (uniformBuffersList) {
  22353. uniformBuffersList.push("Light" + lightIndex);
  22354. }
  22355. samplersList.push("shadowSampler" + lightIndex);
  22356. }
  22357. if (defines["NUM_MORPH_INFLUENCERS"]) {
  22358. uniformsList.push("morphTargetInfluences");
  22359. }
  22360. };
  22361. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  22362. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  22363. if (!defines["SHADOWS"]) {
  22364. return;
  22365. }
  22366. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  22367. if (!defines["LIGHT" + lightIndex]) {
  22368. break;
  22369. }
  22370. if (lightIndex > 0) {
  22371. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  22372. }
  22373. if (defines["SHADOW" + lightIndex]) {
  22374. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  22375. }
  22376. if (defines["SHADOWPCF" + lightIndex]) {
  22377. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  22378. }
  22379. if (defines["SHADOWESM" + lightIndex]) {
  22380. fallbacks.addFallback(0, "SHADOWESM" + lightIndex);
  22381. }
  22382. }
  22383. };
  22384. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  22385. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  22386. if (influencers > 0) {
  22387. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  22388. var manager = mesh.morphTargetManager;
  22389. var normal = manager.supportsNormals && defines["NORMAL"];
  22390. var tangent = manager.supportsTangents && defines["TANGENT"];
  22391. for (var index = 0; index < influencers; index++) {
  22392. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  22393. if (normal) {
  22394. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  22395. }
  22396. if (tangent) {
  22397. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  22398. }
  22399. if (attribs.length > maxAttributesCount) {
  22400. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  22401. }
  22402. }
  22403. }
  22404. };
  22405. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  22406. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  22407. fallbacks.addCPUSkinningFallback(0, mesh);
  22408. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  22409. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  22410. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  22411. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  22412. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  22413. }
  22414. }
  22415. };
  22416. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  22417. if (defines["INSTANCES"]) {
  22418. attribs.push("world0");
  22419. attribs.push("world1");
  22420. attribs.push("world2");
  22421. attribs.push("world3");
  22422. }
  22423. };
  22424. // Bindings
  22425. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect, depthValuesAlreadySet) {
  22426. var shadowGenerator = light.getShadowGenerator();
  22427. if (mesh.receiveShadows && shadowGenerator) {
  22428. if (!light.needCube()) {
  22429. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  22430. }
  22431. else {
  22432. if (!depthValuesAlreadySet) {
  22433. depthValuesAlreadySet = true;
  22434. effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  22435. }
  22436. }
  22437. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  22438. light._uniformBuffer.updateFloat3("shadowsInfo", shadowGenerator.getDarkness(), shadowGenerator.blurScale / shadowGenerator.getShadowMap().getSize().width, shadowGenerator.depthScale, lightIndex);
  22439. }
  22440. return depthValuesAlreadySet;
  22441. };
  22442. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  22443. light.transferToEffect(effect, lightIndex + "");
  22444. };
  22445. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights) {
  22446. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  22447. var lightIndex = 0;
  22448. var depthValuesAlreadySet = false;
  22449. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  22450. var light = _a[_i];
  22451. light._uniformBuffer.bindToEffect(effect, "Light" + lightIndex);
  22452. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  22453. light.diffuse.scaleToRef(light.intensity, BABYLON.Tmp.Color3[0]);
  22454. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], light.range, lightIndex + "");
  22455. if (defines["SPECULARTERM"]) {
  22456. light.specular.scaleToRef(light.intensity, BABYLON.Tmp.Color3[1]);
  22457. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], lightIndex + "");
  22458. }
  22459. // Shadows
  22460. if (scene.shadowsEnabled) {
  22461. depthValuesAlreadySet = this.BindLightShadow(light, scene, mesh, lightIndex + "", effect, depthValuesAlreadySet);
  22462. }
  22463. light._uniformBuffer.update();
  22464. lightIndex++;
  22465. if (lightIndex === maxSimultaneousLights)
  22466. break;
  22467. }
  22468. };
  22469. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  22470. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  22471. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  22472. effect.setColor3("vFogColor", scene.fogColor);
  22473. }
  22474. };
  22475. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  22476. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  22477. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  22478. if (matrices) {
  22479. effect.setMatrices("mBones", matrices);
  22480. }
  22481. }
  22482. };
  22483. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  22484. if (!abstractMesh || !abstractMesh.morphTargetManager) {
  22485. return;
  22486. }
  22487. effect.setFloatArray("morphTargetInfluences", abstractMesh.morphTargetManager.influences);
  22488. };
  22489. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  22490. if (defines["LOGARITHMICDEPTH"]) {
  22491. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  22492. }
  22493. };
  22494. MaterialHelper.BindClipPlane = function (effect, scene) {
  22495. if (scene.clipPlane) {
  22496. var clipPlane = scene.clipPlane;
  22497. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  22498. }
  22499. };
  22500. return MaterialHelper;
  22501. }());
  22502. BABYLON.MaterialHelper = MaterialHelper;
  22503. })(BABYLON || (BABYLON = {}));
  22504. //# sourceMappingURL=babylon.materialHelper.js.map
  22505. var BABYLON;
  22506. (function (BABYLON) {
  22507. var MaterialDefines = (function () {
  22508. function MaterialDefines() {
  22509. this._isDirty = true;
  22510. this._areLightsDirty = true;
  22511. this._areAttributesDirty = true;
  22512. this._areTexturesDirty = true;
  22513. this._areFresnelDirty = true;
  22514. this._areMiscDirty = true;
  22515. this._normals = false;
  22516. this._uvs = false;
  22517. this._needNormals = false;
  22518. this._needUVs = false;
  22519. }
  22520. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  22521. get: function () {
  22522. return this._isDirty;
  22523. },
  22524. enumerable: true,
  22525. configurable: true
  22526. });
  22527. MaterialDefines.prototype.markAsProcessed = function () {
  22528. this._isDirty = false;
  22529. this._areAttributesDirty = false;
  22530. this._areTexturesDirty = false;
  22531. this._areFresnelDirty = false;
  22532. this._areLightsDirty = false;
  22533. this._areMiscDirty = false;
  22534. };
  22535. MaterialDefines.prototype.markAsUnprocessed = function () {
  22536. this._isDirty = true;
  22537. };
  22538. MaterialDefines.prototype.markAllAsDirty = function () {
  22539. this._areTexturesDirty = true;
  22540. this._areAttributesDirty = true;
  22541. this._areLightsDirty = true;
  22542. this._areFresnelDirty = true;
  22543. this._areMiscDirty = true;
  22544. this._isDirty = true;
  22545. };
  22546. MaterialDefines.prototype.markAsLightDirty = function () {
  22547. this._areLightsDirty = true;
  22548. this._isDirty = true;
  22549. };
  22550. MaterialDefines.prototype.markAsAttributesDirty = function () {
  22551. this._areAttributesDirty = true;
  22552. this._isDirty = true;
  22553. };
  22554. MaterialDefines.prototype.markAsTexturesDirty = function () {
  22555. this._areTexturesDirty = true;
  22556. this._isDirty = true;
  22557. };
  22558. MaterialDefines.prototype.markAsFresnelDirty = function () {
  22559. this._areFresnelDirty = true;
  22560. this._isDirty = true;
  22561. };
  22562. MaterialDefines.prototype.markAsMiscDirty = function () {
  22563. this._areMiscDirty = true;
  22564. this._isDirty = true;
  22565. };
  22566. MaterialDefines.prototype.rebuild = function () {
  22567. if (this._keys) {
  22568. delete this._keys;
  22569. }
  22570. this._keys = [];
  22571. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  22572. var key = _a[_i];
  22573. if (key[0] === "_") {
  22574. continue;
  22575. }
  22576. this._keys.push(key);
  22577. }
  22578. };
  22579. MaterialDefines.prototype.isEqual = function (other) {
  22580. if (this._keys.length !== other._keys.length) {
  22581. return false;
  22582. }
  22583. for (var index = 0; index < this._keys.length; index++) {
  22584. var prop = this._keys[index];
  22585. if (this[prop] !== other[prop]) {
  22586. return false;
  22587. }
  22588. }
  22589. return true;
  22590. };
  22591. MaterialDefines.prototype.cloneTo = function (other) {
  22592. if (this._keys.length !== other._keys.length) {
  22593. other._keys = this._keys.slice(0);
  22594. }
  22595. for (var index = 0; index < this._keys.length; index++) {
  22596. var prop = this._keys[index];
  22597. other[prop] = this[prop];
  22598. }
  22599. };
  22600. MaterialDefines.prototype.reset = function () {
  22601. for (var index = 0; index < this._keys.length; index++) {
  22602. var prop = this._keys[index];
  22603. if (typeof (this[prop]) === "number") {
  22604. this[prop] = 0;
  22605. }
  22606. else {
  22607. this[prop] = false;
  22608. }
  22609. }
  22610. };
  22611. MaterialDefines.prototype.toString = function () {
  22612. var result = "";
  22613. for (var index = 0; index < this._keys.length; index++) {
  22614. var prop = this._keys[index];
  22615. var value = this[prop];
  22616. if (typeof (value) === "number") {
  22617. result += "#define " + prop + " " + this[prop] + "\n";
  22618. }
  22619. else if (value) {
  22620. result += "#define " + prop + "\n";
  22621. }
  22622. }
  22623. return result;
  22624. };
  22625. return MaterialDefines;
  22626. }());
  22627. BABYLON.MaterialDefines = MaterialDefines;
  22628. var Material = (function () {
  22629. function Material(name, scene, doNotAdd) {
  22630. this.checkReadyOnEveryCall = false;
  22631. this.checkReadyOnlyOnce = false;
  22632. this.state = "";
  22633. this.alpha = 1.0;
  22634. this._backFaceCulling = true;
  22635. this.doNotSerialize = false;
  22636. this.storeEffectOnSubMeshes = false;
  22637. /**
  22638. * An event triggered when the material is disposed.
  22639. * @type {BABYLON.Observable}
  22640. */
  22641. this.onDisposeObservable = new BABYLON.Observable();
  22642. /**
  22643. * An event triggered when the material is bound.
  22644. * @type {BABYLON.Observable}
  22645. */
  22646. this.onBindObservable = new BABYLON.Observable();
  22647. /**
  22648. * An event triggered when the material is unbound.
  22649. * @type {BABYLON.Observable}
  22650. */
  22651. this.onUnBindObservable = new BABYLON.Observable();
  22652. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  22653. this.disableDepthWrite = false;
  22654. this._fogEnabled = true;
  22655. this.pointSize = 1.0;
  22656. this.zOffset = 0;
  22657. this._wasPreviouslyReady = false;
  22658. this._fillMode = Material.TriangleFillMode;
  22659. this.name = name;
  22660. this.id = name;
  22661. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  22662. if (this._scene.useRightHandedSystem) {
  22663. this.sideOrientation = Material.ClockWiseSideOrientation;
  22664. }
  22665. else {
  22666. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  22667. }
  22668. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  22669. this._useUBO = this.getScene().getEngine().webGLVersion > 1;
  22670. if (!doNotAdd) {
  22671. this._scene.materials.push(this);
  22672. }
  22673. }
  22674. Object.defineProperty(Material, "TriangleFillMode", {
  22675. get: function () {
  22676. return Material._TriangleFillMode;
  22677. },
  22678. enumerable: true,
  22679. configurable: true
  22680. });
  22681. Object.defineProperty(Material, "WireFrameFillMode", {
  22682. get: function () {
  22683. return Material._WireFrameFillMode;
  22684. },
  22685. enumerable: true,
  22686. configurable: true
  22687. });
  22688. Object.defineProperty(Material, "PointFillMode", {
  22689. get: function () {
  22690. return Material._PointFillMode;
  22691. },
  22692. enumerable: true,
  22693. configurable: true
  22694. });
  22695. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  22696. get: function () {
  22697. return Material._ClockWiseSideOrientation;
  22698. },
  22699. enumerable: true,
  22700. configurable: true
  22701. });
  22702. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  22703. get: function () {
  22704. return Material._CounterClockWiseSideOrientation;
  22705. },
  22706. enumerable: true,
  22707. configurable: true
  22708. });
  22709. Object.defineProperty(Material, "TextureDirtyFlag", {
  22710. get: function () {
  22711. return Material._TextureDirtyFlag;
  22712. },
  22713. enumerable: true,
  22714. configurable: true
  22715. });
  22716. Object.defineProperty(Material, "LightDirtyFlag", {
  22717. get: function () {
  22718. return Material._LightDirtyFlag;
  22719. },
  22720. enumerable: true,
  22721. configurable: true
  22722. });
  22723. Object.defineProperty(Material, "FresnelDirtyFlag", {
  22724. get: function () {
  22725. return Material._FresnelDirtyFlag;
  22726. },
  22727. enumerable: true,
  22728. configurable: true
  22729. });
  22730. Object.defineProperty(Material, "AttributesDirtyFlag", {
  22731. get: function () {
  22732. return Material._AttributesDirtyFlag;
  22733. },
  22734. enumerable: true,
  22735. configurable: true
  22736. });
  22737. Object.defineProperty(Material, "MiscDirtyFlag", {
  22738. get: function () {
  22739. return Material._MiscDirtyFlag;
  22740. },
  22741. enumerable: true,
  22742. configurable: true
  22743. });
  22744. Object.defineProperty(Material.prototype, "backFaceCulling", {
  22745. get: function () {
  22746. return this._backFaceCulling;
  22747. },
  22748. set: function (value) {
  22749. if (this._backFaceCulling === value) {
  22750. return;
  22751. }
  22752. this._backFaceCulling = value;
  22753. this.markAsDirty(Material.TextureDirtyFlag);
  22754. },
  22755. enumerable: true,
  22756. configurable: true
  22757. });
  22758. Object.defineProperty(Material.prototype, "onDispose", {
  22759. set: function (callback) {
  22760. if (this._onDisposeObserver) {
  22761. this.onDisposeObservable.remove(this._onDisposeObserver);
  22762. }
  22763. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  22764. },
  22765. enumerable: true,
  22766. configurable: true
  22767. });
  22768. Object.defineProperty(Material.prototype, "onBind", {
  22769. set: function (callback) {
  22770. if (this._onBindObserver) {
  22771. this.onBindObservable.remove(this._onBindObserver);
  22772. }
  22773. this._onBindObserver = this.onBindObservable.add(callback);
  22774. },
  22775. enumerable: true,
  22776. configurable: true
  22777. });
  22778. Object.defineProperty(Material.prototype, "fogEnabled", {
  22779. get: function () {
  22780. return this._fogEnabled;
  22781. },
  22782. set: function (value) {
  22783. if (this._fogEnabled === value) {
  22784. return;
  22785. }
  22786. this._fogEnabled = value;
  22787. this.markAsDirty(Material.MiscDirtyFlag);
  22788. },
  22789. enumerable: true,
  22790. configurable: true
  22791. });
  22792. Object.defineProperty(Material.prototype, "wireframe", {
  22793. get: function () {
  22794. return this._fillMode === Material.WireFrameFillMode;
  22795. },
  22796. set: function (value) {
  22797. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  22798. },
  22799. enumerable: true,
  22800. configurable: true
  22801. });
  22802. Object.defineProperty(Material.prototype, "pointsCloud", {
  22803. get: function () {
  22804. return this._fillMode === Material.PointFillMode;
  22805. },
  22806. set: function (value) {
  22807. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  22808. },
  22809. enumerable: true,
  22810. configurable: true
  22811. });
  22812. Object.defineProperty(Material.prototype, "fillMode", {
  22813. get: function () {
  22814. return this._fillMode;
  22815. },
  22816. set: function (value) {
  22817. if (this._fillMode === value) {
  22818. return;
  22819. }
  22820. this._fillMode = value;
  22821. this.markAsDirty(Material.MiscDirtyFlag);
  22822. },
  22823. enumerable: true,
  22824. configurable: true
  22825. });
  22826. /**
  22827. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22828. * subclasses should override adding information pertainent to themselves
  22829. */
  22830. Material.prototype.toString = function (fullDetails) {
  22831. var ret = "Name: " + this.name;
  22832. if (fullDetails) {
  22833. }
  22834. return ret;
  22835. };
  22836. /**
  22837. * Child classes can use it to update shaders
  22838. */
  22839. Material.prototype.markAsDirty = function (flag) {
  22840. };
  22841. Material.prototype.getClassName = function () {
  22842. return "Material";
  22843. };
  22844. Object.defineProperty(Material.prototype, "isFrozen", {
  22845. get: function () {
  22846. return this.checkReadyOnlyOnce;
  22847. },
  22848. enumerable: true,
  22849. configurable: true
  22850. });
  22851. Material.prototype.freeze = function () {
  22852. this.checkReadyOnlyOnce = true;
  22853. };
  22854. Material.prototype.unfreeze = function () {
  22855. this.checkReadyOnlyOnce = false;
  22856. };
  22857. Material.prototype.isReady = function (mesh, useInstances) {
  22858. return true;
  22859. };
  22860. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  22861. return false;
  22862. };
  22863. Material.prototype.getEffect = function () {
  22864. return this._effect;
  22865. };
  22866. Material.prototype.getScene = function () {
  22867. return this._scene;
  22868. };
  22869. Material.prototype.needAlphaBlending = function () {
  22870. return (this.alpha < 1.0);
  22871. };
  22872. Material.prototype.needAlphaTesting = function () {
  22873. return false;
  22874. };
  22875. Material.prototype.getAlphaTestTexture = function () {
  22876. return null;
  22877. };
  22878. Material.prototype.markDirty = function () {
  22879. this._wasPreviouslyReady = false;
  22880. };
  22881. Material.prototype._preBind = function (effect) {
  22882. var engine = this._scene.getEngine();
  22883. var reverse = this.sideOrientation === Material.ClockWiseSideOrientation;
  22884. engine.enableEffect(effect ? effect : this._effect);
  22885. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  22886. };
  22887. Material.prototype.bind = function (world, mesh) {
  22888. };
  22889. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  22890. };
  22891. Material.prototype.bindOnlyWorldMatrix = function (world) {
  22892. };
  22893. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  22894. sceneUbo.bindToEffect(effect, "Scene");
  22895. };
  22896. Material.prototype.bindView = function (effect) {
  22897. if (!this._useUBO) {
  22898. effect.setMatrix("view", this.getScene().getViewMatrix());
  22899. }
  22900. else {
  22901. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  22902. }
  22903. };
  22904. Material.prototype.bindViewProjection = function (effect) {
  22905. if (!this._useUBO) {
  22906. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  22907. }
  22908. else {
  22909. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  22910. }
  22911. };
  22912. Material.prototype._afterBind = function (mesh) {
  22913. this._scene._cachedMaterial = this;
  22914. this.onBindObservable.notifyObservers(mesh);
  22915. if (this.disableDepthWrite) {
  22916. var engine = this._scene.getEngine();
  22917. this._cachedDepthWriteState = engine.getDepthWrite();
  22918. engine.setDepthWrite(false);
  22919. }
  22920. };
  22921. Material.prototype.unbind = function () {
  22922. this.onUnBindObservable.notifyObservers(this);
  22923. if (this.disableDepthWrite) {
  22924. var engine = this._scene.getEngine();
  22925. engine.setDepthWrite(this._cachedDepthWriteState);
  22926. }
  22927. };
  22928. Material.prototype.clone = function (name) {
  22929. return null;
  22930. };
  22931. Material.prototype.getBindedMeshes = function () {
  22932. var result = new Array();
  22933. for (var index = 0; index < this._scene.meshes.length; index++) {
  22934. var mesh = this._scene.meshes[index];
  22935. if (mesh.material === this) {
  22936. result.push(mesh);
  22937. }
  22938. }
  22939. return result;
  22940. };
  22941. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  22942. // Animations
  22943. this.getScene().stopAnimation(this);
  22944. // Remove from scene
  22945. var index = this._scene.materials.indexOf(this);
  22946. if (index >= 0) {
  22947. this._scene.materials.splice(index, 1);
  22948. }
  22949. // Remove from meshes
  22950. for (index = 0; index < this._scene.meshes.length; index++) {
  22951. var mesh = this._scene.meshes[index];
  22952. if (mesh.material === this) {
  22953. mesh.material = null;
  22954. if (mesh.geometry) {
  22955. var geometry = mesh.geometry;
  22956. if (this.storeEffectOnSubMeshes) {
  22957. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  22958. var subMesh = _a[_i];
  22959. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  22960. }
  22961. }
  22962. else {
  22963. geometry._releaseVertexArrayObject(this._effect);
  22964. }
  22965. }
  22966. }
  22967. }
  22968. this._uniformBuffer.dispose();
  22969. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  22970. if (forceDisposeEffect && this._effect) {
  22971. if (this.storeEffectOnSubMeshes) {
  22972. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  22973. var subMesh = _c[_b];
  22974. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  22975. }
  22976. }
  22977. else {
  22978. this._scene.getEngine()._releaseEffect(this._effect);
  22979. }
  22980. this._effect = null;
  22981. }
  22982. // Callback
  22983. this.onDisposeObservable.notifyObservers(this);
  22984. this.onDisposeObservable.clear();
  22985. this.onBindObservable.clear();
  22986. this.onUnBindObservable.clear();
  22987. };
  22988. Material.prototype.serialize = function () {
  22989. return BABYLON.SerializationHelper.Serialize(this);
  22990. };
  22991. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  22992. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  22993. multiMaterial.id = parsedMultiMaterial.id;
  22994. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  22995. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  22996. var subMatId = parsedMultiMaterial.materials[matIndex];
  22997. if (subMatId) {
  22998. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  22999. }
  23000. else {
  23001. multiMaterial.subMaterials.push(null);
  23002. }
  23003. }
  23004. return multiMaterial;
  23005. };
  23006. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  23007. if (!parsedMaterial.customType) {
  23008. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  23009. }
  23010. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  23011. return materialType.Parse(parsedMaterial, scene, rootUrl);
  23012. ;
  23013. };
  23014. return Material;
  23015. }());
  23016. Material._TriangleFillMode = 0;
  23017. Material._WireFrameFillMode = 1;
  23018. Material._PointFillMode = 2;
  23019. Material._ClockWiseSideOrientation = 0;
  23020. Material._CounterClockWiseSideOrientation = 1;
  23021. Material._TextureDirtyFlag = 0;
  23022. Material._LightDirtyFlag = 1;
  23023. Material._FresnelDirtyFlag = 2;
  23024. Material._AttributesDirtyFlag = 4;
  23025. Material._MiscDirtyFlag = 8;
  23026. __decorate([
  23027. BABYLON.serialize()
  23028. ], Material.prototype, "id", void 0);
  23029. __decorate([
  23030. BABYLON.serialize()
  23031. ], Material.prototype, "name", void 0);
  23032. __decorate([
  23033. BABYLON.serialize()
  23034. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  23035. __decorate([
  23036. BABYLON.serialize()
  23037. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  23038. __decorate([
  23039. BABYLON.serialize()
  23040. ], Material.prototype, "state", void 0);
  23041. __decorate([
  23042. BABYLON.serialize()
  23043. ], Material.prototype, "alpha", void 0);
  23044. __decorate([
  23045. BABYLON.serialize("backFaceCulling")
  23046. ], Material.prototype, "_backFaceCulling", void 0);
  23047. __decorate([
  23048. BABYLON.serialize()
  23049. ], Material.prototype, "sideOrientation", void 0);
  23050. __decorate([
  23051. BABYLON.serialize()
  23052. ], Material.prototype, "alphaMode", void 0);
  23053. __decorate([
  23054. BABYLON.serialize()
  23055. ], Material.prototype, "disableDepthWrite", void 0);
  23056. __decorate([
  23057. BABYLON.serialize("fogEnabled")
  23058. ], Material.prototype, "_fogEnabled", void 0);
  23059. __decorate([
  23060. BABYLON.serialize()
  23061. ], Material.prototype, "pointSize", void 0);
  23062. __decorate([
  23063. BABYLON.serialize()
  23064. ], Material.prototype, "zOffset", void 0);
  23065. __decorate([
  23066. BABYLON.serialize()
  23067. ], Material.prototype, "wireframe", null);
  23068. __decorate([
  23069. BABYLON.serialize()
  23070. ], Material.prototype, "pointsCloud", null);
  23071. __decorate([
  23072. BABYLON.serialize()
  23073. ], Material.prototype, "fillMode", null);
  23074. BABYLON.Material = Material;
  23075. })(BABYLON || (BABYLON = {}));
  23076. //# sourceMappingURL=babylon.material.js.map
  23077. var BABYLON;
  23078. (function (BABYLON) {
  23079. var UniformBuffer = (function () {
  23080. /**
  23081. * Uniform buffer objects.
  23082. *
  23083. * Handles blocks of uniform on the GPU.
  23084. *
  23085. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  23086. *
  23087. * For more information, please refer to :
  23088. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  23089. */
  23090. function UniformBuffer(engine, data, dynamic) {
  23091. this._engine = engine;
  23092. this._noUBO = engine.webGLVersion === 1;
  23093. this._dynamic = dynamic;
  23094. this._data = data || [];
  23095. this._uniformLocations = {};
  23096. this._uniformSizes = {};
  23097. this._uniformLocationPointer = 0;
  23098. this._needSync = false;
  23099. if (this._noUBO) {
  23100. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  23101. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  23102. this.updateFloat = this._updateFloatForEffect;
  23103. this.updateFloat2 = this._updateFloat2ForEffect;
  23104. this.updateFloat3 = this._updateFloat3ForEffect;
  23105. this.updateFloat4 = this._updateFloat4ForEffect;
  23106. this.updateMatrix = this._updateMatrixForEffect;
  23107. this.updateVector3 = this._updateVector3ForEffect;
  23108. this.updateVector4 = this._updateVector4ForEffect;
  23109. this.updateColor3 = this._updateColor3ForEffect;
  23110. this.updateColor4 = this._updateColor4ForEffect;
  23111. }
  23112. else {
  23113. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  23114. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  23115. this.updateFloat = this._updateFloatForUniform;
  23116. this.updateFloat2 = this._updateFloat2ForUniform;
  23117. this.updateFloat3 = this._updateFloat3ForUniform;
  23118. this.updateFloat4 = this._updateFloat4ForUniform;
  23119. this.updateMatrix = this._updateMatrixForUniform;
  23120. this.updateVector3 = this._updateVector3ForUniform;
  23121. this.updateVector4 = this._updateVector4ForUniform;
  23122. this.updateColor3 = this._updateColor3ForUniform;
  23123. this.updateColor4 = this._updateColor4ForUniform;
  23124. }
  23125. }
  23126. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  23127. // Properties
  23128. /**
  23129. * Indicates if the buffer is using the WebGL2 UBO implementation,
  23130. * or just falling back on setUniformXXX calls.
  23131. */
  23132. get: function () {
  23133. return !this._noUBO;
  23134. },
  23135. enumerable: true,
  23136. configurable: true
  23137. });
  23138. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  23139. /**
  23140. * Indicates if the WebGL underlying uniform buffer is in sync
  23141. * with the javascript cache data.
  23142. */
  23143. get: function () {
  23144. return !this._needSync;
  23145. },
  23146. enumerable: true,
  23147. configurable: true
  23148. });
  23149. /**
  23150. * Indicates if the WebGL underlying uniform buffer is dynamic.
  23151. * Also, a dynamic UniformBuffer will disable cache verification and always
  23152. * update the underlying WebGL uniform buffer to the GPU.
  23153. */
  23154. UniformBuffer.prototype.isDynamic = function () {
  23155. return this._dynamic;
  23156. };
  23157. /**
  23158. * The data cache on JS side.
  23159. */
  23160. UniformBuffer.prototype.getData = function () {
  23161. return this._bufferData;
  23162. };
  23163. /**
  23164. * The underlying WebGL Uniform buffer.
  23165. */
  23166. UniformBuffer.prototype.getBuffer = function () {
  23167. return this._buffer;
  23168. };
  23169. /**
  23170. * std140 layout specifies how to align data within an UBO structure.
  23171. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  23172. * for specs.
  23173. */
  23174. UniformBuffer.prototype._fillAlignment = function (size) {
  23175. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  23176. // and 4x4 matrices
  23177. // TODO : change if other types are used
  23178. var alignment;
  23179. if (size <= 2) {
  23180. alignment = size;
  23181. }
  23182. else {
  23183. alignment = 4;
  23184. }
  23185. if ((this._uniformLocationPointer % alignment) !== 0) {
  23186. var oldPointer = this._uniformLocationPointer;
  23187. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  23188. var diff = this._uniformLocationPointer - oldPointer;
  23189. for (var i = 0; i < diff; i++) {
  23190. this._data.push(0);
  23191. }
  23192. }
  23193. };
  23194. /**
  23195. * Adds an uniform in the buffer.
  23196. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  23197. * for the layout to be correct !
  23198. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  23199. * @param {number|number[]} size Data size, or data directly.
  23200. */
  23201. UniformBuffer.prototype.addUniform = function (name, size) {
  23202. if (this._noUBO) {
  23203. return;
  23204. }
  23205. if (this._uniformLocations[name] !== undefined) {
  23206. // Already existing uniform
  23207. return;
  23208. }
  23209. // This function must be called in the order of the shader layout !
  23210. // size can be the size of the uniform, or data directly
  23211. var data;
  23212. if (size instanceof Array) {
  23213. data = size;
  23214. size = data.length;
  23215. }
  23216. else {
  23217. size = size;
  23218. data = [];
  23219. // Fill with zeros
  23220. for (var i = 0; i < size; i++) {
  23221. data.push(0);
  23222. }
  23223. }
  23224. this._fillAlignment(size);
  23225. this._uniformSizes[name] = size;
  23226. this._uniformLocations[name] = this._uniformLocationPointer;
  23227. this._uniformLocationPointer += size;
  23228. for (var i = 0; i < size; i++) {
  23229. this._data.push(data[i]);
  23230. }
  23231. this._needSync = true;
  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 {Matrix} mat A 4x4 matrix.
  23237. */
  23238. UniformBuffer.prototype.addMatrix = function (name, mat) {
  23239. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  23240. };
  23241. /**
  23242. * Wrapper for addUniform.
  23243. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  23244. * @param {number} x
  23245. * @param {number} y
  23246. */
  23247. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  23248. var temp = [x, y];
  23249. this.addUniform(name, temp);
  23250. };
  23251. /**
  23252. * Wrapper for addUniform.
  23253. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  23254. * @param {number} x
  23255. * @param {number} y
  23256. * @param {number} z
  23257. */
  23258. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  23259. var temp = [x, y, z];
  23260. this.addUniform(name, temp);
  23261. };
  23262. /**
  23263. * Wrapper for addUniform.
  23264. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  23265. * @param {Color3} color
  23266. */
  23267. UniformBuffer.prototype.addColor3 = function (name, color) {
  23268. var temp = [];
  23269. color.toArray(temp);
  23270. this.addUniform(name, temp);
  23271. };
  23272. /**
  23273. * Wrapper for addUniform.
  23274. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  23275. * @param {Color3} color
  23276. * @param {number} alpha
  23277. */
  23278. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  23279. var temp = [];
  23280. color.toArray(temp);
  23281. temp.push(alpha);
  23282. this.addUniform(name, temp);
  23283. };
  23284. /**
  23285. * Wrapper for addUniform.
  23286. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  23287. * @param {Vector3} vector
  23288. */
  23289. UniformBuffer.prototype.addVector3 = function (name, vector) {
  23290. var temp = [];
  23291. vector.toArray(temp);
  23292. this.addUniform(name, temp);
  23293. };
  23294. /**
  23295. * Wrapper for addUniform.
  23296. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  23297. */
  23298. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  23299. this.addUniform(name, 12);
  23300. };
  23301. /**
  23302. * Wrapper for addUniform.
  23303. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  23304. */
  23305. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  23306. this.addUniform(name, 8);
  23307. };
  23308. /**
  23309. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  23310. */
  23311. UniformBuffer.prototype.create = function () {
  23312. if (this._noUBO) {
  23313. return;
  23314. }
  23315. if (this._buffer) {
  23316. return; // nothing to do
  23317. }
  23318. // See spec, alignment must be filled as a vec4
  23319. this._fillAlignment(4);
  23320. this._bufferData = new Float32Array(this._data);
  23321. if (this._dynamic) {
  23322. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  23323. }
  23324. else {
  23325. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  23326. }
  23327. this._needSync = true;
  23328. };
  23329. /**
  23330. * Updates the WebGL Uniform Buffer on the GPU.
  23331. * If the `dynamic` flag is set to true, no cache comparison is done.
  23332. * Otherwise, the buffer will be updated only if the cache differs.
  23333. */
  23334. UniformBuffer.prototype.update = function () {
  23335. if (!this._buffer) {
  23336. this.create();
  23337. return;
  23338. }
  23339. if (!this._dynamic && !this._needSync) {
  23340. return;
  23341. }
  23342. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  23343. this._needSync = false;
  23344. };
  23345. /**
  23346. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  23347. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  23348. * @param {number[]|Float32Array} data Flattened data
  23349. * @param {number} size Size of the data.
  23350. */
  23351. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  23352. var location = this._uniformLocations[uniformName];
  23353. if (location === undefined) {
  23354. if (this._buffer) {
  23355. // Cannot add an uniform if the buffer is already created
  23356. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  23357. return;
  23358. }
  23359. this.addUniform(uniformName, size);
  23360. location = this._uniformLocations[uniformName];
  23361. }
  23362. if (!this._buffer) {
  23363. this.create();
  23364. }
  23365. if (!this._dynamic) {
  23366. // Cache for static uniform buffers
  23367. var changed = false;
  23368. for (var i = 0; i < size; i++) {
  23369. if (this._bufferData[location + i] !== data[i]) {
  23370. changed = true;
  23371. this._bufferData[location + i] = data[i];
  23372. }
  23373. }
  23374. this._needSync = this._needSync || changed;
  23375. }
  23376. else {
  23377. // No cache for dynamic
  23378. for (var i = 0; i < size; i++) {
  23379. this._bufferData[location + i] = data[i];
  23380. }
  23381. }
  23382. };
  23383. // Update methods
  23384. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  23385. // To match std140, matrix must be realigned
  23386. for (var i = 0; i < 3; i++) {
  23387. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  23388. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  23389. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  23390. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  23391. }
  23392. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  23393. };
  23394. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  23395. this._currentEffect.setMatrix3x3(name, matrix);
  23396. };
  23397. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  23398. this._currentEffect.setMatrix2x2(name, matrix);
  23399. };
  23400. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  23401. // To match std140, matrix must be realigned
  23402. for (var i = 0; i < 2; i++) {
  23403. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  23404. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  23405. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  23406. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  23407. }
  23408. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  23409. };
  23410. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  23411. this._currentEffect.setFloat(name, x);
  23412. };
  23413. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  23414. UniformBuffer._tempBuffer[0] = x;
  23415. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  23416. };
  23417. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y) {
  23418. this._currentEffect.setFloat2(name, x, y);
  23419. };
  23420. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y) {
  23421. UniformBuffer._tempBuffer[0] = x;
  23422. UniformBuffer._tempBuffer[1] = y;
  23423. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  23424. };
  23425. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  23426. if (suffix === void 0) { suffix = ""; }
  23427. this._currentEffect.setFloat3(name + suffix, x, y, z);
  23428. };
  23429. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  23430. if (suffix === void 0) { suffix = ""; }
  23431. UniformBuffer._tempBuffer[0] = x;
  23432. UniformBuffer._tempBuffer[1] = y;
  23433. UniformBuffer._tempBuffer[2] = z;
  23434. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  23435. };
  23436. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  23437. if (suffix === void 0) { suffix = ""; }
  23438. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  23439. };
  23440. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  23441. if (suffix === void 0) { suffix = ""; }
  23442. UniformBuffer._tempBuffer[0] = x;
  23443. UniformBuffer._tempBuffer[1] = y;
  23444. UniformBuffer._tempBuffer[2] = z;
  23445. UniformBuffer._tempBuffer[3] = w;
  23446. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  23447. };
  23448. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  23449. this._currentEffect.setMatrix(name, mat);
  23450. };
  23451. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  23452. this.updateUniform(name, mat.toArray(), 16);
  23453. };
  23454. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  23455. this._currentEffect.setVector3(name, vector);
  23456. };
  23457. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  23458. vector.toArray(UniformBuffer._tempBuffer);
  23459. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  23460. };
  23461. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  23462. this._currentEffect.setVector4(name, vector);
  23463. };
  23464. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  23465. vector.toArray(UniformBuffer._tempBuffer);
  23466. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  23467. };
  23468. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  23469. if (suffix === void 0) { suffix = ""; }
  23470. this._currentEffect.setColor3(name + suffix, color);
  23471. };
  23472. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  23473. if (suffix === void 0) { suffix = ""; }
  23474. color.toArray(UniformBuffer._tempBuffer);
  23475. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  23476. };
  23477. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  23478. if (suffix === void 0) { suffix = ""; }
  23479. this._currentEffect.setColor4(name + suffix, color, alpha);
  23480. };
  23481. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  23482. if (suffix === void 0) { suffix = ""; }
  23483. color.toArray(UniformBuffer._tempBuffer);
  23484. UniformBuffer._tempBuffer[3] = alpha;
  23485. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  23486. };
  23487. /**
  23488. * Sets a sampler uniform on the effect.
  23489. * @param {string} name Name of the sampler.
  23490. * @param {Texture} texture
  23491. */
  23492. UniformBuffer.prototype.setTexture = function (name, texture) {
  23493. this._currentEffect.setTexture(name, texture);
  23494. };
  23495. /**
  23496. * Directly updates the value of the uniform in the cache AND on the GPU.
  23497. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  23498. * @param {number[]|Float32Array} data Flattened data
  23499. */
  23500. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  23501. this.updateUniform(uniformName, data, data.length);
  23502. this.update();
  23503. };
  23504. /**
  23505. * Binds this uniform buffer to an effect.
  23506. * @param {Effect} effect
  23507. * @param {string} name Name of the uniform block in the shader.
  23508. */
  23509. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  23510. this._currentEffect = effect;
  23511. if (this._noUBO) {
  23512. return;
  23513. }
  23514. effect.bindUniformBuffer(this._buffer, name);
  23515. };
  23516. /**
  23517. * Disposes the uniform buffer.
  23518. */
  23519. UniformBuffer.prototype.dispose = function () {
  23520. if (!this._buffer) {
  23521. return;
  23522. }
  23523. if (this._engine._releaseBuffer(this._buffer)) {
  23524. this._buffer = null;
  23525. }
  23526. };
  23527. return UniformBuffer;
  23528. }());
  23529. // Pool for avoiding memory leaks
  23530. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  23531. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  23532. BABYLON.UniformBuffer = UniformBuffer;
  23533. })(BABYLON || (BABYLON = {}));
  23534. //# sourceMappingURL=babylon.uniformBuffer.js.map
  23535. var BABYLON;
  23536. (function (BABYLON) {
  23537. var PushMaterial = (function (_super) {
  23538. __extends(PushMaterial, _super);
  23539. function PushMaterial(name, scene) {
  23540. var _this = _super.call(this, name, scene) || this;
  23541. _this.storeEffectOnSubMeshes = true;
  23542. return _this;
  23543. }
  23544. PushMaterial.prototype.getEffect = function () {
  23545. return this._activeEffect;
  23546. };
  23547. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  23548. if (!mesh) {
  23549. return false;
  23550. }
  23551. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  23552. return true;
  23553. }
  23554. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  23555. };
  23556. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  23557. this._activeEffect.setMatrix("world", world);
  23558. };
  23559. PushMaterial.prototype.bind = function (world, mesh) {
  23560. if (!mesh) {
  23561. return;
  23562. }
  23563. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  23564. };
  23565. PushMaterial.prototype._afterBind = function (mesh, effect) {
  23566. _super.prototype._afterBind.call(this, mesh);
  23567. this.getScene()._cachedEffect = effect;
  23568. };
  23569. PushMaterial.prototype._mustRebind = function (scene, effect) {
  23570. return scene.getCachedEffect() !== effect || scene.getCachedMaterial() !== this;
  23571. };
  23572. PushMaterial.prototype.markAsDirty = function (flag) {
  23573. if (flag & BABYLON.Material.TextureDirtyFlag) {
  23574. this._markAllSubMeshesAsTexturesDirty();
  23575. }
  23576. if (flag & BABYLON.Material.LightDirtyFlag) {
  23577. this._markAllSubMeshesAsLightsDirty();
  23578. }
  23579. if (flag & BABYLON.Material.FresnelDirtyFlag) {
  23580. this._markAllSubMeshesAsFresnelDirty();
  23581. }
  23582. if (flag & BABYLON.Material.AttributesDirtyFlag) {
  23583. this._markAllSubMeshesAsAttributesDirty();
  23584. }
  23585. if (flag & BABYLON.Material.MiscDirtyFlag) {
  23586. this._markAllSubMeshesAsMiscDirty();
  23587. }
  23588. };
  23589. PushMaterial.prototype._markAllSubMeshesAsDirty = function (func) {
  23590. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  23591. var mesh = _a[_i];
  23592. if (!mesh.subMeshes) {
  23593. continue;
  23594. }
  23595. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  23596. var subMesh = _c[_b];
  23597. if (subMesh.getMaterial() !== this) {
  23598. continue;
  23599. }
  23600. if (!subMesh._materialDefines) {
  23601. return;
  23602. }
  23603. func(subMesh._materialDefines);
  23604. }
  23605. }
  23606. };
  23607. PushMaterial.prototype._markAllSubMeshesAsTexturesDirty = function () {
  23608. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  23609. };
  23610. PushMaterial.prototype._markAllSubMeshesAsFresnelDirty = function () {
  23611. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  23612. };
  23613. PushMaterial.prototype._markAllSubMeshesAsLightsDirty = function () {
  23614. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  23615. };
  23616. PushMaterial.prototype._markAllSubMeshesAsAttributesDirty = function () {
  23617. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  23618. };
  23619. PushMaterial.prototype._markAllSubMeshesAsMiscDirty = function () {
  23620. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  23621. };
  23622. return PushMaterial;
  23623. }(BABYLON.Material));
  23624. BABYLON.PushMaterial = PushMaterial;
  23625. })(BABYLON || (BABYLON = {}));
  23626. //# sourceMappingURL=babylon.pushMaterial.js.map
  23627. var BABYLON;
  23628. (function (BABYLON) {
  23629. var VertexData = (function () {
  23630. function VertexData() {
  23631. }
  23632. VertexData.prototype.set = function (data, kind) {
  23633. switch (kind) {
  23634. case BABYLON.VertexBuffer.PositionKind:
  23635. this.positions = data;
  23636. break;
  23637. case BABYLON.VertexBuffer.NormalKind:
  23638. this.normals = data;
  23639. break;
  23640. case BABYLON.VertexBuffer.TangentKind:
  23641. this.tangents = data;
  23642. break;
  23643. case BABYLON.VertexBuffer.UVKind:
  23644. this.uvs = data;
  23645. break;
  23646. case BABYLON.VertexBuffer.UV2Kind:
  23647. this.uvs2 = data;
  23648. break;
  23649. case BABYLON.VertexBuffer.UV3Kind:
  23650. this.uvs3 = data;
  23651. break;
  23652. case BABYLON.VertexBuffer.UV4Kind:
  23653. this.uvs4 = data;
  23654. break;
  23655. case BABYLON.VertexBuffer.UV5Kind:
  23656. this.uvs5 = data;
  23657. break;
  23658. case BABYLON.VertexBuffer.UV6Kind:
  23659. this.uvs6 = data;
  23660. break;
  23661. case BABYLON.VertexBuffer.ColorKind:
  23662. this.colors = data;
  23663. break;
  23664. case BABYLON.VertexBuffer.MatricesIndicesKind:
  23665. this.matricesIndices = data;
  23666. break;
  23667. case BABYLON.VertexBuffer.MatricesWeightsKind:
  23668. this.matricesWeights = data;
  23669. break;
  23670. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  23671. this.matricesIndicesExtra = data;
  23672. break;
  23673. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  23674. this.matricesWeightsExtra = data;
  23675. break;
  23676. }
  23677. };
  23678. /**
  23679. * Associates the vertexData to the passed Mesh.
  23680. * Sets it as updatable or not (default `false`).
  23681. * Returns the VertexData.
  23682. */
  23683. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  23684. this._applyTo(mesh, updatable);
  23685. return this;
  23686. };
  23687. /**
  23688. * Associates the vertexData to the passed Geometry.
  23689. * Sets it as updatable or not (default `false`).
  23690. * Returns the VertexData.
  23691. */
  23692. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  23693. this._applyTo(geometry, updatable);
  23694. return this;
  23695. };
  23696. /**
  23697. * Updates the associated mesh.
  23698. * Returns the VertexData.
  23699. */
  23700. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  23701. this._update(mesh);
  23702. return this;
  23703. };
  23704. /**
  23705. * Updates the associated geometry.
  23706. * Returns the VertexData.
  23707. */
  23708. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  23709. this._update(geometry);
  23710. return this;
  23711. };
  23712. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  23713. if (this.positions) {
  23714. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  23715. }
  23716. if (this.normals) {
  23717. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  23718. }
  23719. if (this.tangents) {
  23720. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  23721. }
  23722. if (this.uvs) {
  23723. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  23724. }
  23725. if (this.uvs2) {
  23726. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  23727. }
  23728. if (this.uvs3) {
  23729. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  23730. }
  23731. if (this.uvs4) {
  23732. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  23733. }
  23734. if (this.uvs5) {
  23735. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  23736. }
  23737. if (this.uvs6) {
  23738. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  23739. }
  23740. if (this.colors) {
  23741. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  23742. }
  23743. if (this.matricesIndices) {
  23744. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  23745. }
  23746. if (this.matricesWeights) {
  23747. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  23748. }
  23749. if (this.matricesIndicesExtra) {
  23750. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  23751. }
  23752. if (this.matricesWeightsExtra) {
  23753. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  23754. }
  23755. if (this.indices) {
  23756. meshOrGeometry.setIndices(this.indices);
  23757. }
  23758. return this;
  23759. };
  23760. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  23761. if (this.positions) {
  23762. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  23763. }
  23764. if (this.normals) {
  23765. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  23766. }
  23767. if (this.tangents) {
  23768. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  23769. }
  23770. if (this.uvs) {
  23771. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  23772. }
  23773. if (this.uvs2) {
  23774. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  23775. }
  23776. if (this.uvs3) {
  23777. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  23778. }
  23779. if (this.uvs4) {
  23780. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  23781. }
  23782. if (this.uvs5) {
  23783. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  23784. }
  23785. if (this.uvs6) {
  23786. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  23787. }
  23788. if (this.colors) {
  23789. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  23790. }
  23791. if (this.matricesIndices) {
  23792. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  23793. }
  23794. if (this.matricesWeights) {
  23795. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  23796. }
  23797. if (this.matricesIndicesExtra) {
  23798. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  23799. }
  23800. if (this.matricesWeightsExtra) {
  23801. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  23802. }
  23803. if (this.indices) {
  23804. meshOrGeometry.setIndices(this.indices);
  23805. }
  23806. return this;
  23807. };
  23808. /**
  23809. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  23810. * Returns the VertexData.
  23811. */
  23812. VertexData.prototype.transform = function (matrix) {
  23813. var transformed = BABYLON.Vector3.Zero();
  23814. var index;
  23815. if (this.positions) {
  23816. var position = BABYLON.Vector3.Zero();
  23817. for (index = 0; index < this.positions.length; index += 3) {
  23818. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  23819. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  23820. this.positions[index] = transformed.x;
  23821. this.positions[index + 1] = transformed.y;
  23822. this.positions[index + 2] = transformed.z;
  23823. }
  23824. }
  23825. if (this.normals) {
  23826. var normal = BABYLON.Vector3.Zero();
  23827. for (index = 0; index < this.normals.length; index += 3) {
  23828. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  23829. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  23830. this.normals[index] = transformed.x;
  23831. this.normals[index + 1] = transformed.y;
  23832. this.normals[index + 2] = transformed.z;
  23833. }
  23834. }
  23835. if (this.tangents) {
  23836. var tangent = BABYLON.Vector4.Zero();
  23837. var tangentTransformed = BABYLON.Vector4.Zero();
  23838. for (index = 0; index < this.tangents.length; index += 4) {
  23839. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  23840. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  23841. this.tangents[index] = tangentTransformed.x;
  23842. this.tangents[index + 1] = tangentTransformed.y;
  23843. this.tangents[index + 2] = tangentTransformed.z;
  23844. this.tangents[index + 3] = tangentTransformed.w;
  23845. }
  23846. }
  23847. return this;
  23848. };
  23849. /**
  23850. * Merges the passed VertexData into the current one.
  23851. * Returns the modified VertexData.
  23852. */
  23853. VertexData.prototype.merge = function (other) {
  23854. if (other.indices) {
  23855. if (!this.indices) {
  23856. this.indices = [];
  23857. }
  23858. var offset = this.positions ? this.positions.length / 3 : 0;
  23859. for (var index = 0; index < other.indices.length; index++) {
  23860. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  23861. this.indices.push(other.indices[index] + offset);
  23862. }
  23863. }
  23864. this.positions = this._mergeElement(this.positions, other.positions);
  23865. this.normals = this._mergeElement(this.normals, other.normals);
  23866. this.tangents = this._mergeElement(this.tangents, other.tangents);
  23867. this.uvs = this._mergeElement(this.uvs, other.uvs);
  23868. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  23869. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  23870. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  23871. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  23872. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  23873. this.colors = this._mergeElement(this.colors, other.colors);
  23874. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  23875. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  23876. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  23877. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  23878. return this;
  23879. };
  23880. VertexData.prototype._mergeElement = function (source, other) {
  23881. if (!other)
  23882. return source;
  23883. if (!source)
  23884. return other;
  23885. var len = other.length + source.length;
  23886. var isSrcTypedArray = source instanceof Float32Array;
  23887. var isOthTypedArray = other instanceof Float32Array;
  23888. // use non-loop method when the source is Float32Array
  23889. if (isSrcTypedArray) {
  23890. var ret32 = new Float32Array(len);
  23891. ret32.set(source);
  23892. ret32.set(other, source.length);
  23893. return ret32;
  23894. // source is number[], when other is also use concat
  23895. }
  23896. else if (!isOthTypedArray) {
  23897. return source.concat(other);
  23898. // source is a number[], but other is a Float32Array, loop required
  23899. }
  23900. else {
  23901. var ret = source.slice(0); // copy source to a separate array
  23902. for (var i = 0, len = other.length; i < len; i++) {
  23903. ret.push(other[i]);
  23904. }
  23905. return ret;
  23906. }
  23907. };
  23908. /**
  23909. * Serializes the VertexData.
  23910. * Returns a serialized object.
  23911. */
  23912. VertexData.prototype.serialize = function () {
  23913. var serializationObject = this.serialize();
  23914. if (this.positions) {
  23915. serializationObject.positions = this.positions;
  23916. }
  23917. if (this.normals) {
  23918. serializationObject.normals = this.normals;
  23919. }
  23920. if (this.tangents) {
  23921. serializationObject.tangents = this.tangents;
  23922. }
  23923. if (this.uvs) {
  23924. serializationObject.uvs = this.uvs;
  23925. }
  23926. if (this.uvs2) {
  23927. serializationObject.uvs2 = this.uvs2;
  23928. }
  23929. if (this.uvs3) {
  23930. serializationObject.uvs3 = this.uvs3;
  23931. }
  23932. if (this.uvs4) {
  23933. serializationObject.uvs4 = this.uvs4;
  23934. }
  23935. if (this.uvs5) {
  23936. serializationObject.uvs5 = this.uvs5;
  23937. }
  23938. if (this.uvs6) {
  23939. serializationObject.uvs6 = this.uvs6;
  23940. }
  23941. if (this.colors) {
  23942. serializationObject.colors = this.colors;
  23943. }
  23944. if (this.matricesIndices) {
  23945. serializationObject.matricesIndices = this.matricesIndices;
  23946. serializationObject.matricesIndices._isExpanded = true;
  23947. }
  23948. if (this.matricesWeights) {
  23949. serializationObject.matricesWeights = this.matricesWeights;
  23950. }
  23951. if (this.matricesIndicesExtra) {
  23952. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  23953. serializationObject.matricesIndicesExtra._isExpanded = true;
  23954. }
  23955. if (this.matricesWeightsExtra) {
  23956. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  23957. }
  23958. serializationObject.indices = this.indices;
  23959. return serializationObject;
  23960. };
  23961. // Statics
  23962. /**
  23963. * Returns the object VertexData associated to the passed mesh.
  23964. */
  23965. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  23966. return VertexData._ExtractFrom(mesh, copyWhenShared);
  23967. };
  23968. /**
  23969. * Returns the object VertexData associated to the passed geometry.
  23970. */
  23971. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  23972. return VertexData._ExtractFrom(geometry, copyWhenShared);
  23973. };
  23974. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  23975. var result = new VertexData();
  23976. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  23977. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  23978. }
  23979. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  23980. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  23981. }
  23982. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  23983. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared);
  23984. }
  23985. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  23986. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  23987. }
  23988. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  23989. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  23990. }
  23991. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  23992. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  23993. }
  23994. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  23995. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  23996. }
  23997. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  23998. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  23999. }
  24000. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  24001. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  24002. }
  24003. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  24004. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  24005. }
  24006. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  24007. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  24008. }
  24009. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  24010. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  24011. }
  24012. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  24013. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
  24014. }
  24015. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  24016. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
  24017. }
  24018. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  24019. return result;
  24020. };
  24021. /**
  24022. * Creates the vertexData of the Ribbon.
  24023. */
  24024. VertexData.CreateRibbon = function (options) {
  24025. var pathArray = options.pathArray;
  24026. var closeArray = options.closeArray || false;
  24027. var closePath = options.closePath || false;
  24028. var invertUV = options.invertUV || false;
  24029. var defaultOffset = Math.floor(pathArray[0].length / 2);
  24030. var offset = options.offset || defaultOffset;
  24031. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  24032. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24033. var customUV = options.uvs;
  24034. var customColors = options.colors;
  24035. var positions = [];
  24036. var indices = [];
  24037. var normals = [];
  24038. var uvs = [];
  24039. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  24040. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  24041. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  24042. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  24043. var minlg; // minimal length among all paths from pathArray
  24044. var lg = []; // array of path lengths : nb of vertex per path
  24045. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  24046. var p; // path iterator
  24047. var i; // point iterator
  24048. var j; // point iterator
  24049. // if single path in pathArray
  24050. if (pathArray.length < 2) {
  24051. var ar1 = [];
  24052. var ar2 = [];
  24053. for (i = 0; i < pathArray[0].length - offset; i++) {
  24054. ar1.push(pathArray[0][i]);
  24055. ar2.push(pathArray[0][i + offset]);
  24056. }
  24057. pathArray = [ar1, ar2];
  24058. }
  24059. // positions and horizontal distances (u)
  24060. var idc = 0;
  24061. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  24062. var path;
  24063. var l;
  24064. minlg = pathArray[0].length;
  24065. var vectlg;
  24066. var dist;
  24067. for (p = 0; p < pathArray.length; p++) {
  24068. uTotalDistance[p] = 0;
  24069. us[p] = [0];
  24070. path = pathArray[p];
  24071. l = path.length;
  24072. minlg = (minlg < l) ? minlg : l;
  24073. j = 0;
  24074. while (j < l) {
  24075. positions.push(path[j].x, path[j].y, path[j].z);
  24076. if (j > 0) {
  24077. vectlg = path[j].subtract(path[j - 1]).length();
  24078. dist = vectlg + uTotalDistance[p];
  24079. us[p].push(dist);
  24080. uTotalDistance[p] = dist;
  24081. }
  24082. j++;
  24083. }
  24084. if (closePath) {
  24085. j--;
  24086. positions.push(path[0].x, path[0].y, path[0].z);
  24087. vectlg = path[j].subtract(path[0]).length();
  24088. dist = vectlg + uTotalDistance[p];
  24089. us[p].push(dist);
  24090. uTotalDistance[p] = dist;
  24091. }
  24092. lg[p] = l + closePathCorr;
  24093. idx[p] = idc;
  24094. idc += (l + closePathCorr);
  24095. }
  24096. // vertical distances (v)
  24097. var path1;
  24098. var path2;
  24099. var vertex1;
  24100. var vertex2;
  24101. for (i = 0; i < minlg + closePathCorr; i++) {
  24102. vTotalDistance[i] = 0;
  24103. vs[i] = [0];
  24104. for (p = 0; p < pathArray.length - 1; p++) {
  24105. path1 = pathArray[p];
  24106. path2 = pathArray[p + 1];
  24107. if (i === minlg) {
  24108. vertex1 = path1[0];
  24109. vertex2 = path2[0];
  24110. }
  24111. else {
  24112. vertex1 = path1[i];
  24113. vertex2 = path2[i];
  24114. }
  24115. vectlg = vertex2.subtract(vertex1).length();
  24116. dist = vectlg + vTotalDistance[i];
  24117. vs[i].push(dist);
  24118. vTotalDistance[i] = dist;
  24119. }
  24120. if (closeArray) {
  24121. path1 = pathArray[p];
  24122. path2 = pathArray[0];
  24123. if (i === minlg) {
  24124. vertex2 = path2[0];
  24125. }
  24126. vectlg = vertex2.subtract(vertex1).length();
  24127. dist = vectlg + vTotalDistance[i];
  24128. vTotalDistance[i] = dist;
  24129. }
  24130. }
  24131. // uvs
  24132. var u;
  24133. var v;
  24134. if (customUV) {
  24135. for (p = 0; p < customUV.length; p++) {
  24136. uvs.push(customUV[p].x, customUV[p].y);
  24137. }
  24138. }
  24139. else {
  24140. for (p = 0; p < pathArray.length; p++) {
  24141. for (i = 0; i < minlg + closePathCorr; i++) {
  24142. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  24143. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  24144. if (invertUV) {
  24145. uvs.push(v, u);
  24146. }
  24147. else {
  24148. uvs.push(u, v);
  24149. }
  24150. }
  24151. }
  24152. }
  24153. // indices
  24154. p = 0; // path index
  24155. var pi = 0; // positions array index
  24156. var l1 = lg[p] - 1; // path1 length
  24157. var l2 = lg[p + 1] - 1; // path2 length
  24158. var min = (l1 < l2) ? l1 : l2; // current path stop index
  24159. var shft = idx[1] - idx[0]; // shift
  24160. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  24161. while (pi <= min && p < path1nb) {
  24162. // 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
  24163. indices.push(pi, pi + shft, pi + 1);
  24164. indices.push(pi + shft + 1, pi + 1, pi + shft);
  24165. pi += 1;
  24166. if (pi === min) {
  24167. p++;
  24168. if (p === lg.length - 1) {
  24169. shft = idx[0] - idx[p];
  24170. l1 = lg[p] - 1;
  24171. l2 = lg[0] - 1;
  24172. }
  24173. else {
  24174. shft = idx[p + 1] - idx[p];
  24175. l1 = lg[p] - 1;
  24176. l2 = lg[p + 1] - 1;
  24177. }
  24178. pi = idx[p];
  24179. min = (l1 < l2) ? l1 + pi : l2 + pi;
  24180. }
  24181. }
  24182. // normals
  24183. VertexData.ComputeNormals(positions, indices, normals);
  24184. if (closePath) {
  24185. var indexFirst = 0;
  24186. var indexLast = 0;
  24187. for (p = 0; p < pathArray.length; p++) {
  24188. indexFirst = idx[p] * 3;
  24189. if (p + 1 < pathArray.length) {
  24190. indexLast = (idx[p + 1] - 1) * 3;
  24191. }
  24192. else {
  24193. indexLast = normals.length - 3;
  24194. }
  24195. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  24196. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  24197. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  24198. normals[indexLast] = normals[indexFirst];
  24199. normals[indexLast + 1] = normals[indexFirst + 1];
  24200. normals[indexLast + 2] = normals[indexFirst + 2];
  24201. }
  24202. }
  24203. // sides
  24204. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24205. // Colors
  24206. if (customColors) {
  24207. var colors = new Float32Array(customColors.length * 4);
  24208. for (var c = 0; c < customColors.length; c++) {
  24209. colors[c * 4] = customColors[c].r;
  24210. colors[c * 4 + 1] = customColors[c].g;
  24211. colors[c * 4 + 2] = customColors[c].b;
  24212. colors[c * 4 + 3] = customColors[c].a;
  24213. }
  24214. }
  24215. // Result
  24216. var vertexData = new VertexData();
  24217. var positions32 = new Float32Array(positions);
  24218. var normals32 = new Float32Array(normals);
  24219. var uvs32 = new Float32Array(uvs);
  24220. vertexData.indices = indices;
  24221. vertexData.positions = positions32;
  24222. vertexData.normals = normals32;
  24223. vertexData.uvs = uvs32;
  24224. if (customColors) {
  24225. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  24226. }
  24227. if (closePath) {
  24228. vertexData._idx = idx;
  24229. }
  24230. return vertexData;
  24231. };
  24232. /**
  24233. * Creates the VertexData of the Box.
  24234. */
  24235. VertexData.CreateBox = function (options) {
  24236. var normalsSource = [
  24237. new BABYLON.Vector3(0, 0, 1),
  24238. new BABYLON.Vector3(0, 0, -1),
  24239. new BABYLON.Vector3(1, 0, 0),
  24240. new BABYLON.Vector3(-1, 0, 0),
  24241. new BABYLON.Vector3(0, 1, 0),
  24242. new BABYLON.Vector3(0, -1, 0)
  24243. ];
  24244. var indices = [];
  24245. var positions = [];
  24246. var normals = [];
  24247. var uvs = [];
  24248. var width = options.width || options.size || 1;
  24249. var height = options.height || options.size || 1;
  24250. var depth = options.depth || options.size || 1;
  24251. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24252. var faceUV = options.faceUV || new Array(6);
  24253. var faceColors = options.faceColors;
  24254. var colors = [];
  24255. // default face colors and UV if undefined
  24256. for (var f = 0; f < 6; f++) {
  24257. if (faceUV[f] === undefined) {
  24258. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  24259. }
  24260. if (faceColors && faceColors[f] === undefined) {
  24261. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  24262. }
  24263. }
  24264. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  24265. // Create each face in turn.
  24266. for (var index = 0; index < normalsSource.length; index++) {
  24267. var normal = normalsSource[index];
  24268. // Get two vectors perpendicular to the face normal and to each other.
  24269. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  24270. var side2 = BABYLON.Vector3.Cross(normal, side1);
  24271. // Six indices (two triangles) per face.
  24272. var verticesLength = positions.length / 3;
  24273. indices.push(verticesLength);
  24274. indices.push(verticesLength + 1);
  24275. indices.push(verticesLength + 2);
  24276. indices.push(verticesLength);
  24277. indices.push(verticesLength + 2);
  24278. indices.push(verticesLength + 3);
  24279. // Four vertices per face.
  24280. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  24281. positions.push(vertex.x, vertex.y, vertex.z);
  24282. normals.push(normal.x, normal.y, normal.z);
  24283. uvs.push(faceUV[index].z, faceUV[index].w);
  24284. if (faceColors) {
  24285. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  24286. }
  24287. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  24288. positions.push(vertex.x, vertex.y, vertex.z);
  24289. normals.push(normal.x, normal.y, normal.z);
  24290. uvs.push(faceUV[index].x, faceUV[index].w);
  24291. if (faceColors) {
  24292. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  24293. }
  24294. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  24295. positions.push(vertex.x, vertex.y, vertex.z);
  24296. normals.push(normal.x, normal.y, normal.z);
  24297. uvs.push(faceUV[index].x, faceUV[index].y);
  24298. if (faceColors) {
  24299. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  24300. }
  24301. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  24302. positions.push(vertex.x, vertex.y, vertex.z);
  24303. normals.push(normal.x, normal.y, normal.z);
  24304. uvs.push(faceUV[index].z, faceUV[index].y);
  24305. if (faceColors) {
  24306. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  24307. }
  24308. }
  24309. // sides
  24310. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24311. // Result
  24312. var vertexData = new VertexData();
  24313. vertexData.indices = indices;
  24314. vertexData.positions = positions;
  24315. vertexData.normals = normals;
  24316. vertexData.uvs = uvs;
  24317. if (faceColors) {
  24318. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  24319. vertexData.colors = totalColors;
  24320. }
  24321. return vertexData;
  24322. };
  24323. /**
  24324. * Creates the VertexData of the Sphere.
  24325. */
  24326. VertexData.CreateSphere = function (options) {
  24327. var segments = options.segments || 32;
  24328. var diameterX = options.diameterX || options.diameter || 1;
  24329. var diameterY = options.diameterY || options.diameter || 1;
  24330. var diameterZ = options.diameterZ || options.diameter || 1;
  24331. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  24332. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  24333. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24334. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  24335. var totalZRotationSteps = 2 + segments;
  24336. var totalYRotationSteps = 2 * totalZRotationSteps;
  24337. var indices = [];
  24338. var positions = [];
  24339. var normals = [];
  24340. var uvs = [];
  24341. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  24342. var normalizedZ = zRotationStep / totalZRotationSteps;
  24343. var angleZ = normalizedZ * Math.PI * slice;
  24344. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  24345. var normalizedY = yRotationStep / totalYRotationSteps;
  24346. var angleY = normalizedY * Math.PI * 2 * arc;
  24347. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  24348. var rotationY = BABYLON.Matrix.RotationY(angleY);
  24349. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  24350. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  24351. var vertex = complete.multiply(radius);
  24352. var normal = complete.divide(radius).normalize();
  24353. positions.push(vertex.x, vertex.y, vertex.z);
  24354. normals.push(normal.x, normal.y, normal.z);
  24355. uvs.push(normalizedY, normalizedZ);
  24356. }
  24357. if (zRotationStep > 0) {
  24358. var verticesCount = positions.length / 3;
  24359. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  24360. indices.push((firstIndex));
  24361. indices.push((firstIndex + 1));
  24362. indices.push(firstIndex + totalYRotationSteps + 1);
  24363. indices.push((firstIndex + totalYRotationSteps + 1));
  24364. indices.push((firstIndex + 1));
  24365. indices.push((firstIndex + totalYRotationSteps + 2));
  24366. }
  24367. }
  24368. }
  24369. // Sides
  24370. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24371. // Result
  24372. var vertexData = new VertexData();
  24373. vertexData.indices = indices;
  24374. vertexData.positions = positions;
  24375. vertexData.normals = normals;
  24376. vertexData.uvs = uvs;
  24377. return vertexData;
  24378. };
  24379. /**
  24380. * Creates the VertexData of the Cylinder or Cone.
  24381. */
  24382. VertexData.CreateCylinder = function (options) {
  24383. var height = options.height || 2;
  24384. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  24385. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  24386. var tessellation = options.tessellation || 24;
  24387. var subdivisions = options.subdivisions || 1;
  24388. var hasRings = options.hasRings;
  24389. var enclose = options.enclose;
  24390. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  24391. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24392. var faceUV = options.faceUV || new Array(3);
  24393. var faceColors = options.faceColors;
  24394. // default face colors and UV if undefined
  24395. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  24396. var ringNb = (hasRings) ? subdivisions : 1;
  24397. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  24398. var f;
  24399. for (f = 0; f < surfaceNb; f++) {
  24400. if (faceColors && faceColors[f] === undefined) {
  24401. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  24402. }
  24403. }
  24404. for (f = 0; f < surfaceNb; f++) {
  24405. if (faceUV && faceUV[f] === undefined) {
  24406. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  24407. }
  24408. }
  24409. var indices = [];
  24410. var positions = [];
  24411. var normals = [];
  24412. var uvs = [];
  24413. var colors = [];
  24414. var angle_step = Math.PI * 2 * arc / tessellation;
  24415. var angle;
  24416. var h;
  24417. var radius;
  24418. var tan = (diameterBottom - diameterTop) / 2 / height;
  24419. var ringVertex = BABYLON.Vector3.Zero();
  24420. var ringNormal = BABYLON.Vector3.Zero();
  24421. var ringFirstVertex = BABYLON.Vector3.Zero();
  24422. var ringFirstNormal = BABYLON.Vector3.Zero();
  24423. var quadNormal = BABYLON.Vector3.Zero();
  24424. var Y = BABYLON.Axis.Y;
  24425. // positions, normals, uvs
  24426. var i;
  24427. var j;
  24428. var r;
  24429. var ringIdx = 1;
  24430. var s = 1; // surface index
  24431. var cs = 0;
  24432. var v = 0;
  24433. for (i = 0; i <= subdivisions; i++) {
  24434. h = i / subdivisions;
  24435. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  24436. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  24437. for (r = 0; r < ringIdx; r++) {
  24438. if (hasRings) {
  24439. s += r;
  24440. }
  24441. if (enclose) {
  24442. s += 2 * r;
  24443. }
  24444. for (j = 0; j <= tessellation; j++) {
  24445. angle = j * angle_step;
  24446. // position
  24447. ringVertex.x = Math.cos(-angle) * radius;
  24448. ringVertex.y = -height / 2 + h * height;
  24449. ringVertex.z = Math.sin(-angle) * radius;
  24450. // normal
  24451. if (diameterTop === 0 && i === subdivisions) {
  24452. // if no top cap, reuse former normals
  24453. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  24454. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  24455. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  24456. }
  24457. else {
  24458. ringNormal.x = ringVertex.x;
  24459. ringNormal.z = ringVertex.z;
  24460. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  24461. ringNormal.normalize();
  24462. }
  24463. // keep first ring vertex values for enclose
  24464. if (j === 0) {
  24465. ringFirstVertex.copyFrom(ringVertex);
  24466. ringFirstNormal.copyFrom(ringNormal);
  24467. }
  24468. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  24469. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  24470. if (hasRings) {
  24471. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  24472. }
  24473. else {
  24474. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  24475. }
  24476. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  24477. if (faceColors) {
  24478. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  24479. }
  24480. }
  24481. // if enclose, add four vertices and their dedicated normals
  24482. if (arc !== 1 && enclose) {
  24483. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  24484. positions.push(0, ringVertex.y, 0);
  24485. positions.push(0, ringVertex.y, 0);
  24486. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  24487. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  24488. quadNormal.normalize();
  24489. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  24490. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  24491. quadNormal.normalize();
  24492. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  24493. if (hasRings) {
  24494. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  24495. }
  24496. else {
  24497. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  24498. }
  24499. uvs.push(faceUV[s + 1].x, v);
  24500. uvs.push(faceUV[s + 1].z, v);
  24501. if (hasRings) {
  24502. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  24503. }
  24504. else {
  24505. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  24506. }
  24507. uvs.push(faceUV[s + 2].x, v);
  24508. uvs.push(faceUV[s + 2].z, v);
  24509. if (faceColors) {
  24510. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  24511. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  24512. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  24513. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  24514. }
  24515. }
  24516. if (cs !== s) {
  24517. cs = s;
  24518. }
  24519. }
  24520. }
  24521. // indices
  24522. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  24523. var s;
  24524. i = 0;
  24525. for (s = 0; s < subdivisions; s++) {
  24526. for (j = 0; j < tessellation; j++) {
  24527. var i0 = i * (e + 1) + j;
  24528. var i1 = (i + 1) * (e + 1) + j;
  24529. var i2 = i * (e + 1) + (j + 1);
  24530. var i3 = (i + 1) * (e + 1) + (j + 1);
  24531. indices.push(i0, i1, i2);
  24532. indices.push(i3, i2, i1);
  24533. }
  24534. if (arc !== 1 && enclose) {
  24535. indices.push(i0 + 2, i1 + 2, i2 + 2);
  24536. indices.push(i3 + 2, i2 + 2, i1 + 2);
  24537. indices.push(i0 + 4, i1 + 4, i2 + 4);
  24538. indices.push(i3 + 4, i2 + 4, i1 + 4);
  24539. }
  24540. i = (hasRings) ? (i + 2) : (i + 1);
  24541. }
  24542. // Caps
  24543. var createCylinderCap = function (isTop) {
  24544. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  24545. if (radius === 0) {
  24546. return;
  24547. }
  24548. // Cap positions, normals & uvs
  24549. var angle;
  24550. var circleVector;
  24551. var i;
  24552. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  24553. var c;
  24554. if (faceColors) {
  24555. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  24556. }
  24557. // cap center
  24558. var vbase = positions.length / 3;
  24559. var offset = isTop ? height / 2 : -height / 2;
  24560. var center = new BABYLON.Vector3(0, offset, 0);
  24561. positions.push(center.x, center.y, center.z);
  24562. normals.push(0, isTop ? 1 : -1, 0);
  24563. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  24564. if (faceColors) {
  24565. colors.push(c.r, c.g, c.b, c.a);
  24566. }
  24567. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  24568. for (i = 0; i <= tessellation; i++) {
  24569. angle = Math.PI * 2 * i * arc / tessellation;
  24570. var cos = Math.cos(-angle);
  24571. var sin = Math.sin(-angle);
  24572. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  24573. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  24574. positions.push(circleVector.x, circleVector.y, circleVector.z);
  24575. normals.push(0, isTop ? 1 : -1, 0);
  24576. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  24577. if (faceColors) {
  24578. colors.push(c.r, c.g, c.b, c.a);
  24579. }
  24580. }
  24581. // Cap indices
  24582. for (i = 0; i < tessellation; i++) {
  24583. if (!isTop) {
  24584. indices.push(vbase);
  24585. indices.push(vbase + (i + 1));
  24586. indices.push(vbase + (i + 2));
  24587. }
  24588. else {
  24589. indices.push(vbase);
  24590. indices.push(vbase + (i + 2));
  24591. indices.push(vbase + (i + 1));
  24592. }
  24593. }
  24594. };
  24595. // add caps to geometry
  24596. createCylinderCap(false);
  24597. createCylinderCap(true);
  24598. // Sides
  24599. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24600. var vertexData = new VertexData();
  24601. vertexData.indices = indices;
  24602. vertexData.positions = positions;
  24603. vertexData.normals = normals;
  24604. vertexData.uvs = uvs;
  24605. if (faceColors) {
  24606. vertexData.colors = colors;
  24607. }
  24608. return vertexData;
  24609. };
  24610. /**
  24611. * Creates the VertexData of the Torus.
  24612. */
  24613. VertexData.CreateTorus = function (options) {
  24614. var indices = [];
  24615. var positions = [];
  24616. var normals = [];
  24617. var uvs = [];
  24618. var diameter = options.diameter || 1;
  24619. var thickness = options.thickness || 0.5;
  24620. var tessellation = options.tessellation || 16;
  24621. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24622. var stride = tessellation + 1;
  24623. for (var i = 0; i <= tessellation; i++) {
  24624. var u = i / tessellation;
  24625. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  24626. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  24627. for (var j = 0; j <= tessellation; j++) {
  24628. var v = 1 - j / tessellation;
  24629. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  24630. var dx = Math.cos(innerAngle);
  24631. var dy = Math.sin(innerAngle);
  24632. // Create a vertex.
  24633. var normal = new BABYLON.Vector3(dx, dy, 0);
  24634. var position = normal.scale(thickness / 2);
  24635. var textureCoordinate = new BABYLON.Vector2(u, v);
  24636. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  24637. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  24638. positions.push(position.x, position.y, position.z);
  24639. normals.push(normal.x, normal.y, normal.z);
  24640. uvs.push(textureCoordinate.x, textureCoordinate.y);
  24641. // And create indices for two triangles.
  24642. var nextI = (i + 1) % stride;
  24643. var nextJ = (j + 1) % stride;
  24644. indices.push(i * stride + j);
  24645. indices.push(i * stride + nextJ);
  24646. indices.push(nextI * stride + j);
  24647. indices.push(i * stride + nextJ);
  24648. indices.push(nextI * stride + nextJ);
  24649. indices.push(nextI * stride + j);
  24650. }
  24651. }
  24652. // Sides
  24653. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24654. // Result
  24655. var vertexData = new VertexData();
  24656. vertexData.indices = indices;
  24657. vertexData.positions = positions;
  24658. vertexData.normals = normals;
  24659. vertexData.uvs = uvs;
  24660. return vertexData;
  24661. };
  24662. /**
  24663. * Creates the VertexData of the LineSystem.
  24664. */
  24665. VertexData.CreateLineSystem = function (options) {
  24666. var indices = [];
  24667. var positions = [];
  24668. var lines = options.lines;
  24669. var idx = 0;
  24670. for (var l = 0; l < lines.length; l++) {
  24671. var points = lines[l];
  24672. for (var index = 0; index < points.length; index++) {
  24673. positions.push(points[index].x, points[index].y, points[index].z);
  24674. if (index > 0) {
  24675. indices.push(idx - 1);
  24676. indices.push(idx);
  24677. }
  24678. idx++;
  24679. }
  24680. }
  24681. var vertexData = new VertexData();
  24682. vertexData.indices = indices;
  24683. vertexData.positions = positions;
  24684. return vertexData;
  24685. };
  24686. /**
  24687. * Create the VertexData of the DashedLines.
  24688. */
  24689. VertexData.CreateDashedLines = function (options) {
  24690. var dashSize = options.dashSize || 3;
  24691. var gapSize = options.gapSize || 1;
  24692. var dashNb = options.dashNb || 200;
  24693. var points = options.points;
  24694. var positions = new Array();
  24695. var indices = new Array();
  24696. var curvect = BABYLON.Vector3.Zero();
  24697. var lg = 0;
  24698. var nb = 0;
  24699. var shft = 0;
  24700. var dashshft = 0;
  24701. var curshft = 0;
  24702. var idx = 0;
  24703. var i = 0;
  24704. for (i = 0; i < points.length - 1; i++) {
  24705. points[i + 1].subtractToRef(points[i], curvect);
  24706. lg += curvect.length();
  24707. }
  24708. shft = lg / dashNb;
  24709. dashshft = dashSize * shft / (dashSize + gapSize);
  24710. for (i = 0; i < points.length - 1; i++) {
  24711. points[i + 1].subtractToRef(points[i], curvect);
  24712. nb = Math.floor(curvect.length() / shft);
  24713. curvect.normalize();
  24714. for (var j = 0; j < nb; j++) {
  24715. curshft = shft * j;
  24716. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  24717. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  24718. indices.push(idx, idx + 1);
  24719. idx += 2;
  24720. }
  24721. }
  24722. // Result
  24723. var vertexData = new VertexData();
  24724. vertexData.positions = positions;
  24725. vertexData.indices = indices;
  24726. return vertexData;
  24727. };
  24728. /**
  24729. * Creates the VertexData of the Ground.
  24730. */
  24731. VertexData.CreateGround = function (options) {
  24732. var indices = [];
  24733. var positions = [];
  24734. var normals = [];
  24735. var uvs = [];
  24736. var row, col;
  24737. var width = options.width || 1;
  24738. var height = options.height || 1;
  24739. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  24740. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  24741. for (row = 0; row <= subdivisionsY; row++) {
  24742. for (col = 0; col <= subdivisionsX; col++) {
  24743. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  24744. var normal = new BABYLON.Vector3(0, 1.0, 0);
  24745. positions.push(position.x, position.y, position.z);
  24746. normals.push(normal.x, normal.y, normal.z);
  24747. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  24748. }
  24749. }
  24750. for (row = 0; row < subdivisionsY; row++) {
  24751. for (col = 0; col < subdivisionsX; col++) {
  24752. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  24753. indices.push(col + 1 + row * (subdivisionsX + 1));
  24754. indices.push(col + row * (subdivisionsX + 1));
  24755. indices.push(col + (row + 1) * (subdivisionsX + 1));
  24756. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  24757. indices.push(col + row * (subdivisionsX + 1));
  24758. }
  24759. }
  24760. // Result
  24761. var vertexData = new VertexData();
  24762. vertexData.indices = indices;
  24763. vertexData.positions = positions;
  24764. vertexData.normals = normals;
  24765. vertexData.uvs = uvs;
  24766. return vertexData;
  24767. };
  24768. /**
  24769. * Creates the VertexData of the TiledGround.
  24770. */
  24771. VertexData.CreateTiledGround = function (options) {
  24772. var xmin = options.xmin || -1.0;
  24773. var zmin = options.zmin || -1.0;
  24774. var xmax = options.xmax || 1.0;
  24775. var zmax = options.zmax || 1.0;
  24776. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  24777. var precision = options.precision || { w: 1, h: 1 };
  24778. var indices = [];
  24779. var positions = [];
  24780. var normals = [];
  24781. var uvs = [];
  24782. var row, col, tileRow, tileCol;
  24783. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  24784. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  24785. precision.w = (precision.w < 1) ? 1 : precision.w;
  24786. precision.h = (precision.h < 1) ? 1 : precision.h;
  24787. var tileSize = {
  24788. 'w': (xmax - xmin) / subdivisions.w,
  24789. 'h': (zmax - zmin) / subdivisions.h
  24790. };
  24791. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  24792. // Indices
  24793. var base = positions.length / 3;
  24794. var rowLength = precision.w + 1;
  24795. for (row = 0; row < precision.h; row++) {
  24796. for (col = 0; col < precision.w; col++) {
  24797. var square = [
  24798. base + col + row * rowLength,
  24799. base + (col + 1) + row * rowLength,
  24800. base + (col + 1) + (row + 1) * rowLength,
  24801. base + col + (row + 1) * rowLength
  24802. ];
  24803. indices.push(square[1]);
  24804. indices.push(square[2]);
  24805. indices.push(square[3]);
  24806. indices.push(square[0]);
  24807. indices.push(square[1]);
  24808. indices.push(square[3]);
  24809. }
  24810. }
  24811. // Position, normals and uvs
  24812. var position = BABYLON.Vector3.Zero();
  24813. var normal = new BABYLON.Vector3(0, 1.0, 0);
  24814. for (row = 0; row <= precision.h; row++) {
  24815. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  24816. for (col = 0; col <= precision.w; col++) {
  24817. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  24818. position.y = 0;
  24819. positions.push(position.x, position.y, position.z);
  24820. normals.push(normal.x, normal.y, normal.z);
  24821. uvs.push(col / precision.w, row / precision.h);
  24822. }
  24823. }
  24824. }
  24825. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  24826. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  24827. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  24828. }
  24829. }
  24830. // Result
  24831. var vertexData = new VertexData();
  24832. vertexData.indices = indices;
  24833. vertexData.positions = positions;
  24834. vertexData.normals = normals;
  24835. vertexData.uvs = uvs;
  24836. return vertexData;
  24837. };
  24838. /**
  24839. * Creates the VertexData of the Ground designed from a heightmap.
  24840. */
  24841. VertexData.CreateGroundFromHeightMap = function (options) {
  24842. var indices = [];
  24843. var positions = [];
  24844. var normals = [];
  24845. var uvs = [];
  24846. var row, col;
  24847. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  24848. // Vertices
  24849. for (row = 0; row <= options.subdivisions; row++) {
  24850. for (col = 0; col <= options.subdivisions; col++) {
  24851. 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));
  24852. // Compute height
  24853. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  24854. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  24855. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  24856. var r = options.buffer[pos] / 255.0;
  24857. var g = options.buffer[pos + 1] / 255.0;
  24858. var b = options.buffer[pos + 2] / 255.0;
  24859. var gradient = r * filter.r + g * filter.g + b * filter.b;
  24860. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  24861. // Add vertex
  24862. positions.push(position.x, position.y, position.z);
  24863. normals.push(0, 0, 0);
  24864. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  24865. }
  24866. }
  24867. // Indices
  24868. for (row = 0; row < options.subdivisions; row++) {
  24869. for (col = 0; col < options.subdivisions; col++) {
  24870. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  24871. indices.push(col + 1 + row * (options.subdivisions + 1));
  24872. indices.push(col + row * (options.subdivisions + 1));
  24873. indices.push(col + (row + 1) * (options.subdivisions + 1));
  24874. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  24875. indices.push(col + row * (options.subdivisions + 1));
  24876. }
  24877. }
  24878. // Normals
  24879. VertexData.ComputeNormals(positions, indices, normals);
  24880. // Result
  24881. var vertexData = new VertexData();
  24882. vertexData.indices = indices;
  24883. vertexData.positions = positions;
  24884. vertexData.normals = normals;
  24885. vertexData.uvs = uvs;
  24886. return vertexData;
  24887. };
  24888. /**
  24889. * Creates the VertexData of the Plane.
  24890. */
  24891. VertexData.CreatePlane = function (options) {
  24892. var indices = [];
  24893. var positions = [];
  24894. var normals = [];
  24895. var uvs = [];
  24896. var width = options.width || options.size || 1;
  24897. var height = options.height || options.size || 1;
  24898. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24899. // Vertices
  24900. var halfWidth = width / 2.0;
  24901. var halfHeight = height / 2.0;
  24902. positions.push(-halfWidth, -halfHeight, 0);
  24903. normals.push(0, 0, -1.0);
  24904. uvs.push(0.0, 0.0);
  24905. positions.push(halfWidth, -halfHeight, 0);
  24906. normals.push(0, 0, -1.0);
  24907. uvs.push(1.0, 0.0);
  24908. positions.push(halfWidth, halfHeight, 0);
  24909. normals.push(0, 0, -1.0);
  24910. uvs.push(1.0, 1.0);
  24911. positions.push(-halfWidth, halfHeight, 0);
  24912. normals.push(0, 0, -1.0);
  24913. uvs.push(0.0, 1.0);
  24914. // Indices
  24915. indices.push(0);
  24916. indices.push(1);
  24917. indices.push(2);
  24918. indices.push(0);
  24919. indices.push(2);
  24920. indices.push(3);
  24921. // Sides
  24922. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24923. // Result
  24924. var vertexData = new VertexData();
  24925. vertexData.indices = indices;
  24926. vertexData.positions = positions;
  24927. vertexData.normals = normals;
  24928. vertexData.uvs = uvs;
  24929. return vertexData;
  24930. };
  24931. /**
  24932. * Creates the VertexData of the Disc or regular Polygon.
  24933. */
  24934. VertexData.CreateDisc = function (options) {
  24935. var positions = [];
  24936. var indices = [];
  24937. var normals = [];
  24938. var uvs = [];
  24939. var radius = options.radius || 0.5;
  24940. var tessellation = options.tessellation || 64;
  24941. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  24942. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24943. // positions and uvs
  24944. positions.push(0, 0, 0); // disc center first
  24945. uvs.push(0.5, 0.5);
  24946. var theta = Math.PI * 2 * arc;
  24947. var step = theta / tessellation;
  24948. for (var a = 0; a < theta; a += step) {
  24949. var x = Math.cos(a);
  24950. var y = Math.sin(a);
  24951. var u = (x + 1) / 2;
  24952. var v = (1 - y) / 2;
  24953. positions.push(radius * x, radius * y, 0);
  24954. uvs.push(u, v);
  24955. }
  24956. if (arc === 1) {
  24957. positions.push(positions[3], positions[4], positions[5]); // close the circle
  24958. uvs.push(uvs[2], uvs[3]);
  24959. }
  24960. //indices
  24961. var vertexNb = positions.length / 3;
  24962. for (var i = 1; i < vertexNb - 1; i++) {
  24963. indices.push(i + 1, 0, i);
  24964. }
  24965. // result
  24966. VertexData.ComputeNormals(positions, indices, normals);
  24967. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24968. var vertexData = new VertexData();
  24969. vertexData.indices = indices;
  24970. vertexData.positions = positions;
  24971. vertexData.normals = normals;
  24972. vertexData.uvs = uvs;
  24973. return vertexData;
  24974. };
  24975. /**
  24976. * Creates the VertexData of the IcoSphere.
  24977. */
  24978. VertexData.CreateIcoSphere = function (options) {
  24979. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24980. var radius = options.radius || 1;
  24981. var flat = (options.flat === undefined) ? true : options.flat;
  24982. var subdivisions = options.subdivisions || 4;
  24983. var radiusX = options.radiusX || radius;
  24984. var radiusY = options.radiusY || radius;
  24985. var radiusZ = options.radiusZ || radius;
  24986. var t = (1 + Math.sqrt(5)) / 2;
  24987. // 12 vertex x,y,z
  24988. var ico_vertices = [
  24989. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  24990. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  24991. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  24992. ];
  24993. // index of 3 vertex makes a face of icopshere
  24994. var ico_indices = [
  24995. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  24996. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  24997. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  24998. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  24999. ];
  25000. // vertex for uv have aliased position, not for UV
  25001. var vertices_unalias_id = [
  25002. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  25003. // vertex alias
  25004. 0,
  25005. 2,
  25006. 3,
  25007. 3,
  25008. 3,
  25009. 4,
  25010. 7,
  25011. 8,
  25012. 9,
  25013. 9,
  25014. 10,
  25015. 11 // 23: B + 12
  25016. ];
  25017. // uv as integer step (not pixels !)
  25018. var ico_vertexuv = [
  25019. 5, 1, 3, 1, 6, 4, 0, 0,
  25020. 5, 3, 4, 2, 2, 2, 4, 0,
  25021. 2, 0, 1, 1, 6, 0, 6, 2,
  25022. // vertex alias (for same vertex on different faces)
  25023. 0, 4,
  25024. 3, 3,
  25025. 4, 4,
  25026. 3, 1,
  25027. 4, 2,
  25028. 4, 4,
  25029. 0, 2,
  25030. 1, 1,
  25031. 2, 2,
  25032. 3, 3,
  25033. 1, 3,
  25034. 2, 4 // 23: B + 12
  25035. ];
  25036. // Vertices[0, 1, ...9, A, B] : position on UV plane
  25037. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  25038. // First island of uv mapping
  25039. // v = 4h 3+ 2
  25040. // v = 3h 9+ 4
  25041. // v = 2h 9+ 5 B
  25042. // v = 1h 9 1 0
  25043. // v = 0h 3 8 7 A
  25044. // u = 0 1 2 3 4 5 6 *a
  25045. // Second island of uv mapping
  25046. // v = 4h 0+ B+ 4+
  25047. // v = 3h A+ 2+
  25048. // v = 2h 7+ 6 3+
  25049. // v = 1h 8+ 3+
  25050. // v = 0h
  25051. // u = 0 1 2 3 4 5 6 *a
  25052. // Face layout on texture UV mapping
  25053. // ============
  25054. // \ 4 /\ 16 / ======
  25055. // \ / \ / /\ 11 /
  25056. // \/ 7 \/ / \ /
  25057. // ======= / 10 \/
  25058. // /\ 17 /\ =======
  25059. // / \ / \ \ 15 /\
  25060. // / 8 \/ 12 \ \ / \
  25061. // ============ \/ 6 \
  25062. // \ 18 /\ ============
  25063. // \ / \ \ 5 /\ 0 /
  25064. // \/ 13 \ \ / \ /
  25065. // ======= \/ 1 \/
  25066. // =============
  25067. // /\ 19 /\ 2 /\
  25068. // / \ / \ / \
  25069. // / 14 \/ 9 \/ 3 \
  25070. // ===================
  25071. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  25072. var ustep = 138 / 1024;
  25073. var vstep = 239 / 1024;
  25074. var uoffset = 60 / 1024;
  25075. var voffset = 26 / 1024;
  25076. // Second island should have margin, not to touch the first island
  25077. // avoid any borderline artefact in pixel rounding
  25078. var island_u_offset = -40 / 1024;
  25079. var island_v_offset = +20 / 1024;
  25080. // face is either island 0 or 1 :
  25081. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  25082. var island = [
  25083. 0, 0, 0, 0, 1,
  25084. 0, 0, 1, 1, 0,
  25085. 0, 0, 1, 1, 0,
  25086. 0, 1, 1, 1, 0 // 15 - 19
  25087. ];
  25088. var indices = [];
  25089. var positions = [];
  25090. var normals = [];
  25091. var uvs = [];
  25092. var current_indice = 0;
  25093. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  25094. var face_vertex_pos = new Array(3);
  25095. var face_vertex_uv = new Array(3);
  25096. var v012;
  25097. for (v012 = 0; v012 < 3; v012++) {
  25098. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  25099. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  25100. }
  25101. // create all with normals
  25102. for (var face = 0; face < 20; face++) {
  25103. // 3 vertex per face
  25104. for (v012 = 0; v012 < 3; v012++) {
  25105. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  25106. var v_id = ico_indices[3 * face + v012];
  25107. // vertex have 3D position (x,y,z)
  25108. 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]);
  25109. // Normalize to get normal, then scale to radius
  25110. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  25111. // uv Coordinates from vertex ID
  25112. 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);
  25113. }
  25114. // Subdivide the face (interpolate pos, norm, uv)
  25115. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  25116. // - norm is linear interpolation of vertex corner normal
  25117. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  25118. // - uv is linear interpolation
  25119. //
  25120. // Topology is as below for sub-divide by 2
  25121. // vertex shown as v0,v1,v2
  25122. // interp index is i1 to progress in range [v0,v1[
  25123. // interp index is i2 to progress in range [v0,v2[
  25124. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  25125. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  25126. //
  25127. //
  25128. // i2 v2
  25129. // ^ ^
  25130. // / / \
  25131. // / / \
  25132. // / / \
  25133. // / / (0,1) \
  25134. // / #---------\
  25135. // / / \ (0,0)'/ \
  25136. // / / \ / \
  25137. // / / \ / \
  25138. // / / (0,0) \ / (1,0) \
  25139. // / #---------#---------\
  25140. // v0 v1
  25141. //
  25142. // --------------------> i1
  25143. //
  25144. // interp of (i1,i2):
  25145. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  25146. // along i1 : lerp(x0,x1, i1/(S-i2))
  25147. //
  25148. // centroid of triangle is needed to get help normal computation
  25149. // (c1,c2) are used for centroid location
  25150. var interp_vertex = function (i1, i2, c1, c2) {
  25151. // vertex is interpolated from
  25152. // - face_vertex_pos[0..2]
  25153. // - face_vertex_uv[0..2]
  25154. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  25155. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  25156. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  25157. pos_interp.normalize();
  25158. var vertex_normal;
  25159. if (flat) {
  25160. // in flat mode, recalculate normal as face centroid normal
  25161. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  25162. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  25163. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  25164. }
  25165. else {
  25166. // in smooth mode, recalculate normal from each single vertex position
  25167. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  25168. }
  25169. // Vertex normal need correction due to X,Y,Z radius scaling
  25170. vertex_normal.x /= radiusX;
  25171. vertex_normal.y /= radiusY;
  25172. vertex_normal.z /= radiusZ;
  25173. vertex_normal.normalize();
  25174. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  25175. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  25176. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  25177. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  25178. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  25179. uvs.push(uv_interp.x, uv_interp.y);
  25180. // push each vertex has member of a face
  25181. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  25182. indices.push(current_indice);
  25183. current_indice++;
  25184. };
  25185. for (var i2 = 0; i2 < subdivisions; i2++) {
  25186. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  25187. // face : (i1,i2) for /\ :
  25188. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  25189. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  25190. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  25191. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  25192. if (i1 + i2 + 1 < subdivisions) {
  25193. // face : (i1,i2)' for \/ :
  25194. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  25195. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  25196. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  25197. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  25198. }
  25199. }
  25200. }
  25201. }
  25202. // Sides
  25203. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25204. // Result
  25205. var vertexData = new VertexData();
  25206. vertexData.indices = indices;
  25207. vertexData.positions = positions;
  25208. vertexData.normals = normals;
  25209. vertexData.uvs = uvs;
  25210. return vertexData;
  25211. };
  25212. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  25213. /**
  25214. * Creates the VertexData of the Polyhedron.
  25215. */
  25216. VertexData.CreatePolyhedron = function (options) {
  25217. // provided polyhedron types :
  25218. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  25219. // 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)
  25220. var polyhedra = [];
  25221. 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]] };
  25222. 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]] };
  25223. polyhedra[2] = {
  25224. 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]],
  25225. 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]]
  25226. };
  25227. polyhedra[3] = {
  25228. 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]],
  25229. 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]]
  25230. };
  25231. polyhedra[4] = {
  25232. 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]],
  25233. 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]]
  25234. };
  25235. 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]] };
  25236. 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]] };
  25237. 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]] };
  25238. 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]] };
  25239. 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]] };
  25240. 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]] };
  25241. 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]] };
  25242. 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]] };
  25243. 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]] };
  25244. polyhedra[14] = {
  25245. 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]],
  25246. 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]]
  25247. };
  25248. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  25249. var size = options.size;
  25250. var sizeX = options.sizeX || size || 1;
  25251. var sizeY = options.sizeY || size || 1;
  25252. var sizeZ = options.sizeZ || size || 1;
  25253. var data = options.custom || polyhedra[type];
  25254. var nbfaces = data.face.length;
  25255. var faceUV = options.faceUV || new Array(nbfaces);
  25256. var faceColors = options.faceColors;
  25257. var flat = (options.flat === undefined) ? true : options.flat;
  25258. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25259. var positions = [];
  25260. var indices = [];
  25261. var normals = [];
  25262. var uvs = [];
  25263. var colors = [];
  25264. var index = 0;
  25265. var faceIdx = 0; // face cursor in the array "indexes"
  25266. var indexes = [];
  25267. var i = 0;
  25268. var f = 0;
  25269. var u, v, ang, x, y, tmp;
  25270. // default face colors and UV if undefined
  25271. if (flat) {
  25272. for (f = 0; f < nbfaces; f++) {
  25273. if (faceColors && faceColors[f] === undefined) {
  25274. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  25275. }
  25276. if (faceUV && faceUV[f] === undefined) {
  25277. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  25278. }
  25279. }
  25280. }
  25281. if (!flat) {
  25282. for (i = 0; i < data.vertex.length; i++) {
  25283. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  25284. uvs.push(0, 0);
  25285. }
  25286. for (f = 0; f < nbfaces; f++) {
  25287. for (i = 0; i < data.face[f].length - 2; i++) {
  25288. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  25289. }
  25290. }
  25291. }
  25292. else {
  25293. for (f = 0; f < nbfaces; f++) {
  25294. var fl = data.face[f].length; // number of vertices of the current face
  25295. ang = 2 * Math.PI / fl;
  25296. x = 0.5 * Math.tan(ang / 2);
  25297. y = 0.5;
  25298. // positions, uvs, colors
  25299. for (i = 0; i < fl; i++) {
  25300. // positions
  25301. 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);
  25302. indexes.push(index);
  25303. index++;
  25304. // uvs
  25305. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  25306. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  25307. uvs.push(u, v);
  25308. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  25309. y = x * Math.sin(ang) + y * Math.cos(ang);
  25310. x = tmp;
  25311. // colors
  25312. if (faceColors) {
  25313. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  25314. }
  25315. }
  25316. // indices from indexes
  25317. for (i = 0; i < fl - 2; i++) {
  25318. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  25319. }
  25320. faceIdx += fl;
  25321. }
  25322. }
  25323. VertexData.ComputeNormals(positions, indices, normals);
  25324. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25325. var vertexData = new VertexData();
  25326. vertexData.positions = positions;
  25327. vertexData.indices = indices;
  25328. vertexData.normals = normals;
  25329. vertexData.uvs = uvs;
  25330. if (faceColors && flat) {
  25331. vertexData.colors = colors;
  25332. }
  25333. return vertexData;
  25334. };
  25335. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  25336. /**
  25337. * Creates the VertexData of the Torus Knot.
  25338. */
  25339. VertexData.CreateTorusKnot = function (options) {
  25340. var indices = [];
  25341. var positions = [];
  25342. var normals = [];
  25343. var uvs = [];
  25344. var radius = options.radius || 2;
  25345. var tube = options.tube || 0.5;
  25346. var radialSegments = options.radialSegments || 32;
  25347. var tubularSegments = options.tubularSegments || 32;
  25348. var p = options.p || 2;
  25349. var q = options.q || 3;
  25350. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25351. // Helper
  25352. var getPos = function (angle) {
  25353. var cu = Math.cos(angle);
  25354. var su = Math.sin(angle);
  25355. var quOverP = q / p * angle;
  25356. var cs = Math.cos(quOverP);
  25357. var tx = radius * (2 + cs) * 0.5 * cu;
  25358. var ty = radius * (2 + cs) * su * 0.5;
  25359. var tz = radius * Math.sin(quOverP) * 0.5;
  25360. return new BABYLON.Vector3(tx, ty, tz);
  25361. };
  25362. // Vertices
  25363. var i;
  25364. var j;
  25365. for (i = 0; i <= radialSegments; i++) {
  25366. var modI = i % radialSegments;
  25367. var u = modI / radialSegments * 2 * p * Math.PI;
  25368. var p1 = getPos(u);
  25369. var p2 = getPos(u + 0.01);
  25370. var tang = p2.subtract(p1);
  25371. var n = p2.add(p1);
  25372. var bitan = BABYLON.Vector3.Cross(tang, n);
  25373. n = BABYLON.Vector3.Cross(bitan, tang);
  25374. bitan.normalize();
  25375. n.normalize();
  25376. for (j = 0; j < tubularSegments; j++) {
  25377. var modJ = j % tubularSegments;
  25378. var v = modJ / tubularSegments * 2 * Math.PI;
  25379. var cx = -tube * Math.cos(v);
  25380. var cy = tube * Math.sin(v);
  25381. positions.push(p1.x + cx * n.x + cy * bitan.x);
  25382. positions.push(p1.y + cx * n.y + cy * bitan.y);
  25383. positions.push(p1.z + cx * n.z + cy * bitan.z);
  25384. uvs.push(i / radialSegments);
  25385. uvs.push(j / tubularSegments);
  25386. }
  25387. }
  25388. for (i = 0; i < radialSegments; i++) {
  25389. for (j = 0; j < tubularSegments; j++) {
  25390. var jNext = (j + 1) % tubularSegments;
  25391. var a = i * tubularSegments + j;
  25392. var b = (i + 1) * tubularSegments + j;
  25393. var c = (i + 1) * tubularSegments + jNext;
  25394. var d = i * tubularSegments + jNext;
  25395. indices.push(d);
  25396. indices.push(b);
  25397. indices.push(a);
  25398. indices.push(d);
  25399. indices.push(c);
  25400. indices.push(b);
  25401. }
  25402. }
  25403. // Normals
  25404. VertexData.ComputeNormals(positions, indices, normals);
  25405. // Sides
  25406. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25407. // Result
  25408. var vertexData = new VertexData();
  25409. vertexData.indices = indices;
  25410. vertexData.positions = positions;
  25411. vertexData.normals = normals;
  25412. vertexData.uvs = uvs;
  25413. return vertexData;
  25414. };
  25415. // Tools
  25416. /**
  25417. * @param {any} - positions (number[] or Float32Array)
  25418. * @param {any} - indices (number[] or Uint16Array)
  25419. * @param {any} - normals (number[] or Float32Array)
  25420. * options (optional) :
  25421. * facetPositions : optional array of facet positions (vector3)
  25422. * facetNormals : optional array of facet normals (vector3)
  25423. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  25424. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  25425. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  25426. * bbSize : optional bounding box size data, required for facetPartitioning computation
  25427. * bInfo : optional bounding info, required for facetPartitioning computation
  25428. */
  25429. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  25430. // temporary scalar variables
  25431. var index = 0; // facet index
  25432. var p1p2x = 0.0; // p1p2 vector x coordinate
  25433. var p1p2y = 0.0; // p1p2 vector y coordinate
  25434. var p1p2z = 0.0; // p1p2 vector z coordinate
  25435. var p3p2x = 0.0; // p3p2 vector x coordinate
  25436. var p3p2y = 0.0; // p3p2 vector y coordinate
  25437. var p3p2z = 0.0; // p3p2 vector z coordinate
  25438. var faceNormalx = 0.0; // facet normal x coordinate
  25439. var faceNormaly = 0.0; // facet normal y coordinate
  25440. var faceNormalz = 0.0; // facet normal z coordinate
  25441. var length = 0.0; // facet normal length before normalization
  25442. var v1x = 0; // vector1 x index in the positions array
  25443. var v1y = 0; // vector1 y index in the positions array
  25444. var v1z = 0; // vector1 z index in the positions array
  25445. var v2x = 0; // vector2 x index in the positions array
  25446. var v2y = 0; // vector2 y index in the positions array
  25447. var v2z = 0; // vector2 z index in the positions array
  25448. var v3x = 0; // vector3 x index in the positions array
  25449. var v3y = 0; // vector3 y index in the positions array
  25450. var v3z = 0; // vector3 z index in the positions array
  25451. var computeFacetNormals = false;
  25452. var computeFacetPositions = false;
  25453. var computeFacetPartitioning = false;
  25454. if (options) {
  25455. computeFacetNormals = (options.facetNormals) ? true : false;
  25456. computeFacetPositions = (options.facetPositions) ? true : false;
  25457. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  25458. }
  25459. // facetPartitioning reinit if needed
  25460. if (computeFacetPartitioning) {
  25461. var ox = 0; // X partitioning index for facet position
  25462. var oy = 0; // Y partinioning index for facet position
  25463. var oz = 0; // Z partinioning index for facet position
  25464. var b1x = 0; // X partitioning index for facet v1 vertex
  25465. var b1y = 0; // Y partitioning index for facet v1 vertex
  25466. var b1z = 0; // z partitioning index for facet v1 vertex
  25467. var b2x = 0; // X partitioning index for facet v2 vertex
  25468. var b2y = 0; // Y partitioning index for facet v2 vertex
  25469. var b2z = 0; // Z partitioning index for facet v2 vertex
  25470. var b3x = 0; // X partitioning index for facet v3 vertex
  25471. var b3y = 0; // Y partitioning index for facet v3 vertex
  25472. var b3z = 0; // Z partitioning index for facet v3 vertex
  25473. var block_idx_o = 0; // facet barycenter block index
  25474. var block_idx_v1 = 0; // v1 vertex block index
  25475. var block_idx_v2 = 0; // v2 vertex block index
  25476. var block_idx_v3 = 0; // v3 vertex block index
  25477. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  25478. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  25479. var xSubRatio = options.subDiv.X * options.ratio / options.bbSize.x;
  25480. var ySubRatio = options.subDiv.Y * options.ratio / options.bbSize.y;
  25481. var zSubRatio = options.subDiv.Z * options.ratio / options.bbSize.z;
  25482. var subSq = options.subDiv.max * options.subDiv.max;
  25483. options.facetPartitioning.length = 0;
  25484. }
  25485. // reset the normals
  25486. for (index = 0; index < positions.length; index++) {
  25487. normals[index] = 0.0;
  25488. }
  25489. // Loop : 1 indice triplet = 1 facet
  25490. var nbFaces = indices.length / 3;
  25491. for (index = 0; index < nbFaces; index++) {
  25492. // get the indexes of the coordinates of each vertex of the facet
  25493. v1x = indices[index * 3] * 3;
  25494. v1y = v1x + 1;
  25495. v1z = v1x + 2;
  25496. v2x = indices[index * 3 + 1] * 3;
  25497. v2y = v2x + 1;
  25498. v2z = v2x + 2;
  25499. v3x = indices[index * 3 + 2] * 3;
  25500. v3y = v3x + 1;
  25501. v3z = v3x + 2;
  25502. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  25503. p1p2y = positions[v1y] - positions[v2y];
  25504. p1p2z = positions[v1z] - positions[v2z];
  25505. p3p2x = positions[v3x] - positions[v2x];
  25506. p3p2y = positions[v3y] - positions[v2y];
  25507. p3p2z = positions[v3z] - positions[v2z];
  25508. // compute the face normal with the cross product
  25509. faceNormalx = p1p2y * p3p2z - p1p2z * p3p2y;
  25510. faceNormaly = p1p2z * p3p2x - p1p2x * p3p2z;
  25511. faceNormalz = p1p2x * p3p2y - p1p2y * p3p2x;
  25512. // normalize this normal and store it in the array facetData
  25513. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  25514. length = (length === 0) ? 1.0 : length;
  25515. faceNormalx /= length;
  25516. faceNormaly /= length;
  25517. faceNormalz /= length;
  25518. if (computeFacetNormals) {
  25519. options.facetNormals[index].x = faceNormalx;
  25520. options.facetNormals[index].y = faceNormaly;
  25521. options.facetNormals[index].z = faceNormalz;
  25522. }
  25523. if (computeFacetPositions) {
  25524. // compute and the facet barycenter coordinates in the array facetPositions
  25525. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  25526. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  25527. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  25528. }
  25529. if (computeFacetPartitioning) {
  25530. // store the facet indexes in arrays in the main facetPartitioning array :
  25531. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  25532. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  25533. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  25534. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  25535. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  25536. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  25537. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  25538. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  25539. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  25540. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  25541. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  25542. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  25543. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  25544. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  25545. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  25546. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  25547. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  25548. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  25549. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  25550. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  25551. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  25552. // push each facet index in each block containing the vertex
  25553. options.facetPartitioning[block_idx_v1].push(index);
  25554. if (block_idx_v2 != block_idx_v1) {
  25555. options.facetPartitioning[block_idx_v2].push(index);
  25556. }
  25557. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  25558. options.facetPartitioning[block_idx_v3].push(index);
  25559. }
  25560. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  25561. options.facetPartitioning[block_idx_o].push(index);
  25562. }
  25563. }
  25564. // compute the normals anyway
  25565. normals[v1x] += faceNormalx; // accumulate all the normals per face
  25566. normals[v1y] += faceNormaly;
  25567. normals[v1z] += faceNormalz;
  25568. normals[v2x] += faceNormalx;
  25569. normals[v2y] += faceNormaly;
  25570. normals[v2z] += faceNormalz;
  25571. normals[v3x] += faceNormalx;
  25572. normals[v3y] += faceNormaly;
  25573. normals[v3z] += faceNormalz;
  25574. }
  25575. // last normalization of each normal
  25576. for (index = 0; index < normals.length / 3; index++) {
  25577. faceNormalx = normals[index * 3];
  25578. faceNormaly = normals[index * 3 + 1];
  25579. faceNormalz = normals[index * 3 + 2];
  25580. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  25581. length = (length === 0) ? 1.0 : length;
  25582. faceNormalx /= length;
  25583. faceNormaly /= length;
  25584. faceNormalz /= length;
  25585. normals[index * 3] = faceNormalx;
  25586. normals[index * 3 + 1] = faceNormaly;
  25587. normals[index * 3 + 2] = faceNormalz;
  25588. }
  25589. };
  25590. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  25591. var li = indices.length;
  25592. var ln = normals.length;
  25593. var i;
  25594. var n;
  25595. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25596. switch (sideOrientation) {
  25597. case BABYLON.Mesh.FRONTSIDE:
  25598. // nothing changed
  25599. break;
  25600. case BABYLON.Mesh.BACKSIDE:
  25601. var tmp;
  25602. // indices
  25603. for (i = 0; i < li; i += 3) {
  25604. tmp = indices[i];
  25605. indices[i] = indices[i + 2];
  25606. indices[i + 2] = tmp;
  25607. }
  25608. // normals
  25609. for (n = 0; n < ln; n++) {
  25610. normals[n] = -normals[n];
  25611. }
  25612. break;
  25613. case BABYLON.Mesh.DOUBLESIDE:
  25614. // positions
  25615. var lp = positions.length;
  25616. var l = lp / 3;
  25617. for (var p = 0; p < lp; p++) {
  25618. positions[lp + p] = positions[p];
  25619. }
  25620. // indices
  25621. for (i = 0; i < li; i += 3) {
  25622. indices[i + li] = indices[i + 2] + l;
  25623. indices[i + 1 + li] = indices[i + 1] + l;
  25624. indices[i + 2 + li] = indices[i] + l;
  25625. }
  25626. // normals
  25627. for (n = 0; n < ln; n++) {
  25628. normals[ln + n] = -normals[n];
  25629. }
  25630. // uvs
  25631. var lu = uvs.length;
  25632. for (var u = 0; u < lu; u++) {
  25633. uvs[u + lu] = uvs[u];
  25634. }
  25635. break;
  25636. }
  25637. };
  25638. /**
  25639. * Creates a new VertexData from the imported parameters.
  25640. */
  25641. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  25642. var vertexData = new VertexData();
  25643. // positions
  25644. var positions = parsedVertexData.positions;
  25645. if (positions) {
  25646. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  25647. }
  25648. // normals
  25649. var normals = parsedVertexData.normals;
  25650. if (normals) {
  25651. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  25652. }
  25653. // tangents
  25654. var tangents = parsedVertexData.tangents;
  25655. if (tangents) {
  25656. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  25657. }
  25658. // uvs
  25659. var uvs = parsedVertexData.uvs;
  25660. if (uvs) {
  25661. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  25662. }
  25663. // uv2s
  25664. var uv2s = parsedVertexData.uv2s;
  25665. if (uv2s) {
  25666. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  25667. }
  25668. // uv3s
  25669. var uv3s = parsedVertexData.uv3s;
  25670. if (uv3s) {
  25671. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  25672. }
  25673. // uv4s
  25674. var uv4s = parsedVertexData.uv4s;
  25675. if (uv4s) {
  25676. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  25677. }
  25678. // uv5s
  25679. var uv5s = parsedVertexData.uv5s;
  25680. if (uv5s) {
  25681. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  25682. }
  25683. // uv6s
  25684. var uv6s = parsedVertexData.uv6s;
  25685. if (uv6s) {
  25686. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  25687. }
  25688. // colors
  25689. var colors = parsedVertexData.colors;
  25690. if (colors) {
  25691. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  25692. }
  25693. // matricesIndices
  25694. var matricesIndices = parsedVertexData.matricesIndices;
  25695. if (matricesIndices) {
  25696. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  25697. }
  25698. // matricesWeights
  25699. var matricesWeights = parsedVertexData.matricesWeights;
  25700. if (matricesWeights) {
  25701. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  25702. }
  25703. // indices
  25704. var indices = parsedVertexData.indices;
  25705. if (indices) {
  25706. vertexData.indices = indices;
  25707. }
  25708. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  25709. };
  25710. return VertexData;
  25711. }());
  25712. BABYLON.VertexData = VertexData;
  25713. })(BABYLON || (BABYLON = {}));
  25714. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  25715. var BABYLON;
  25716. (function (BABYLON) {
  25717. var Geometry = (function () {
  25718. function Geometry(id, scene, vertexData, updatable, mesh) {
  25719. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  25720. this._totalVertices = 0;
  25721. this._isDisposed = false;
  25722. this.id = id;
  25723. this._engine = scene.getEngine();
  25724. this._meshes = [];
  25725. this._scene = scene;
  25726. //Init vertex buffer cache
  25727. this._vertexBuffers = {};
  25728. this._indices = [];
  25729. // vertexData
  25730. if (vertexData) {
  25731. this.setAllVerticesData(vertexData, updatable);
  25732. }
  25733. else {
  25734. this._totalVertices = 0;
  25735. this._indices = [];
  25736. }
  25737. if (this._engine.getCaps().vertexArrayObject) {
  25738. this._vertexArrayObjects = {};
  25739. }
  25740. // applyToMesh
  25741. if (mesh) {
  25742. if (mesh.getClassName() === "LinesMesh") {
  25743. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  25744. this.updateExtend();
  25745. }
  25746. this.applyToMesh(mesh);
  25747. mesh.computeWorldMatrix(true);
  25748. }
  25749. }
  25750. Object.defineProperty(Geometry.prototype, "boundingBias", {
  25751. /**
  25752. * 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
  25753. * @returns The Bias Vector
  25754. */
  25755. get: function () {
  25756. return this._boundingBias;
  25757. },
  25758. set: function (value) {
  25759. if (this._boundingBias && this._boundingBias.equals(value)) {
  25760. return;
  25761. }
  25762. this._boundingBias = value.clone();
  25763. this.updateBoundingInfo(true, null);
  25764. },
  25765. enumerable: true,
  25766. configurable: true
  25767. });
  25768. Object.defineProperty(Geometry.prototype, "extend", {
  25769. get: function () {
  25770. return this._extend;
  25771. },
  25772. enumerable: true,
  25773. configurable: true
  25774. });
  25775. Geometry.prototype.getScene = function () {
  25776. return this._scene;
  25777. };
  25778. Geometry.prototype.getEngine = function () {
  25779. return this._engine;
  25780. };
  25781. Geometry.prototype.isReady = function () {
  25782. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  25783. };
  25784. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  25785. get: function () {
  25786. for (var index = 0; index < this._meshes.length; index++) {
  25787. if (!this._meshes[index].doNotSerialize) {
  25788. return false;
  25789. }
  25790. }
  25791. return true;
  25792. },
  25793. enumerable: true,
  25794. configurable: true
  25795. });
  25796. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  25797. vertexData.applyToGeometry(this, updatable);
  25798. this.notifyUpdate();
  25799. };
  25800. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  25801. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  25802. this.setVerticesBuffer(buffer);
  25803. };
  25804. Geometry.prototype.removeVerticesData = function (kind) {
  25805. if (this._vertexBuffers[kind]) {
  25806. this._vertexBuffers[kind].dispose();
  25807. delete this._vertexBuffers[kind];
  25808. }
  25809. };
  25810. Geometry.prototype.setVerticesBuffer = function (buffer) {
  25811. var kind = buffer.getKind();
  25812. if (this._vertexBuffers[kind]) {
  25813. this._vertexBuffers[kind].dispose();
  25814. }
  25815. this._vertexBuffers[kind] = buffer;
  25816. if (kind === BABYLON.VertexBuffer.PositionKind) {
  25817. var data = buffer.getData();
  25818. var stride = buffer.getStrideSize();
  25819. this._totalVertices = data.length / stride;
  25820. this.updateExtend(data, stride);
  25821. var meshes = this._meshes;
  25822. var numOfMeshes = meshes.length;
  25823. for (var index = 0; index < numOfMeshes; index++) {
  25824. var mesh = meshes[index];
  25825. mesh._resetPointsArrayCache();
  25826. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  25827. mesh._createGlobalSubMesh();
  25828. mesh.computeWorldMatrix(true);
  25829. }
  25830. }
  25831. this.notifyUpdate(kind);
  25832. if (this._vertexArrayObjects) {
  25833. this._disposeVertexArrayObjects();
  25834. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  25835. }
  25836. };
  25837. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  25838. var vertexBuffer = this.getVertexBuffer(kind);
  25839. if (!vertexBuffer) {
  25840. return;
  25841. }
  25842. vertexBuffer.updateDirectly(data, offset);
  25843. this.notifyUpdate(kind);
  25844. };
  25845. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  25846. var vertexBuffer = this.getVertexBuffer(kind);
  25847. if (!vertexBuffer) {
  25848. return;
  25849. }
  25850. vertexBuffer.update(data);
  25851. if (kind === BABYLON.VertexBuffer.PositionKind) {
  25852. var stride = vertexBuffer.getStrideSize();
  25853. this._totalVertices = data.length / stride;
  25854. this.updateBoundingInfo(updateExtends, data);
  25855. }
  25856. this.notifyUpdate(kind);
  25857. };
  25858. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  25859. if (updateExtends) {
  25860. this.updateExtend(data);
  25861. }
  25862. var meshes = this._meshes;
  25863. var numOfMeshes = meshes.length;
  25864. for (var index = 0; index < numOfMeshes; index++) {
  25865. var mesh = meshes[index];
  25866. mesh._resetPointsArrayCache();
  25867. if (updateExtends) {
  25868. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  25869. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  25870. var subMesh = mesh.subMeshes[subIndex];
  25871. subMesh.refreshBoundingInfo();
  25872. }
  25873. }
  25874. }
  25875. };
  25876. Geometry.prototype._bind = function (effect, indexToBind) {
  25877. if (indexToBind === void 0) { indexToBind = undefined; }
  25878. if (indexToBind === undefined) {
  25879. indexToBind = this._indexBuffer;
  25880. }
  25881. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  25882. this._engine.bindBuffers(this.getVertexBuffers(), indexToBind, effect);
  25883. return;
  25884. }
  25885. // Using VAO
  25886. if (!this._vertexArrayObjects[effect.key]) {
  25887. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(this.getVertexBuffers(), indexToBind, effect);
  25888. }
  25889. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  25890. };
  25891. Geometry.prototype.getTotalVertices = function () {
  25892. if (!this.isReady()) {
  25893. return 0;
  25894. }
  25895. return this._totalVertices;
  25896. };
  25897. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  25898. var vertexBuffer = this.getVertexBuffer(kind);
  25899. if (!vertexBuffer) {
  25900. return null;
  25901. }
  25902. var orig = vertexBuffer.getData();
  25903. if (!copyWhenShared || this._meshes.length === 1) {
  25904. return orig;
  25905. }
  25906. else {
  25907. var len = orig.length;
  25908. var copy = [];
  25909. for (var i = 0; i < len; i++) {
  25910. copy.push(orig[i]);
  25911. }
  25912. return copy;
  25913. }
  25914. };
  25915. Geometry.prototype.getVertexBuffer = function (kind) {
  25916. if (!this.isReady()) {
  25917. return null;
  25918. }
  25919. return this._vertexBuffers[kind];
  25920. };
  25921. Geometry.prototype.getVertexBuffers = function () {
  25922. if (!this.isReady()) {
  25923. return null;
  25924. }
  25925. return this._vertexBuffers;
  25926. };
  25927. Geometry.prototype.isVerticesDataPresent = function (kind) {
  25928. if (!this._vertexBuffers) {
  25929. if (this._delayInfo) {
  25930. return this._delayInfo.indexOf(kind) !== -1;
  25931. }
  25932. return false;
  25933. }
  25934. return this._vertexBuffers[kind] !== undefined;
  25935. };
  25936. Geometry.prototype.getVerticesDataKinds = function () {
  25937. var result = [];
  25938. var kind;
  25939. if (!this._vertexBuffers && this._delayInfo) {
  25940. for (kind in this._delayInfo) {
  25941. result.push(kind);
  25942. }
  25943. }
  25944. else {
  25945. for (kind in this._vertexBuffers) {
  25946. result.push(kind);
  25947. }
  25948. }
  25949. return result;
  25950. };
  25951. Geometry.prototype.setIndices = function (indices, totalVertices) {
  25952. if (this._indexBuffer) {
  25953. this._engine._releaseBuffer(this._indexBuffer);
  25954. }
  25955. this._disposeVertexArrayObjects();
  25956. this._indices = indices;
  25957. if (this._meshes.length !== 0 && this._indices) {
  25958. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  25959. }
  25960. if (totalVertices !== undefined) {
  25961. this._totalVertices = totalVertices;
  25962. }
  25963. var meshes = this._meshes;
  25964. var numOfMeshes = meshes.length;
  25965. for (var index = 0; index < numOfMeshes; index++) {
  25966. meshes[index]._createGlobalSubMesh();
  25967. }
  25968. this.notifyUpdate();
  25969. };
  25970. Geometry.prototype.getTotalIndices = function () {
  25971. if (!this.isReady()) {
  25972. return 0;
  25973. }
  25974. return this._indices.length;
  25975. };
  25976. Geometry.prototype.getIndices = function (copyWhenShared) {
  25977. if (!this.isReady()) {
  25978. return null;
  25979. }
  25980. var orig = this._indices;
  25981. if (!copyWhenShared || this._meshes.length === 1) {
  25982. return orig;
  25983. }
  25984. else {
  25985. var len = orig.length;
  25986. var copy = [];
  25987. for (var i = 0; i < len; i++) {
  25988. copy.push(orig[i]);
  25989. }
  25990. return copy;
  25991. }
  25992. };
  25993. Geometry.prototype.getIndexBuffer = function () {
  25994. if (!this.isReady()) {
  25995. return null;
  25996. }
  25997. return this._indexBuffer;
  25998. };
  25999. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  26000. if (!effect || !this._vertexArrayObjects) {
  26001. return;
  26002. }
  26003. if (this._vertexArrayObjects[effect.key]) {
  26004. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  26005. delete this._vertexArrayObjects[effect.key];
  26006. }
  26007. };
  26008. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  26009. var meshes = this._meshes;
  26010. var index = meshes.indexOf(mesh);
  26011. if (index === -1) {
  26012. return;
  26013. }
  26014. meshes.splice(index, 1);
  26015. mesh._geometry = null;
  26016. if (meshes.length === 0 && shouldDispose) {
  26017. this.dispose();
  26018. }
  26019. };
  26020. Geometry.prototype.applyToMesh = function (mesh) {
  26021. if (mesh._geometry === this) {
  26022. return;
  26023. }
  26024. var previousGeometry = mesh._geometry;
  26025. if (previousGeometry) {
  26026. previousGeometry.releaseForMesh(mesh);
  26027. }
  26028. var meshes = this._meshes;
  26029. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  26030. mesh._geometry = this;
  26031. this._scene.pushGeometry(this);
  26032. meshes.push(mesh);
  26033. if (this.isReady()) {
  26034. this._applyToMesh(mesh);
  26035. }
  26036. else {
  26037. mesh._boundingInfo = this._boundingInfo;
  26038. }
  26039. };
  26040. Geometry.prototype.updateExtend = function (data, stride) {
  26041. if (data === void 0) { data = null; }
  26042. if (!data) {
  26043. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  26044. }
  26045. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  26046. };
  26047. Geometry.prototype._applyToMesh = function (mesh) {
  26048. var numOfMeshes = this._meshes.length;
  26049. // vertexBuffers
  26050. for (var kind in this._vertexBuffers) {
  26051. if (numOfMeshes === 1) {
  26052. this._vertexBuffers[kind].create();
  26053. }
  26054. var buffer = this._vertexBuffers[kind].getBuffer();
  26055. if (buffer)
  26056. buffer.references = numOfMeshes;
  26057. if (kind === BABYLON.VertexBuffer.PositionKind) {
  26058. mesh._resetPointsArrayCache();
  26059. if (!this._extend) {
  26060. this.updateExtend(this._vertexBuffers[kind].getData());
  26061. }
  26062. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  26063. mesh._createGlobalSubMesh();
  26064. //bounding info was just created again, world matrix should be applied again.
  26065. mesh._updateBoundingInfo();
  26066. }
  26067. }
  26068. // indexBuffer
  26069. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  26070. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  26071. }
  26072. if (this._indexBuffer) {
  26073. this._indexBuffer.references = numOfMeshes;
  26074. }
  26075. };
  26076. Geometry.prototype.notifyUpdate = function (kind) {
  26077. if (this.onGeometryUpdated) {
  26078. this.onGeometryUpdated(this, kind);
  26079. }
  26080. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  26081. var mesh = _a[_i];
  26082. mesh._markSubMeshesAsAttributesDirty();
  26083. }
  26084. };
  26085. Geometry.prototype.load = function (scene, onLoaded) {
  26086. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  26087. return;
  26088. }
  26089. if (this.isReady()) {
  26090. if (onLoaded) {
  26091. onLoaded();
  26092. }
  26093. return;
  26094. }
  26095. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  26096. this._queueLoad(scene, onLoaded);
  26097. };
  26098. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  26099. var _this = this;
  26100. scene._addPendingData(this);
  26101. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  26102. _this._delayLoadingFunction(JSON.parse(data), _this);
  26103. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  26104. _this._delayInfo = [];
  26105. scene._removePendingData(_this);
  26106. var meshes = _this._meshes;
  26107. var numOfMeshes = meshes.length;
  26108. for (var index = 0; index < numOfMeshes; index++) {
  26109. _this._applyToMesh(meshes[index]);
  26110. }
  26111. if (onLoaded) {
  26112. onLoaded();
  26113. }
  26114. }, function () { }, scene.database);
  26115. };
  26116. /**
  26117. * Invert the geometry to move from a right handed system to a left handed one.
  26118. */
  26119. Geometry.prototype.toLeftHanded = function () {
  26120. // Flip faces
  26121. var tIndices = this.getIndices(false);
  26122. if (tIndices != null && tIndices.length > 0) {
  26123. for (var i = 0; i < tIndices.length; i += 3) {
  26124. var tTemp = tIndices[i + 0];
  26125. tIndices[i + 0] = tIndices[i + 2];
  26126. tIndices[i + 2] = tTemp;
  26127. }
  26128. this.setIndices(tIndices);
  26129. }
  26130. // Negate position.z
  26131. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  26132. if (tPositions != null && tPositions.length > 0) {
  26133. for (var i = 0; i < tPositions.length; i += 3) {
  26134. tPositions[i + 2] = -tPositions[i + 2];
  26135. }
  26136. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  26137. }
  26138. // Negate normal.z
  26139. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  26140. if (tNormals != null && tNormals.length > 0) {
  26141. for (var i = 0; i < tNormals.length; i += 3) {
  26142. tNormals[i + 2] = -tNormals[i + 2];
  26143. }
  26144. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  26145. }
  26146. };
  26147. Geometry.prototype.isDisposed = function () {
  26148. return this._isDisposed;
  26149. };
  26150. Geometry.prototype._disposeVertexArrayObjects = function () {
  26151. if (this._vertexArrayObjects) {
  26152. for (var kind in this._vertexArrayObjects) {
  26153. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  26154. }
  26155. this._vertexArrayObjects = {};
  26156. }
  26157. };
  26158. Geometry.prototype.dispose = function () {
  26159. var meshes = this._meshes;
  26160. var numOfMeshes = meshes.length;
  26161. var index;
  26162. for (index = 0; index < numOfMeshes; index++) {
  26163. this.releaseForMesh(meshes[index]);
  26164. }
  26165. this._meshes = [];
  26166. this._disposeVertexArrayObjects();
  26167. for (var kind in this._vertexBuffers) {
  26168. this._vertexBuffers[kind].dispose();
  26169. }
  26170. this._vertexBuffers = {};
  26171. this._totalVertices = 0;
  26172. if (this._indexBuffer) {
  26173. this._engine._releaseBuffer(this._indexBuffer);
  26174. }
  26175. this._indexBuffer = null;
  26176. this._indices = [];
  26177. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26178. this.delayLoadingFile = null;
  26179. this._delayLoadingFunction = null;
  26180. this._delayInfo = [];
  26181. this._boundingInfo = null;
  26182. this._scene.removeGeometry(this);
  26183. this._isDisposed = true;
  26184. };
  26185. Geometry.prototype.copy = function (id) {
  26186. var vertexData = new BABYLON.VertexData();
  26187. vertexData.indices = [];
  26188. var indices = this.getIndices();
  26189. for (var index = 0; index < indices.length; index++) {
  26190. vertexData.indices.push(indices[index]);
  26191. }
  26192. var updatable = false;
  26193. var stopChecking = false;
  26194. var kind;
  26195. for (kind in this._vertexBuffers) {
  26196. // using slice() to make a copy of the array and not just reference it
  26197. var data = this.getVerticesData(kind);
  26198. if (data instanceof Float32Array) {
  26199. vertexData.set(new Float32Array(data), kind);
  26200. }
  26201. else {
  26202. vertexData.set(data.slice(0), kind);
  26203. }
  26204. if (!stopChecking) {
  26205. updatable = this.getVertexBuffer(kind).isUpdatable();
  26206. stopChecking = !updatable;
  26207. }
  26208. }
  26209. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  26210. geometry.delayLoadState = this.delayLoadState;
  26211. geometry.delayLoadingFile = this.delayLoadingFile;
  26212. geometry._delayLoadingFunction = this._delayLoadingFunction;
  26213. for (kind in this._delayInfo) {
  26214. geometry._delayInfo = geometry._delayInfo || [];
  26215. geometry._delayInfo.push(kind);
  26216. }
  26217. // Bounding info
  26218. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  26219. return geometry;
  26220. };
  26221. Geometry.prototype.serialize = function () {
  26222. var serializationObject = {};
  26223. serializationObject.id = this.id;
  26224. if (BABYLON.Tags.HasTags(this)) {
  26225. serializationObject.tags = BABYLON.Tags.GetTags(this);
  26226. }
  26227. return serializationObject;
  26228. };
  26229. Geometry.prototype.serializeVerticeData = function () {
  26230. var serializationObject = this.serialize();
  26231. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  26232. serializationObject.positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26233. if (this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable) {
  26234. serializationObject.positions._updatable = true;
  26235. }
  26236. }
  26237. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  26238. serializationObject.normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26239. if (this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable) {
  26240. serializationObject.normals._updatable = true;
  26241. }
  26242. }
  26243. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  26244. serializationObject.uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  26245. if (this.getVertexBuffer(BABYLON.VertexBuffer.UVKind).isUpdatable) {
  26246. serializationObject.uvs._updatable = true;
  26247. }
  26248. }
  26249. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  26250. serializationObject.uv2s = this.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  26251. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV2Kind).isUpdatable) {
  26252. serializationObject.uv2s._updatable = true;
  26253. }
  26254. }
  26255. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  26256. serializationObject.uv3s = this.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  26257. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV3Kind).isUpdatable) {
  26258. serializationObject.uv3s._updatable = true;
  26259. }
  26260. }
  26261. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  26262. serializationObject.uv4s = this.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  26263. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV4Kind).isUpdatable) {
  26264. serializationObject.uv4s._updatable = true;
  26265. }
  26266. }
  26267. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  26268. serializationObject.uv5s = this.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  26269. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV5Kind).isUpdatable) {
  26270. serializationObject.uv5s._updatable = true;
  26271. }
  26272. }
  26273. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  26274. serializationObject.uv6s = this.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  26275. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV6Kind).isUpdatable) {
  26276. serializationObject.uv6s._updatable = true;
  26277. }
  26278. }
  26279. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  26280. serializationObject.colors = this.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  26281. if (this.getVertexBuffer(BABYLON.VertexBuffer.ColorKind).isUpdatable) {
  26282. serializationObject.colors._updatable = true;
  26283. }
  26284. }
  26285. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  26286. serializationObject.matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  26287. serializationObject.matricesIndices._isExpanded = true;
  26288. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesIndicesKind).isUpdatable) {
  26289. serializationObject.matricesIndices._updatable = true;
  26290. }
  26291. }
  26292. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  26293. serializationObject.matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  26294. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesWeightsKind).isUpdatable) {
  26295. serializationObject.matricesWeights._updatable = true;
  26296. }
  26297. }
  26298. serializationObject.indices = this.getIndices();
  26299. return serializationObject;
  26300. };
  26301. // Statics
  26302. Geometry.ExtractFromMesh = function (mesh, id) {
  26303. var geometry = mesh._geometry;
  26304. if (!geometry) {
  26305. return null;
  26306. }
  26307. return geometry.copy(id);
  26308. };
  26309. /**
  26310. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  26311. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  26312. * Be aware Math.random() could cause collisions, but:
  26313. * "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"
  26314. */
  26315. Geometry.RandomId = function () {
  26316. return BABYLON.Tools.RandomId();
  26317. };
  26318. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  26319. var scene = mesh.getScene();
  26320. // Geometry
  26321. var geometryId = parsedGeometry.geometryId;
  26322. if (geometryId) {
  26323. var geometry = scene.getGeometryByID(geometryId);
  26324. if (geometry) {
  26325. geometry.applyToMesh(mesh);
  26326. }
  26327. }
  26328. else if (parsedGeometry instanceof ArrayBuffer) {
  26329. var binaryInfo = mesh._binaryInfo;
  26330. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  26331. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  26332. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  26333. }
  26334. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  26335. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  26336. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  26337. }
  26338. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  26339. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  26340. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  26341. }
  26342. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  26343. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  26344. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  26345. }
  26346. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  26347. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  26348. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  26349. }
  26350. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  26351. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  26352. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  26353. }
  26354. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  26355. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  26356. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  26357. }
  26358. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  26359. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  26360. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  26361. }
  26362. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  26363. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  26364. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  26365. }
  26366. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  26367. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  26368. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  26369. }
  26370. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  26371. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  26372. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  26373. }
  26374. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  26375. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  26376. mesh.setIndices(indicesData);
  26377. }
  26378. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  26379. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  26380. mesh.subMeshes = [];
  26381. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  26382. var materialIndex = subMeshesData[(i * 5) + 0];
  26383. var verticesStart = subMeshesData[(i * 5) + 1];
  26384. var verticesCount = subMeshesData[(i * 5) + 2];
  26385. var indexStart = subMeshesData[(i * 5) + 3];
  26386. var indexCount = subMeshesData[(i * 5) + 4];
  26387. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  26388. }
  26389. }
  26390. }
  26391. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  26392. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  26393. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  26394. if (parsedGeometry.uvs) {
  26395. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  26396. }
  26397. if (parsedGeometry.uvs2) {
  26398. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  26399. }
  26400. if (parsedGeometry.uvs3) {
  26401. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  26402. }
  26403. if (parsedGeometry.uvs4) {
  26404. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  26405. }
  26406. if (parsedGeometry.uvs5) {
  26407. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  26408. }
  26409. if (parsedGeometry.uvs6) {
  26410. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  26411. }
  26412. if (parsedGeometry.colors) {
  26413. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  26414. }
  26415. if (parsedGeometry.matricesIndices) {
  26416. if (!parsedGeometry.matricesIndices._isExpanded) {
  26417. var floatIndices = [];
  26418. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  26419. var matricesIndex = parsedGeometry.matricesIndices[i];
  26420. floatIndices.push(matricesIndex & 0x000000FF);
  26421. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  26422. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  26423. floatIndices.push(matricesIndex >> 24);
  26424. }
  26425. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  26426. }
  26427. else {
  26428. delete parsedGeometry.matricesIndices._isExpanded;
  26429. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  26430. }
  26431. }
  26432. if (parsedGeometry.matricesIndicesExtra) {
  26433. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  26434. var floatIndices = [];
  26435. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  26436. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  26437. floatIndices.push(matricesIndex & 0x000000FF);
  26438. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  26439. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  26440. floatIndices.push(matricesIndex >> 24);
  26441. }
  26442. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  26443. }
  26444. else {
  26445. delete parsedGeometry.matricesIndices._isExpanded;
  26446. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  26447. }
  26448. }
  26449. if (parsedGeometry.matricesWeights) {
  26450. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  26451. }
  26452. if (parsedGeometry.matricesWeightsExtra) {
  26453. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  26454. }
  26455. mesh.setIndices(parsedGeometry.indices);
  26456. }
  26457. // SubMeshes
  26458. if (parsedGeometry.subMeshes) {
  26459. mesh.subMeshes = [];
  26460. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  26461. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  26462. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  26463. }
  26464. }
  26465. // Flat shading
  26466. if (mesh._shouldGenerateFlatShading) {
  26467. mesh.convertToFlatShadedMesh();
  26468. delete mesh._shouldGenerateFlatShading;
  26469. }
  26470. // Update
  26471. mesh.computeWorldMatrix(true);
  26472. // Octree
  26473. if (scene['_selectionOctree']) {
  26474. scene['_selectionOctree'].addMesh(mesh);
  26475. }
  26476. };
  26477. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  26478. if (scene.getGeometryByID(parsedVertexData.id)) {
  26479. return null; // null since geometry could be something else than a box...
  26480. }
  26481. var geometry = new Geometry(parsedVertexData.id, scene);
  26482. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  26483. if (parsedVertexData.delayLoadingFile) {
  26484. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26485. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  26486. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  26487. geometry._delayInfo = [];
  26488. if (parsedVertexData.hasUVs) {
  26489. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  26490. }
  26491. if (parsedVertexData.hasUVs2) {
  26492. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  26493. }
  26494. if (parsedVertexData.hasUVs3) {
  26495. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  26496. }
  26497. if (parsedVertexData.hasUVs4) {
  26498. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  26499. }
  26500. if (parsedVertexData.hasUVs5) {
  26501. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  26502. }
  26503. if (parsedVertexData.hasUVs6) {
  26504. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  26505. }
  26506. if (parsedVertexData.hasColors) {
  26507. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  26508. }
  26509. if (parsedVertexData.hasMatricesIndices) {
  26510. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  26511. }
  26512. if (parsedVertexData.hasMatricesWeights) {
  26513. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  26514. }
  26515. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  26516. }
  26517. else {
  26518. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  26519. }
  26520. scene.pushGeometry(geometry, true);
  26521. return geometry;
  26522. };
  26523. return Geometry;
  26524. }());
  26525. BABYLON.Geometry = Geometry;
  26526. /////// Primitives //////////////////////////////////////////////
  26527. (function (Geometry) {
  26528. var Primitives;
  26529. (function (Primitives) {
  26530. /// Abstract class
  26531. var _Primitive = (function (_super) {
  26532. __extends(_Primitive, _super);
  26533. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  26534. var _this = _super.call(this, id, scene, null, false, mesh) || this;
  26535. _this._canBeRegenerated = _canBeRegenerated;
  26536. _this._beingRegenerated = true;
  26537. _this.regenerate();
  26538. _this._beingRegenerated = false;
  26539. return _this;
  26540. }
  26541. _Primitive.prototype.canBeRegenerated = function () {
  26542. return this._canBeRegenerated;
  26543. };
  26544. _Primitive.prototype.regenerate = function () {
  26545. if (!this._canBeRegenerated) {
  26546. return;
  26547. }
  26548. this._beingRegenerated = true;
  26549. this.setAllVerticesData(this._regenerateVertexData(), false);
  26550. this._beingRegenerated = false;
  26551. };
  26552. _Primitive.prototype.asNewGeometry = function (id) {
  26553. return _super.prototype.copy.call(this, id);
  26554. };
  26555. // overrides
  26556. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  26557. if (!this._beingRegenerated) {
  26558. return;
  26559. }
  26560. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  26561. };
  26562. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  26563. if (!this._beingRegenerated) {
  26564. return;
  26565. }
  26566. _super.prototype.setVerticesData.call(this, kind, data, false);
  26567. };
  26568. // to override
  26569. // protected
  26570. _Primitive.prototype._regenerateVertexData = function () {
  26571. throw new Error("Abstract method");
  26572. };
  26573. _Primitive.prototype.copy = function (id) {
  26574. throw new Error("Must be overriden in sub-classes.");
  26575. };
  26576. _Primitive.prototype.serialize = function () {
  26577. var serializationObject = _super.prototype.serialize.call(this);
  26578. serializationObject.canBeRegenerated = this.canBeRegenerated();
  26579. return serializationObject;
  26580. };
  26581. return _Primitive;
  26582. }(Geometry));
  26583. Primitives._Primitive = _Primitive;
  26584. var Ribbon = (function (_super) {
  26585. __extends(Ribbon, _super);
  26586. // Members
  26587. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  26588. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26589. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  26590. _this.pathArray = pathArray;
  26591. _this.closeArray = closeArray;
  26592. _this.closePath = closePath;
  26593. _this.offset = offset;
  26594. _this.side = side;
  26595. return _this;
  26596. }
  26597. Ribbon.prototype._regenerateVertexData = function () {
  26598. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  26599. };
  26600. Ribbon.prototype.copy = function (id) {
  26601. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  26602. };
  26603. return Ribbon;
  26604. }(_Primitive));
  26605. Primitives.Ribbon = Ribbon;
  26606. var Box = (function (_super) {
  26607. __extends(Box, _super);
  26608. // Members
  26609. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  26610. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26611. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  26612. _this.size = size;
  26613. _this.side = side;
  26614. return _this;
  26615. }
  26616. Box.prototype._regenerateVertexData = function () {
  26617. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  26618. };
  26619. Box.prototype.copy = function (id) {
  26620. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  26621. };
  26622. Box.prototype.serialize = function () {
  26623. var serializationObject = _super.prototype.serialize.call(this);
  26624. serializationObject.size = this.size;
  26625. return serializationObject;
  26626. };
  26627. Box.Parse = function (parsedBox, scene) {
  26628. if (scene.getGeometryByID(parsedBox.id)) {
  26629. return null; // null since geometry could be something else than a box...
  26630. }
  26631. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  26632. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  26633. scene.pushGeometry(box, true);
  26634. return box;
  26635. };
  26636. return Box;
  26637. }(_Primitive));
  26638. Primitives.Box = Box;
  26639. var Sphere = (function (_super) {
  26640. __extends(Sphere, _super);
  26641. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  26642. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26643. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  26644. _this.segments = segments;
  26645. _this.diameter = diameter;
  26646. _this.side = side;
  26647. return _this;
  26648. }
  26649. Sphere.prototype._regenerateVertexData = function () {
  26650. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  26651. };
  26652. Sphere.prototype.copy = function (id) {
  26653. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  26654. };
  26655. Sphere.prototype.serialize = function () {
  26656. var serializationObject = _super.prototype.serialize.call(this);
  26657. serializationObject.segments = this.segments;
  26658. serializationObject.diameter = this.diameter;
  26659. return serializationObject;
  26660. };
  26661. Sphere.Parse = function (parsedSphere, scene) {
  26662. if (scene.getGeometryByID(parsedSphere.id)) {
  26663. return null; // null since geometry could be something else than a sphere...
  26664. }
  26665. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  26666. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  26667. scene.pushGeometry(sphere, true);
  26668. return sphere;
  26669. };
  26670. return Sphere;
  26671. }(_Primitive));
  26672. Primitives.Sphere = Sphere;
  26673. var Disc = (function (_super) {
  26674. __extends(Disc, _super);
  26675. // Members
  26676. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  26677. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26678. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  26679. _this.radius = radius;
  26680. _this.tessellation = tessellation;
  26681. _this.side = side;
  26682. return _this;
  26683. }
  26684. Disc.prototype._regenerateVertexData = function () {
  26685. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  26686. };
  26687. Disc.prototype.copy = function (id) {
  26688. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  26689. };
  26690. return Disc;
  26691. }(_Primitive));
  26692. Primitives.Disc = Disc;
  26693. var Cylinder = (function (_super) {
  26694. __extends(Cylinder, _super);
  26695. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  26696. if (subdivisions === void 0) { subdivisions = 1; }
  26697. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26698. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  26699. _this.height = height;
  26700. _this.diameterTop = diameterTop;
  26701. _this.diameterBottom = diameterBottom;
  26702. _this.tessellation = tessellation;
  26703. _this.subdivisions = subdivisions;
  26704. _this.side = side;
  26705. return _this;
  26706. }
  26707. Cylinder.prototype._regenerateVertexData = function () {
  26708. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  26709. };
  26710. Cylinder.prototype.copy = function (id) {
  26711. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  26712. };
  26713. Cylinder.prototype.serialize = function () {
  26714. var serializationObject = _super.prototype.serialize.call(this);
  26715. serializationObject.height = this.height;
  26716. serializationObject.diameterTop = this.diameterTop;
  26717. serializationObject.diameterBottom = this.diameterBottom;
  26718. serializationObject.tessellation = this.tessellation;
  26719. return serializationObject;
  26720. };
  26721. Cylinder.Parse = function (parsedCylinder, scene) {
  26722. if (scene.getGeometryByID(parsedCylinder.id)) {
  26723. return null; // null since geometry could be something else than a cylinder...
  26724. }
  26725. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  26726. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  26727. scene.pushGeometry(cylinder, true);
  26728. return cylinder;
  26729. };
  26730. return Cylinder;
  26731. }(_Primitive));
  26732. Primitives.Cylinder = Cylinder;
  26733. var Torus = (function (_super) {
  26734. __extends(Torus, _super);
  26735. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  26736. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26737. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  26738. _this.diameter = diameter;
  26739. _this.thickness = thickness;
  26740. _this.tessellation = tessellation;
  26741. _this.side = side;
  26742. return _this;
  26743. }
  26744. Torus.prototype._regenerateVertexData = function () {
  26745. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  26746. };
  26747. Torus.prototype.copy = function (id) {
  26748. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  26749. };
  26750. Torus.prototype.serialize = function () {
  26751. var serializationObject = _super.prototype.serialize.call(this);
  26752. serializationObject.diameter = this.diameter;
  26753. serializationObject.thickness = this.thickness;
  26754. serializationObject.tessellation = this.tessellation;
  26755. return serializationObject;
  26756. };
  26757. Torus.Parse = function (parsedTorus, scene) {
  26758. if (scene.getGeometryByID(parsedTorus.id)) {
  26759. return null; // null since geometry could be something else than a torus...
  26760. }
  26761. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  26762. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  26763. scene.pushGeometry(torus, true);
  26764. return torus;
  26765. };
  26766. return Torus;
  26767. }(_Primitive));
  26768. Primitives.Torus = Torus;
  26769. var Ground = (function (_super) {
  26770. __extends(Ground, _super);
  26771. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  26772. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  26773. _this.width = width;
  26774. _this.height = height;
  26775. _this.subdivisions = subdivisions;
  26776. return _this;
  26777. }
  26778. Ground.prototype._regenerateVertexData = function () {
  26779. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  26780. };
  26781. Ground.prototype.copy = function (id) {
  26782. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  26783. };
  26784. Ground.prototype.serialize = function () {
  26785. var serializationObject = _super.prototype.serialize.call(this);
  26786. serializationObject.width = this.width;
  26787. serializationObject.height = this.height;
  26788. serializationObject.subdivisions = this.subdivisions;
  26789. return serializationObject;
  26790. };
  26791. Ground.Parse = function (parsedGround, scene) {
  26792. if (scene.getGeometryByID(parsedGround.id)) {
  26793. return null; // null since geometry could be something else than a ground...
  26794. }
  26795. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  26796. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  26797. scene.pushGeometry(ground, true);
  26798. return ground;
  26799. };
  26800. return Ground;
  26801. }(_Primitive));
  26802. Primitives.Ground = Ground;
  26803. var TiledGround = (function (_super) {
  26804. __extends(TiledGround, _super);
  26805. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  26806. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  26807. _this.xmin = xmin;
  26808. _this.zmin = zmin;
  26809. _this.xmax = xmax;
  26810. _this.zmax = zmax;
  26811. _this.subdivisions = subdivisions;
  26812. _this.precision = precision;
  26813. return _this;
  26814. }
  26815. TiledGround.prototype._regenerateVertexData = function () {
  26816. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  26817. };
  26818. TiledGround.prototype.copy = function (id) {
  26819. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  26820. };
  26821. return TiledGround;
  26822. }(_Primitive));
  26823. Primitives.TiledGround = TiledGround;
  26824. var Plane = (function (_super) {
  26825. __extends(Plane, _super);
  26826. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  26827. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26828. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  26829. _this.size = size;
  26830. _this.side = side;
  26831. return _this;
  26832. }
  26833. Plane.prototype._regenerateVertexData = function () {
  26834. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  26835. };
  26836. Plane.prototype.copy = function (id) {
  26837. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  26838. };
  26839. Plane.prototype.serialize = function () {
  26840. var serializationObject = _super.prototype.serialize.call(this);
  26841. serializationObject.size = this.size;
  26842. return serializationObject;
  26843. };
  26844. Plane.Parse = function (parsedPlane, scene) {
  26845. if (scene.getGeometryByID(parsedPlane.id)) {
  26846. return null; // null since geometry could be something else than a ground...
  26847. }
  26848. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  26849. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  26850. scene.pushGeometry(plane, true);
  26851. return plane;
  26852. };
  26853. return Plane;
  26854. }(_Primitive));
  26855. Primitives.Plane = Plane;
  26856. var TorusKnot = (function (_super) {
  26857. __extends(TorusKnot, _super);
  26858. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  26859. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26860. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  26861. _this.radius = radius;
  26862. _this.tube = tube;
  26863. _this.radialSegments = radialSegments;
  26864. _this.tubularSegments = tubularSegments;
  26865. _this.p = p;
  26866. _this.q = q;
  26867. _this.side = side;
  26868. return _this;
  26869. }
  26870. TorusKnot.prototype._regenerateVertexData = function () {
  26871. 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 });
  26872. };
  26873. TorusKnot.prototype.copy = function (id) {
  26874. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  26875. };
  26876. TorusKnot.prototype.serialize = function () {
  26877. var serializationObject = _super.prototype.serialize.call(this);
  26878. serializationObject.radius = this.radius;
  26879. serializationObject.tube = this.tube;
  26880. serializationObject.radialSegments = this.radialSegments;
  26881. serializationObject.tubularSegments = this.tubularSegments;
  26882. serializationObject.p = this.p;
  26883. serializationObject.q = this.q;
  26884. return serializationObject;
  26885. };
  26886. ;
  26887. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  26888. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  26889. return null; // null since geometry could be something else than a ground...
  26890. }
  26891. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  26892. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  26893. scene.pushGeometry(torusKnot, true);
  26894. return torusKnot;
  26895. };
  26896. return TorusKnot;
  26897. }(_Primitive));
  26898. Primitives.TorusKnot = TorusKnot;
  26899. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  26900. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  26901. })(BABYLON || (BABYLON = {}));
  26902. //# sourceMappingURL=babylon.geometry.js.map
  26903. var BABYLON;
  26904. (function (BABYLON) {
  26905. var PostProcessManager = (function () {
  26906. function PostProcessManager(scene) {
  26907. this._vertexBuffers = {};
  26908. this._scene = scene;
  26909. }
  26910. PostProcessManager.prototype._prepareBuffers = function () {
  26911. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  26912. return;
  26913. }
  26914. // VBO
  26915. var vertices = [];
  26916. vertices.push(1, 1);
  26917. vertices.push(-1, 1);
  26918. vertices.push(-1, -1);
  26919. vertices.push(1, -1);
  26920. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  26921. // Indices
  26922. var indices = [];
  26923. indices.push(0);
  26924. indices.push(1);
  26925. indices.push(2);
  26926. indices.push(0);
  26927. indices.push(2);
  26928. indices.push(3);
  26929. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  26930. };
  26931. // Methods
  26932. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  26933. var postProcesses = this._scene.activeCamera._postProcesses;
  26934. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  26935. return false;
  26936. }
  26937. postProcesses[0].activate(this._scene.activeCamera, sourceTexture);
  26938. return true;
  26939. };
  26940. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  26941. var engine = this._scene.getEngine();
  26942. for (var index = 0; index < postProcesses.length; index++) {
  26943. if (index < postProcesses.length - 1) {
  26944. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  26945. }
  26946. else {
  26947. if (targetTexture) {
  26948. engine.bindFramebuffer(targetTexture);
  26949. }
  26950. else {
  26951. engine.restoreDefaultFramebuffer();
  26952. }
  26953. }
  26954. var pp = postProcesses[index];
  26955. var effect = pp.apply();
  26956. if (effect) {
  26957. pp.onBeforeRenderObservable.notifyObservers(effect);
  26958. // VBOs
  26959. this._prepareBuffers();
  26960. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  26961. // Draw order
  26962. engine.draw(true, 0, 6);
  26963. pp.onAfterRenderObservable.notifyObservers(effect);
  26964. }
  26965. }
  26966. // Restore depth buffer
  26967. engine.setDepthBuffer(true);
  26968. engine.setDepthWrite(true);
  26969. };
  26970. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  26971. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  26972. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  26973. return;
  26974. }
  26975. var engine = this._scene.getEngine();
  26976. for (var index = 0, len = postProcesses.length; index < len; index++) {
  26977. if (index < len - 1) {
  26978. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  26979. }
  26980. else {
  26981. if (targetTexture) {
  26982. engine.bindFramebuffer(targetTexture, faceIndex);
  26983. }
  26984. else {
  26985. engine.restoreDefaultFramebuffer();
  26986. }
  26987. }
  26988. if (doNotPresent) {
  26989. break;
  26990. }
  26991. var pp = postProcesses[index];
  26992. var effect = pp.apply();
  26993. if (effect) {
  26994. pp.onBeforeRenderObservable.notifyObservers(effect);
  26995. // VBOs
  26996. this._prepareBuffers();
  26997. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  26998. // Draw order
  26999. engine.draw(true, 0, 6);
  27000. pp.onAfterRenderObservable.notifyObservers(effect);
  27001. }
  27002. }
  27003. // Restore depth buffer
  27004. engine.setDepthBuffer(true);
  27005. engine.setDepthWrite(true);
  27006. };
  27007. PostProcessManager.prototype.dispose = function () {
  27008. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  27009. if (buffer) {
  27010. buffer.dispose();
  27011. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  27012. }
  27013. if (this._indexBuffer) {
  27014. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  27015. this._indexBuffer = null;
  27016. }
  27017. };
  27018. return PostProcessManager;
  27019. }());
  27020. BABYLON.PostProcessManager = PostProcessManager;
  27021. })(BABYLON || (BABYLON = {}));
  27022. //# sourceMappingURL=babylon.postProcessManager.js.map
  27023. var BABYLON;
  27024. (function (BABYLON) {
  27025. var StandardMaterialDefines = (function (_super) {
  27026. __extends(StandardMaterialDefines, _super);
  27027. function StandardMaterialDefines() {
  27028. var _this = _super.call(this) || this;
  27029. _this.DIFFUSE = false;
  27030. _this.AMBIENT = false;
  27031. _this.OPACITY = false;
  27032. _this.OPACITYRGB = false;
  27033. _this.REFLECTION = false;
  27034. _this.EMISSIVE = false;
  27035. _this.SPECULAR = false;
  27036. _this.BUMP = false;
  27037. _this.PARALLAX = false;
  27038. _this.PARALLAXOCCLUSION = false;
  27039. _this.SPECULAROVERALPHA = false;
  27040. _this.CLIPPLANE = false;
  27041. _this.ALPHATEST = false;
  27042. _this.ALPHAFROMDIFFUSE = false;
  27043. _this.POINTSIZE = false;
  27044. _this.FOG = false;
  27045. _this.SPECULARTERM = false;
  27046. _this.DIFFUSEFRESNEL = false;
  27047. _this.OPACITYFRESNEL = false;
  27048. _this.REFLECTIONFRESNEL = false;
  27049. _this.REFRACTIONFRESNEL = false;
  27050. _this.EMISSIVEFRESNEL = false;
  27051. _this.FRESNEL = false;
  27052. _this.NORMAL = false;
  27053. _this.UV1 = false;
  27054. _this.UV2 = false;
  27055. _this.VERTEXCOLOR = false;
  27056. _this.VERTEXALPHA = false;
  27057. _this.NUM_BONE_INFLUENCERS = 0;
  27058. _this.BonesPerMesh = 0;
  27059. _this.INSTANCES = false;
  27060. _this.GLOSSINESS = false;
  27061. _this.ROUGHNESS = false;
  27062. _this.EMISSIVEASILLUMINATION = false;
  27063. _this.LINKEMISSIVEWITHDIFFUSE = false;
  27064. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  27065. _this.LIGHTMAP = false;
  27066. _this.USELIGHTMAPASSHADOWMAP = false;
  27067. _this.REFLECTIONMAP_3D = false;
  27068. _this.REFLECTIONMAP_SPHERICAL = false;
  27069. _this.REFLECTIONMAP_PLANAR = false;
  27070. _this.REFLECTIONMAP_CUBIC = false;
  27071. _this.REFLECTIONMAP_PROJECTION = false;
  27072. _this.REFLECTIONMAP_SKYBOX = false;
  27073. _this.REFLECTIONMAP_EXPLICIT = false;
  27074. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  27075. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  27076. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  27077. _this.INVERTCUBICMAP = false;
  27078. _this.LOGARITHMICDEPTH = false;
  27079. _this.REFRACTION = false;
  27080. _this.REFRACTIONMAP_3D = false;
  27081. _this.REFLECTIONOVERALPHA = false;
  27082. _this.INVERTNORMALMAPX = false;
  27083. _this.INVERTNORMALMAPY = false;
  27084. _this.TWOSIDEDLIGHTING = false;
  27085. _this.SHADOWFULLFLOAT = false;
  27086. _this.CAMERACOLORGRADING = false;
  27087. _this.CAMERACOLORCURVES = false;
  27088. _this.MORPHTARGETS = false;
  27089. _this.MORPHTARGETS_NORMAL = false;
  27090. _this.MORPHTARGETS_TANGENT = false;
  27091. _this.NUM_MORPH_INFLUENCERS = 0;
  27092. _this.rebuild();
  27093. return _this;
  27094. }
  27095. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  27096. var modes = [
  27097. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  27098. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  27099. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  27100. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  27101. ];
  27102. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  27103. var mode = modes_1[_i];
  27104. this[mode] = (mode === modeToEnable);
  27105. }
  27106. };
  27107. return StandardMaterialDefines;
  27108. }(BABYLON.MaterialDefines));
  27109. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  27110. var StandardMaterial = (function (_super) {
  27111. __extends(StandardMaterial, _super);
  27112. function StandardMaterial(name, scene) {
  27113. var _this = _super.call(this, name, scene) || this;
  27114. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  27115. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  27116. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  27117. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  27118. _this.specularPower = 64;
  27119. _this._useAlphaFromDiffuseTexture = false;
  27120. _this._useEmissiveAsIllumination = false;
  27121. _this._linkEmissiveWithDiffuse = false;
  27122. _this._useSpecularOverAlpha = false;
  27123. _this._useReflectionOverAlpha = false;
  27124. _this._disableLighting = false;
  27125. _this._useParallax = false;
  27126. _this._useParallaxOcclusion = false;
  27127. _this.parallaxScaleBias = 0.05;
  27128. _this._roughness = 0;
  27129. _this.indexOfRefraction = 0.98;
  27130. _this.invertRefractionY = true;
  27131. _this._useLightmapAsShadowmap = false;
  27132. _this._useReflectionFresnelFromSpecular = false;
  27133. _this._useGlossinessFromSpecularMapAlpha = false;
  27134. _this._maxSimultaneousLights = 4;
  27135. /**
  27136. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  27137. */
  27138. _this._invertNormalMapX = false;
  27139. /**
  27140. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  27141. */
  27142. _this._invertNormalMapY = false;
  27143. /**
  27144. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  27145. */
  27146. _this._twoSidedLighting = false;
  27147. /**
  27148. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  27149. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  27150. * 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;
  27151. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  27152. */
  27153. _this._cameraColorCurves = null;
  27154. _this._renderTargets = new BABYLON.SmartArray(16);
  27155. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  27156. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  27157. _this.getRenderTargetTextures = function () {
  27158. _this._renderTargets.reset();
  27159. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  27160. _this._renderTargets.push(_this._reflectionTexture);
  27161. }
  27162. if (_this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  27163. _this._renderTargets.push(_this._refractionTexture);
  27164. }
  27165. return _this._renderTargets;
  27166. };
  27167. return _this;
  27168. }
  27169. StandardMaterial.prototype.getClassName = function () {
  27170. return "StandardMaterial";
  27171. };
  27172. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  27173. get: function () {
  27174. return this._useLogarithmicDepth;
  27175. },
  27176. set: function (value) {
  27177. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  27178. this._markAllSubMeshesAsMiscDirty();
  27179. },
  27180. enumerable: true,
  27181. configurable: true
  27182. });
  27183. StandardMaterial.prototype.needAlphaBlending = function () {
  27184. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  27185. };
  27186. StandardMaterial.prototype.needAlphaTesting = function () {
  27187. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  27188. };
  27189. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  27190. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  27191. };
  27192. StandardMaterial.prototype.getAlphaTestTexture = function () {
  27193. return this._diffuseTexture;
  27194. };
  27195. /**
  27196. * Child classes can use it to update shaders
  27197. */
  27198. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  27199. if (this.isFrozen) {
  27200. if (this._wasPreviouslyReady && subMesh.effect) {
  27201. return true;
  27202. }
  27203. }
  27204. if (!subMesh._materialDefines) {
  27205. subMesh._materialDefines = new StandardMaterialDefines();
  27206. }
  27207. var scene = this.getScene();
  27208. var defines = subMesh._materialDefines;
  27209. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  27210. if (defines._renderId === scene.getRenderId()) {
  27211. return true;
  27212. }
  27213. }
  27214. var engine = scene.getEngine();
  27215. // Lights
  27216. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  27217. // Textures
  27218. if (defines._areTexturesDirty) {
  27219. defines._needUVs = false;
  27220. if (scene.texturesEnabled) {
  27221. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  27222. if (!this._diffuseTexture.isReady()) {
  27223. return false;
  27224. }
  27225. else {
  27226. defines._needUVs = true;
  27227. defines.DIFFUSE = true;
  27228. }
  27229. }
  27230. else {
  27231. defines.DIFFUSE = false;
  27232. }
  27233. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  27234. if (!this._ambientTexture.isReady()) {
  27235. return false;
  27236. }
  27237. else {
  27238. defines._needUVs = true;
  27239. defines.AMBIENT = true;
  27240. }
  27241. }
  27242. else {
  27243. defines.AMBIENT = false;
  27244. }
  27245. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  27246. if (!this._opacityTexture.isReady()) {
  27247. return false;
  27248. }
  27249. else {
  27250. defines._needUVs = true;
  27251. defines.OPACITY = true;
  27252. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  27253. }
  27254. }
  27255. else {
  27256. defines.OPACITY = false;
  27257. }
  27258. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  27259. if (!this._reflectionTexture.isReady()) {
  27260. return false;
  27261. }
  27262. else {
  27263. defines._needNormals = true;
  27264. defines.REFLECTION = true;
  27265. defines.ROUGHNESS = (this._roughness > 0);
  27266. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  27267. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  27268. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  27269. switch (this._reflectionTexture.coordinatesMode) {
  27270. case BABYLON.Texture.CUBIC_MODE:
  27271. case BABYLON.Texture.INVCUBIC_MODE:
  27272. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  27273. break;
  27274. case BABYLON.Texture.EXPLICIT_MODE:
  27275. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  27276. break;
  27277. case BABYLON.Texture.PLANAR_MODE:
  27278. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  27279. break;
  27280. case BABYLON.Texture.PROJECTION_MODE:
  27281. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  27282. break;
  27283. case BABYLON.Texture.SKYBOX_MODE:
  27284. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  27285. break;
  27286. case BABYLON.Texture.SPHERICAL_MODE:
  27287. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  27288. break;
  27289. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  27290. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  27291. break;
  27292. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  27293. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  27294. break;
  27295. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  27296. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  27297. break;
  27298. }
  27299. }
  27300. }
  27301. else {
  27302. defines.REFLECTION = false;
  27303. }
  27304. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  27305. if (!this._emissiveTexture.isReady()) {
  27306. return false;
  27307. }
  27308. else {
  27309. defines._needUVs = true;
  27310. defines.EMISSIVE = true;
  27311. }
  27312. }
  27313. else {
  27314. defines.EMISSIVE = false;
  27315. }
  27316. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  27317. if (!this._lightmapTexture.isReady()) {
  27318. return false;
  27319. }
  27320. else {
  27321. defines._needUVs = true;
  27322. defines.LIGHTMAP = true;
  27323. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  27324. }
  27325. }
  27326. else {
  27327. defines.LIGHTMAP = false;
  27328. }
  27329. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  27330. if (!this._specularTexture.isReady()) {
  27331. return false;
  27332. }
  27333. else {
  27334. defines._needUVs = true;
  27335. defines.SPECULAR = true;
  27336. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  27337. }
  27338. }
  27339. else {
  27340. defines.SPECULAR = false;
  27341. }
  27342. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  27343. if (!this._bumpTexture.isReady()) {
  27344. return false;
  27345. }
  27346. else {
  27347. defines._needUVs = true;
  27348. defines.BUMP = true;
  27349. defines.INVERTNORMALMAPX = this.invertNormalMapX;
  27350. defines.INVERTNORMALMAPY = this.invertNormalMapY;
  27351. defines.PARALLAX = this._useParallax;
  27352. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  27353. }
  27354. }
  27355. else {
  27356. defines.BUMP = false;
  27357. }
  27358. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  27359. if (!this._refractionTexture.isReady()) {
  27360. return false;
  27361. }
  27362. else {
  27363. defines._needUVs = true;
  27364. defines.REFRACTION = true;
  27365. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  27366. }
  27367. }
  27368. else {
  27369. defines.REFRACTION = false;
  27370. }
  27371. if (this._cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  27372. if (!this._cameraColorGradingTexture.isReady()) {
  27373. return false;
  27374. }
  27375. else {
  27376. defines.CAMERACOLORGRADING = true;
  27377. }
  27378. }
  27379. else {
  27380. defines.CAMERACOLORGRADING = false;
  27381. }
  27382. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  27383. }
  27384. else {
  27385. defines.DIFFUSE = false;
  27386. defines.AMBIENT = false;
  27387. defines.OPACITY = false;
  27388. defines.REFLECTION = false;
  27389. defines.EMISSIVE = false;
  27390. defines.LIGHTMAP = false;
  27391. defines.BUMP = false;
  27392. defines.REFRACTION = false;
  27393. defines.CAMERACOLORGRADING = false;
  27394. }
  27395. defines.CAMERACOLORCURVES = (this._cameraColorCurves !== undefined && this._cameraColorCurves !== null);
  27396. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  27397. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  27398. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  27399. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  27400. }
  27401. if (defines._areFresnelDirty) {
  27402. if (StandardMaterial.FresnelEnabled) {
  27403. // Fresnel
  27404. if (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled ||
  27405. this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled ||
  27406. this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled ||
  27407. this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled ||
  27408. this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled) {
  27409. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  27410. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  27411. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  27412. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  27413. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  27414. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  27415. defines._needNormals = true;
  27416. defines.FRESNEL = true;
  27417. }
  27418. }
  27419. else {
  27420. defines.FRESNEL = false;
  27421. }
  27422. }
  27423. // Misc.
  27424. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  27425. // Attribs
  27426. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  27427. // Values that need to be evaluated on every frame
  27428. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  27429. if (scene._mirroredCameraPosition && defines.BUMP) {
  27430. defines.INVERTNORMALMAPX = !this.invertNormalMapX;
  27431. defines.INVERTNORMALMAPY = !this.invertNormalMapY;
  27432. defines.markAsUnprocessed();
  27433. }
  27434. // Get correct effect
  27435. if (defines.isDirty) {
  27436. defines.markAsProcessed();
  27437. scene.resetCachedMaterial();
  27438. // Fallbacks
  27439. var fallbacks = new BABYLON.EffectFallbacks();
  27440. if (defines.REFLECTION) {
  27441. fallbacks.addFallback(0, "REFLECTION");
  27442. }
  27443. if (defines.SPECULAR) {
  27444. fallbacks.addFallback(0, "SPECULAR");
  27445. }
  27446. if (defines.BUMP) {
  27447. fallbacks.addFallback(0, "BUMP");
  27448. }
  27449. if (defines.PARALLAX) {
  27450. fallbacks.addFallback(1, "PARALLAX");
  27451. }
  27452. if (defines.PARALLAXOCCLUSION) {
  27453. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  27454. }
  27455. if (defines.SPECULAROVERALPHA) {
  27456. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  27457. }
  27458. if (defines.FOG) {
  27459. fallbacks.addFallback(1, "FOG");
  27460. }
  27461. if (defines.POINTSIZE) {
  27462. fallbacks.addFallback(0, "POINTSIZE");
  27463. }
  27464. if (defines.LOGARITHMICDEPTH) {
  27465. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  27466. }
  27467. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  27468. if (defines.SPECULARTERM) {
  27469. fallbacks.addFallback(0, "SPECULARTERM");
  27470. }
  27471. if (defines.DIFFUSEFRESNEL) {
  27472. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  27473. }
  27474. if (defines.OPACITYFRESNEL) {
  27475. fallbacks.addFallback(2, "OPACITYFRESNEL");
  27476. }
  27477. if (defines.REFLECTIONFRESNEL) {
  27478. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  27479. }
  27480. if (defines.EMISSIVEFRESNEL) {
  27481. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  27482. }
  27483. if (defines.FRESNEL) {
  27484. fallbacks.addFallback(4, "FRESNEL");
  27485. }
  27486. //Attributes
  27487. var attribs = [BABYLON.VertexBuffer.PositionKind];
  27488. if (defines.NORMAL) {
  27489. attribs.push(BABYLON.VertexBuffer.NormalKind);
  27490. }
  27491. if (defines.UV1) {
  27492. attribs.push(BABYLON.VertexBuffer.UVKind);
  27493. }
  27494. if (defines.UV2) {
  27495. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  27496. }
  27497. if (defines.VERTEXCOLOR) {
  27498. attribs.push(BABYLON.VertexBuffer.ColorKind);
  27499. }
  27500. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  27501. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  27502. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  27503. var shaderName = "default";
  27504. if (this.customShaderNameResolve) {
  27505. shaderName = this.customShaderNameResolve(shaderName);
  27506. }
  27507. var join = defines.toString();
  27508. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  27509. "vFogInfos", "vFogColor", "pointSize",
  27510. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  27511. "mBones",
  27512. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  27513. "depthValues",
  27514. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  27515. "logarithmicDepthConstant"
  27516. ];
  27517. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  27518. var uniformBuffers = ["Material", "Scene"];
  27519. if (defines.CAMERACOLORCURVES) {
  27520. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  27521. }
  27522. if (defines.CAMERACOLORGRADING) {
  27523. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  27524. }
  27525. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  27526. uniformsNames: uniforms,
  27527. uniformBuffersNames: uniformBuffers,
  27528. samplers: samplers,
  27529. defines: defines,
  27530. maxSimultaneousLights: this._maxSimultaneousLights
  27531. });
  27532. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  27533. attributes: attribs,
  27534. uniformsNames: uniforms,
  27535. uniformBuffersNames: uniformBuffers,
  27536. samplers: samplers,
  27537. defines: join,
  27538. fallbacks: fallbacks,
  27539. onCompiled: this.onCompiled,
  27540. onError: this.onError,
  27541. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  27542. }, engine), defines);
  27543. this.buildUniformLayout();
  27544. }
  27545. if (!subMesh.effect.isReady()) {
  27546. return false;
  27547. }
  27548. defines._renderId = scene.getRenderId();
  27549. this._wasPreviouslyReady = true;
  27550. return true;
  27551. };
  27552. StandardMaterial.prototype.buildUniformLayout = function () {
  27553. // Order is important !
  27554. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  27555. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  27556. this._uniformBuffer.addUniform("opacityParts", 4);
  27557. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  27558. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  27559. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  27560. this._uniformBuffer.addUniform("refractionRightColor", 4);
  27561. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  27562. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  27563. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  27564. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  27565. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  27566. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  27567. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  27568. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  27569. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  27570. this._uniformBuffer.addUniform("vBumpInfos", 3);
  27571. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  27572. this._uniformBuffer.addUniform("ambientMatrix", 16);
  27573. this._uniformBuffer.addUniform("opacityMatrix", 16);
  27574. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  27575. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  27576. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  27577. this._uniformBuffer.addUniform("specularMatrix", 16);
  27578. this._uniformBuffer.addUniform("bumpMatrix", 16);
  27579. this._uniformBuffer.addUniform("refractionMatrix", 16);
  27580. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  27581. this._uniformBuffer.addUniform("vSpecularColor", 4);
  27582. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  27583. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  27584. this._uniformBuffer.addUniform("pointSize", 1);
  27585. this._uniformBuffer.create();
  27586. };
  27587. StandardMaterial.prototype.unbind = function () {
  27588. if (this._activeEffect) {
  27589. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  27590. this._activeEffect.setTexture("reflection2DSampler", null);
  27591. }
  27592. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  27593. this._activeEffect.setTexture("refraction2DSampler", null);
  27594. }
  27595. }
  27596. _super.prototype.unbind.call(this);
  27597. };
  27598. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  27599. var scene = this.getScene();
  27600. var defines = subMesh._materialDefines;
  27601. if (!defines) {
  27602. return;
  27603. }
  27604. var effect = subMesh.effect;
  27605. this._activeEffect = effect;
  27606. // Matrices
  27607. this.bindOnlyWorldMatrix(world);
  27608. // Bones
  27609. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  27610. if (this._mustRebind(scene, effect)) {
  27611. this._uniformBuffer.bindToEffect(effect, "Material");
  27612. this.bindViewProjection(effect);
  27613. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  27614. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  27615. // Fresnel
  27616. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  27617. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  27618. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  27619. }
  27620. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  27621. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  27622. }
  27623. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  27624. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  27625. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  27626. }
  27627. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  27628. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  27629. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  27630. }
  27631. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  27632. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  27633. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  27634. }
  27635. }
  27636. // Textures
  27637. if (scene.texturesEnabled) {
  27638. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  27639. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  27640. this._uniformBuffer.updateMatrix("diffuseMatrix", this._diffuseTexture.getTextureMatrix());
  27641. }
  27642. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  27643. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  27644. this._uniformBuffer.updateMatrix("ambientMatrix", this._ambientTexture.getTextureMatrix());
  27645. }
  27646. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  27647. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  27648. this._uniformBuffer.updateMatrix("opacityMatrix", this._opacityTexture.getTextureMatrix());
  27649. }
  27650. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  27651. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  27652. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  27653. }
  27654. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  27655. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  27656. this._uniformBuffer.updateMatrix("emissiveMatrix", this._emissiveTexture.getTextureMatrix());
  27657. }
  27658. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  27659. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  27660. this._uniformBuffer.updateMatrix("lightmapMatrix", this._lightmapTexture.getTextureMatrix());
  27661. }
  27662. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  27663. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  27664. this._uniformBuffer.updateMatrix("specularMatrix", this._specularTexture.getTextureMatrix());
  27665. }
  27666. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  27667. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  27668. this._uniformBuffer.updateMatrix("bumpMatrix", this._bumpTexture.getTextureMatrix());
  27669. }
  27670. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  27671. var depth = 1.0;
  27672. if (!this._refractionTexture.isCube) {
  27673. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  27674. if (this._refractionTexture.depth) {
  27675. depth = this._refractionTexture.depth;
  27676. }
  27677. }
  27678. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  27679. }
  27680. }
  27681. // Point size
  27682. if (this.pointsCloud) {
  27683. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  27684. }
  27685. if (defines.SPECULARTERM) {
  27686. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  27687. }
  27688. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  27689. // Diffuse
  27690. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  27691. }
  27692. // Textures
  27693. if (scene.texturesEnabled) {
  27694. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  27695. effect.setTexture("diffuseSampler", this._diffuseTexture);
  27696. }
  27697. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  27698. effect.setTexture("ambientSampler", this._ambientTexture);
  27699. }
  27700. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  27701. effect.setTexture("opacitySampler", this._opacityTexture);
  27702. }
  27703. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  27704. if (this._reflectionTexture.isCube) {
  27705. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  27706. }
  27707. else {
  27708. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  27709. }
  27710. }
  27711. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  27712. effect.setTexture("emissiveSampler", this._emissiveTexture);
  27713. }
  27714. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  27715. effect.setTexture("lightmapSampler", this._lightmapTexture);
  27716. }
  27717. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  27718. effect.setTexture("specularSampler", this._specularTexture);
  27719. }
  27720. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  27721. effect.setTexture("bumpSampler", this._bumpTexture);
  27722. }
  27723. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  27724. var depth = 1.0;
  27725. if (this._refractionTexture.isCube) {
  27726. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  27727. }
  27728. else {
  27729. effect.setTexture("refraction2DSampler", this._refractionTexture);
  27730. }
  27731. }
  27732. if (this._cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  27733. BABYLON.ColorGradingTexture.Bind(this._cameraColorGradingTexture, effect);
  27734. }
  27735. }
  27736. // Clip plane
  27737. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  27738. // Colors
  27739. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  27740. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  27741. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  27742. }
  27743. if (this._mustRebind(scene, effect) || !this.isFrozen) {
  27744. // Lights
  27745. if (scene.lightsEnabled && !this._disableLighting) {
  27746. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  27747. }
  27748. // View
  27749. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  27750. this.bindView(effect);
  27751. }
  27752. // Fog
  27753. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  27754. // Morph targets
  27755. if (defines.NUM_MORPH_INFLUENCERS) {
  27756. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  27757. }
  27758. // Log. depth
  27759. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  27760. // Color Curves
  27761. if (this._cameraColorCurves) {
  27762. BABYLON.ColorCurves.Bind(this._cameraColorCurves, effect);
  27763. }
  27764. }
  27765. this._uniformBuffer.update();
  27766. this._afterBind(mesh, this._activeEffect);
  27767. };
  27768. StandardMaterial.prototype.getAnimatables = function () {
  27769. var results = [];
  27770. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  27771. results.push(this._diffuseTexture);
  27772. }
  27773. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  27774. results.push(this._ambientTexture);
  27775. }
  27776. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  27777. results.push(this._opacityTexture);
  27778. }
  27779. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  27780. results.push(this._reflectionTexture);
  27781. }
  27782. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  27783. results.push(this._emissiveTexture);
  27784. }
  27785. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  27786. results.push(this._specularTexture);
  27787. }
  27788. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  27789. results.push(this._bumpTexture);
  27790. }
  27791. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  27792. results.push(this._lightmapTexture);
  27793. }
  27794. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  27795. results.push(this._refractionTexture);
  27796. }
  27797. if (this._cameraColorGradingTexture && this._cameraColorGradingTexture.animations && this._cameraColorGradingTexture.animations.length > 0) {
  27798. results.push(this._cameraColorGradingTexture);
  27799. }
  27800. return results;
  27801. };
  27802. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  27803. if (forceDisposeTextures) {
  27804. if (this._diffuseTexture) {
  27805. this._diffuseTexture.dispose();
  27806. }
  27807. if (this._ambientTexture) {
  27808. this._ambientTexture.dispose();
  27809. }
  27810. if (this._opacityTexture) {
  27811. this._opacityTexture.dispose();
  27812. }
  27813. if (this._reflectionTexture) {
  27814. this._reflectionTexture.dispose();
  27815. }
  27816. if (this._emissiveTexture) {
  27817. this._emissiveTexture.dispose();
  27818. }
  27819. if (this._specularTexture) {
  27820. this._specularTexture.dispose();
  27821. }
  27822. if (this._bumpTexture) {
  27823. this._bumpTexture.dispose();
  27824. }
  27825. if (this._lightmapTexture) {
  27826. this._lightmapTexture.dispose();
  27827. }
  27828. if (this._refractionTexture) {
  27829. this._refractionTexture.dispose();
  27830. }
  27831. if (this._cameraColorGradingTexture) {
  27832. this._cameraColorGradingTexture.dispose();
  27833. }
  27834. }
  27835. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  27836. };
  27837. StandardMaterial.prototype.clone = function (name) {
  27838. var _this = this;
  27839. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  27840. result.name = name;
  27841. result.id = name;
  27842. return result;
  27843. };
  27844. StandardMaterial.prototype.serialize = function () {
  27845. return BABYLON.SerializationHelper.Serialize(this);
  27846. };
  27847. // Statics
  27848. StandardMaterial.Parse = function (source, scene, rootUrl) {
  27849. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  27850. };
  27851. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  27852. get: function () {
  27853. return StandardMaterial._DiffuseTextureEnabled;
  27854. },
  27855. set: function (value) {
  27856. if (StandardMaterial._DiffuseTextureEnabled === value) {
  27857. return;
  27858. }
  27859. StandardMaterial._DiffuseTextureEnabled = value;
  27860. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  27861. },
  27862. enumerable: true,
  27863. configurable: true
  27864. });
  27865. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  27866. get: function () {
  27867. return StandardMaterial._AmbientTextureEnabled;
  27868. },
  27869. set: function (value) {
  27870. if (StandardMaterial._AmbientTextureEnabled === value) {
  27871. return;
  27872. }
  27873. StandardMaterial._AmbientTextureEnabled = value;
  27874. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  27875. },
  27876. enumerable: true,
  27877. configurable: true
  27878. });
  27879. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  27880. get: function () {
  27881. return StandardMaterial._OpacityTextureEnabled;
  27882. },
  27883. set: function (value) {
  27884. if (StandardMaterial._OpacityTextureEnabled === value) {
  27885. return;
  27886. }
  27887. StandardMaterial._OpacityTextureEnabled = value;
  27888. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  27889. },
  27890. enumerable: true,
  27891. configurable: true
  27892. });
  27893. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  27894. get: function () {
  27895. return StandardMaterial._ReflectionTextureEnabled;
  27896. },
  27897. set: function (value) {
  27898. if (StandardMaterial._ReflectionTextureEnabled === value) {
  27899. return;
  27900. }
  27901. StandardMaterial._ReflectionTextureEnabled = value;
  27902. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  27903. },
  27904. enumerable: true,
  27905. configurable: true
  27906. });
  27907. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  27908. get: function () {
  27909. return StandardMaterial._EmissiveTextureEnabled;
  27910. },
  27911. set: function (value) {
  27912. if (StandardMaterial._EmissiveTextureEnabled === value) {
  27913. return;
  27914. }
  27915. StandardMaterial._EmissiveTextureEnabled = value;
  27916. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  27917. },
  27918. enumerable: true,
  27919. configurable: true
  27920. });
  27921. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  27922. get: function () {
  27923. return StandardMaterial._SpecularTextureEnabled;
  27924. },
  27925. set: function (value) {
  27926. if (StandardMaterial._SpecularTextureEnabled === value) {
  27927. return;
  27928. }
  27929. StandardMaterial._SpecularTextureEnabled = value;
  27930. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  27931. },
  27932. enumerable: true,
  27933. configurable: true
  27934. });
  27935. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  27936. get: function () {
  27937. return StandardMaterial._BumpTextureEnabled;
  27938. },
  27939. set: function (value) {
  27940. if (StandardMaterial._BumpTextureEnabled === value) {
  27941. return;
  27942. }
  27943. StandardMaterial._BumpTextureEnabled = value;
  27944. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  27945. },
  27946. enumerable: true,
  27947. configurable: true
  27948. });
  27949. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  27950. get: function () {
  27951. return StandardMaterial._LightmapTextureEnabled;
  27952. },
  27953. set: function (value) {
  27954. if (StandardMaterial._LightmapTextureEnabled === value) {
  27955. return;
  27956. }
  27957. StandardMaterial._LightmapTextureEnabled = value;
  27958. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  27959. },
  27960. enumerable: true,
  27961. configurable: true
  27962. });
  27963. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  27964. get: function () {
  27965. return StandardMaterial._RefractionTextureEnabled;
  27966. },
  27967. set: function (value) {
  27968. if (StandardMaterial._RefractionTextureEnabled === value) {
  27969. return;
  27970. }
  27971. StandardMaterial._RefractionTextureEnabled = value;
  27972. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  27973. },
  27974. enumerable: true,
  27975. configurable: true
  27976. });
  27977. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  27978. get: function () {
  27979. return StandardMaterial._ColorGradingTextureEnabled;
  27980. },
  27981. set: function (value) {
  27982. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  27983. return;
  27984. }
  27985. StandardMaterial._ColorGradingTextureEnabled = value;
  27986. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  27987. },
  27988. enumerable: true,
  27989. configurable: true
  27990. });
  27991. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  27992. get: function () {
  27993. return StandardMaterial._FresnelEnabled;
  27994. },
  27995. set: function (value) {
  27996. if (StandardMaterial._FresnelEnabled === value) {
  27997. return;
  27998. }
  27999. StandardMaterial._FresnelEnabled = value;
  28000. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  28001. },
  28002. enumerable: true,
  28003. configurable: true
  28004. });
  28005. return StandardMaterial;
  28006. }(BABYLON.PushMaterial));
  28007. // Flags used to enable or disable a type of texture for all Standard Materials
  28008. StandardMaterial._DiffuseTextureEnabled = true;
  28009. StandardMaterial._AmbientTextureEnabled = true;
  28010. StandardMaterial._OpacityTextureEnabled = true;
  28011. StandardMaterial._ReflectionTextureEnabled = true;
  28012. StandardMaterial._EmissiveTextureEnabled = true;
  28013. StandardMaterial._SpecularTextureEnabled = true;
  28014. StandardMaterial._BumpTextureEnabled = true;
  28015. StandardMaterial._LightmapTextureEnabled = true;
  28016. StandardMaterial._RefractionTextureEnabled = true;
  28017. StandardMaterial._ColorGradingTextureEnabled = true;
  28018. StandardMaterial._FresnelEnabled = true;
  28019. __decorate([
  28020. BABYLON.serializeAsTexture("diffuseTexture")
  28021. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  28022. __decorate([
  28023. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28024. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  28025. __decorate([
  28026. BABYLON.serializeAsTexture("ambientTexture")
  28027. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  28028. __decorate([
  28029. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28030. ], StandardMaterial.prototype, "ambientTexture", void 0);
  28031. __decorate([
  28032. BABYLON.serializeAsTexture("opacityTexture")
  28033. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  28034. __decorate([
  28035. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28036. ], StandardMaterial.prototype, "opacityTexture", void 0);
  28037. __decorate([
  28038. BABYLON.serializeAsTexture("reflectionTexture")
  28039. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  28040. __decorate([
  28041. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28042. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  28043. __decorate([
  28044. BABYLON.serializeAsTexture("emissiveTexture")
  28045. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  28046. __decorate([
  28047. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28048. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  28049. __decorate([
  28050. BABYLON.serializeAsTexture("specularTexture")
  28051. ], StandardMaterial.prototype, "_specularTexture", void 0);
  28052. __decorate([
  28053. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28054. ], StandardMaterial.prototype, "specularTexture", void 0);
  28055. __decorate([
  28056. BABYLON.serializeAsTexture("bumpTexture")
  28057. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  28058. __decorate([
  28059. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28060. ], StandardMaterial.prototype, "bumpTexture", void 0);
  28061. __decorate([
  28062. BABYLON.serializeAsTexture("lightmapTexture")
  28063. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  28064. __decorate([
  28065. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28066. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  28067. __decorate([
  28068. BABYLON.serializeAsTexture("refractionTexture")
  28069. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  28070. __decorate([
  28071. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28072. ], StandardMaterial.prototype, "refractionTexture", void 0);
  28073. __decorate([
  28074. BABYLON.serializeAsColor3("ambient")
  28075. ], StandardMaterial.prototype, "ambientColor", void 0);
  28076. __decorate([
  28077. BABYLON.serializeAsColor3("diffuse")
  28078. ], StandardMaterial.prototype, "diffuseColor", void 0);
  28079. __decorate([
  28080. BABYLON.serializeAsColor3("specular")
  28081. ], StandardMaterial.prototype, "specularColor", void 0);
  28082. __decorate([
  28083. BABYLON.serializeAsColor3("emissive")
  28084. ], StandardMaterial.prototype, "emissiveColor", void 0);
  28085. __decorate([
  28086. BABYLON.serialize()
  28087. ], StandardMaterial.prototype, "specularPower", void 0);
  28088. __decorate([
  28089. BABYLON.serialize("useAlphaFromDiffuseTexture")
  28090. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  28091. __decorate([
  28092. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28093. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  28094. __decorate([
  28095. BABYLON.serialize("useEmissiveAsIllumination")
  28096. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  28097. __decorate([
  28098. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28099. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  28100. __decorate([
  28101. BABYLON.serialize("linkEmissiveWithDiffuse")
  28102. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  28103. __decorate([
  28104. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28105. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  28106. __decorate([
  28107. BABYLON.serialize("useSpecularOverAlpha")
  28108. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  28109. __decorate([
  28110. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28111. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  28112. __decorate([
  28113. BABYLON.serialize("useReflectionOverAlpha")
  28114. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  28115. __decorate([
  28116. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28117. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  28118. __decorate([
  28119. BABYLON.serialize("disableLighting")
  28120. ], StandardMaterial.prototype, "_disableLighting", void 0);
  28121. __decorate([
  28122. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  28123. ], StandardMaterial.prototype, "disableLighting", void 0);
  28124. __decorate([
  28125. BABYLON.serialize("useParallax")
  28126. ], StandardMaterial.prototype, "_useParallax", void 0);
  28127. __decorate([
  28128. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28129. ], StandardMaterial.prototype, "useParallax", void 0);
  28130. __decorate([
  28131. BABYLON.serialize("useParallaxOcclusion")
  28132. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  28133. __decorate([
  28134. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28135. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  28136. __decorate([
  28137. BABYLON.serialize()
  28138. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  28139. __decorate([
  28140. BABYLON.serialize("roughness")
  28141. ], StandardMaterial.prototype, "_roughness", void 0);
  28142. __decorate([
  28143. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28144. ], StandardMaterial.prototype, "roughness", void 0);
  28145. __decorate([
  28146. BABYLON.serialize()
  28147. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  28148. __decorate([
  28149. BABYLON.serialize()
  28150. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  28151. __decorate([
  28152. BABYLON.serialize("useLightmapAsShadowmap")
  28153. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  28154. __decorate([
  28155. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28156. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  28157. __decorate([
  28158. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  28159. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  28160. __decorate([
  28161. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  28162. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  28163. __decorate([
  28164. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  28165. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  28166. __decorate([
  28167. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  28168. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  28169. __decorate([
  28170. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  28171. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  28172. __decorate([
  28173. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  28174. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  28175. __decorate([
  28176. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  28177. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  28178. __decorate([
  28179. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  28180. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  28181. __decorate([
  28182. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  28183. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  28184. __decorate([
  28185. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  28186. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  28187. __decorate([
  28188. BABYLON.serialize("useReflectionFresnelFromSpecular")
  28189. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  28190. __decorate([
  28191. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  28192. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  28193. __decorate([
  28194. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  28195. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  28196. __decorate([
  28197. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28198. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  28199. __decorate([
  28200. BABYLON.serialize("maxSimultaneousLights")
  28201. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  28202. __decorate([
  28203. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  28204. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  28205. __decorate([
  28206. BABYLON.serialize("invertNormalMapX")
  28207. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  28208. __decorate([
  28209. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28210. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  28211. __decorate([
  28212. BABYLON.serialize("invertNormalMapY")
  28213. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  28214. __decorate([
  28215. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28216. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  28217. __decorate([
  28218. BABYLON.serialize("twoSidedLighting")
  28219. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  28220. __decorate([
  28221. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28222. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  28223. __decorate([
  28224. BABYLON.serializeAsTexture("cameraColorGradingTexture")
  28225. ], StandardMaterial.prototype, "_cameraColorGradingTexture", void 0);
  28226. __decorate([
  28227. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28228. ], StandardMaterial.prototype, "cameraColorGradingTexture", void 0);
  28229. __decorate([
  28230. BABYLON.serializeAsColorCurves("cameraColorCurves")
  28231. ], StandardMaterial.prototype, "_cameraColorCurves", void 0);
  28232. __decorate([
  28233. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28234. ], StandardMaterial.prototype, "cameraColorCurves", void 0);
  28235. __decorate([
  28236. BABYLON.serialize()
  28237. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  28238. BABYLON.StandardMaterial = StandardMaterial;
  28239. })(BABYLON || (BABYLON = {}));
  28240. //# sourceMappingURL=babylon.standardMaterial.js.map
  28241. var BABYLON;
  28242. (function (BABYLON) {
  28243. var PBRMaterialDefines = (function (_super) {
  28244. __extends(PBRMaterialDefines, _super);
  28245. function PBRMaterialDefines() {
  28246. var _this = _super.call(this) || this;
  28247. _this.ALBEDO = false;
  28248. _this.AMBIENT = false;
  28249. _this.AMBIENTINGRAYSCALE = false;
  28250. _this.OPACITY = false;
  28251. _this.OPACITYRGB = false;
  28252. _this.REFLECTION = false;
  28253. _this.EMISSIVE = false;
  28254. _this.REFLECTIVITY = false;
  28255. _this.BUMP = false;
  28256. _this.PARALLAX = false;
  28257. _this.PARALLAXOCCLUSION = false;
  28258. _this.SPECULAROVERALPHA = false;
  28259. _this.CLIPPLANE = false;
  28260. _this.ALPHATEST = false;
  28261. _this.ALPHAFROMALBEDO = false;
  28262. _this.POINTSIZE = false;
  28263. _this.FOG = false;
  28264. _this.SPECULARTERM = false;
  28265. _this.OPACITYFRESNEL = false;
  28266. _this.EMISSIVEFRESNEL = false;
  28267. _this.FRESNEL = false;
  28268. _this.NORMAL = false;
  28269. _this.TANGENT = false;
  28270. _this.UV1 = false;
  28271. _this.UV2 = false;
  28272. _this.VERTEXCOLOR = false;
  28273. _this.VERTEXALPHA = false;
  28274. _this.NUM_BONE_INFLUENCERS = 0;
  28275. _this.BonesPerMesh = 0;
  28276. _this.INSTANCES = false;
  28277. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  28278. _this.MICROSURFACEAUTOMATIC = false;
  28279. _this.EMISSIVEASILLUMINATION = false;
  28280. _this.LINKEMISSIVEWITHALBEDO = false;
  28281. _this.LIGHTMAP = false;
  28282. _this.USELIGHTMAPASSHADOWMAP = false;
  28283. _this.REFLECTIONMAP_3D = false;
  28284. _this.REFLECTIONMAP_SPHERICAL = false;
  28285. _this.REFLECTIONMAP_PLANAR = false;
  28286. _this.REFLECTIONMAP_CUBIC = false;
  28287. _this.REFLECTIONMAP_PROJECTION = false;
  28288. _this.REFLECTIONMAP_SKYBOX = false;
  28289. _this.REFLECTIONMAP_EXPLICIT = false;
  28290. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  28291. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  28292. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  28293. _this.INVERTCUBICMAP = false;
  28294. _this.LOGARITHMICDEPTH = false;
  28295. _this.CAMERATONEMAP = false;
  28296. _this.CAMERACONTRAST = false;
  28297. _this.CAMERACOLORGRADING = false;
  28298. _this.CAMERACOLORCURVES = false;
  28299. _this.OVERLOADEDVALUES = false;
  28300. _this.OVERLOADEDSHADOWVALUES = false;
  28301. _this.USESPHERICALFROMREFLECTIONMAP = false;
  28302. _this.REFRACTION = false;
  28303. _this.REFRACTIONMAP_3D = false;
  28304. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  28305. _this.REFRACTIONMAPINLINEARSPACE = false;
  28306. _this.LODBASEDMICROSFURACE = false;
  28307. _this.USEPHYSICALLIGHTFALLOFF = false;
  28308. _this.RADIANCEOVERALPHA = false;
  28309. _this.USEPMREMREFLECTION = false;
  28310. _this.USEPMREMREFRACTION = false;
  28311. _this.INVERTNORMALMAPX = false;
  28312. _this.INVERTNORMALMAPY = false;
  28313. _this.TWOSIDEDLIGHTING = false;
  28314. _this.SHADOWFULLFLOAT = false;
  28315. _this.METALLICWORKFLOW = false;
  28316. _this.METALLICMAP = false;
  28317. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  28318. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  28319. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  28320. _this.AOSTOREINMETALMAPRED = false;
  28321. _this.MICROSURFACEMAP = false;
  28322. _this.MORPHTARGETS = false;
  28323. _this.MORPHTARGETS_NORMAL = false;
  28324. _this.MORPHTARGETS_TANGENT = false;
  28325. _this.NUM_MORPH_INFLUENCERS = 0;
  28326. _this.rebuild();
  28327. return _this;
  28328. }
  28329. return PBRMaterialDefines;
  28330. }(BABYLON.MaterialDefines));
  28331. /**
  28332. * The Physically based material of BJS.
  28333. *
  28334. * This offers the main features of a standard PBR material.
  28335. * For more information, please refer to the documentation :
  28336. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  28337. */
  28338. var PBRMaterial = (function (_super) {
  28339. __extends(PBRMaterial, _super);
  28340. /**
  28341. * Instantiates a new PBRMaterial instance.
  28342. *
  28343. * @param name The material name
  28344. * @param scene The scene the material will be use in.
  28345. */
  28346. function PBRMaterial(name, scene) {
  28347. var _this = _super.call(this, name, scene) || this;
  28348. /**
  28349. * Intensity of the direct lights e.g. the four lights available in your scene.
  28350. * This impacts both the direct diffuse and specular highlights.
  28351. */
  28352. _this.directIntensity = 1.0;
  28353. /**
  28354. * Intensity of the emissive part of the material.
  28355. * This helps controlling the emissive effect without modifying the emissive color.
  28356. */
  28357. _this.emissiveIntensity = 1.0;
  28358. /**
  28359. * Intensity of the environment e.g. how much the environment will light the object
  28360. * either through harmonics for rough material or through the refelction for shiny ones.
  28361. */
  28362. _this.environmentIntensity = 1.0;
  28363. /**
  28364. * This is a special control allowing the reduction of the specular highlights coming from the
  28365. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  28366. */
  28367. _this.specularIntensity = 1.0;
  28368. _this._lightingInfos = new BABYLON.Vector4(_this.directIntensity, _this.emissiveIntensity, _this.environmentIntensity, _this.specularIntensity);
  28369. /**
  28370. * Debug Control allowing disabling the bump map on this material.
  28371. */
  28372. _this.disableBumpMap = false;
  28373. /**
  28374. * Debug Control helping enforcing or dropping the darkness of shadows.
  28375. * 1.0 means the shadows have their normal darkness, 0.0 means the shadows are not visible.
  28376. */
  28377. _this.overloadedShadowIntensity = 1.0;
  28378. /**
  28379. * Debug Control helping dropping the shading effect coming from the diffuse lighting.
  28380. * 1.0 means the shade have their normal impact, 0.0 means no shading at all.
  28381. */
  28382. _this.overloadedShadeIntensity = 1.0;
  28383. _this._overloadedShadowInfos = new BABYLON.Vector4(_this.overloadedShadowIntensity, _this.overloadedShadeIntensity, 0.0, 0.0);
  28384. /**
  28385. * The camera exposure used on this material.
  28386. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  28387. * This corresponds to a photographic exposure.
  28388. */
  28389. _this.cameraExposure = 1.0;
  28390. /**
  28391. * The camera contrast used on this material.
  28392. * This property is here and not in the camera to allow controlling contrast without full screen post process.
  28393. */
  28394. _this.cameraContrast = 1.0;
  28395. /**
  28396. * Color Grading 2D Lookup Texture.
  28397. * This allows special effects like sepia, black and white to sixties rendering style.
  28398. */
  28399. _this.cameraColorGradingTexture = null;
  28400. /**
  28401. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  28402. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  28403. * 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;
  28404. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  28405. */
  28406. _this.cameraColorCurves = null;
  28407. _this._cameraInfos = new BABYLON.Vector4(1.0, 1.0, 0.0, 0.0);
  28408. _this._microsurfaceTextureLods = new BABYLON.Vector2(0.0, 0.0);
  28409. /**
  28410. * Debug Control allowing to overload the ambient color.
  28411. * This as to be use with the overloadedAmbientIntensity parameter.
  28412. */
  28413. _this.overloadedAmbient = BABYLON.Color3.White();
  28414. /**
  28415. * Debug Control indicating how much the overloaded ambient color is used against the default one.
  28416. */
  28417. _this.overloadedAmbientIntensity = 0.0;
  28418. /**
  28419. * Debug Control allowing to overload the albedo color.
  28420. * This as to be use with the overloadedAlbedoIntensity parameter.
  28421. */
  28422. _this.overloadedAlbedo = BABYLON.Color3.White();
  28423. /**
  28424. * Debug Control indicating how much the overloaded albedo color is used against the default one.
  28425. */
  28426. _this.overloadedAlbedoIntensity = 0.0;
  28427. /**
  28428. * Debug Control allowing to overload the reflectivity color.
  28429. * This as to be use with the overloadedReflectivityIntensity parameter.
  28430. */
  28431. _this.overloadedReflectivity = new BABYLON.Color3(0.0, 0.0, 0.0);
  28432. /**
  28433. * Debug Control indicating how much the overloaded reflectivity color is used against the default one.
  28434. */
  28435. _this.overloadedReflectivityIntensity = 0.0;
  28436. /**
  28437. * Debug Control allowing to overload the emissive color.
  28438. * This as to be use with the overloadedEmissiveIntensity parameter.
  28439. */
  28440. _this.overloadedEmissive = BABYLON.Color3.White();
  28441. /**
  28442. * Debug Control indicating how much the overloaded emissive color is used against the default one.
  28443. */
  28444. _this.overloadedEmissiveIntensity = 0.0;
  28445. _this._overloadedIntensity = new BABYLON.Vector4(_this.overloadedAmbientIntensity, _this.overloadedAlbedoIntensity, _this.overloadedReflectivityIntensity, _this.overloadedEmissiveIntensity);
  28446. /**
  28447. * Debug Control allowing to overload the reflection color.
  28448. * This as to be use with the overloadedReflectionIntensity parameter.
  28449. */
  28450. _this.overloadedReflection = BABYLON.Color3.White();
  28451. /**
  28452. * Debug Control indicating how much the overloaded reflection color is used against the default one.
  28453. */
  28454. _this.overloadedReflectionIntensity = 0.0;
  28455. /**
  28456. * Debug Control allowing to overload the microsurface.
  28457. * This as to be use with the overloadedMicroSurfaceIntensity parameter.
  28458. */
  28459. _this.overloadedMicroSurface = 0.0;
  28460. /**
  28461. * Debug Control indicating how much the overloaded microsurface is used against the default one.
  28462. */
  28463. _this.overloadedMicroSurfaceIntensity = 0.0;
  28464. _this._overloadedMicroSurface = new BABYLON.Vector3(_this.overloadedMicroSurface, _this.overloadedMicroSurfaceIntensity, _this.overloadedReflectionIntensity);
  28465. /**
  28466. * AKA Occlusion Texture Intensity in other nomenclature.
  28467. */
  28468. _this.ambientTextureStrength = 1.0;
  28469. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  28470. /**
  28471. * AKA Diffuse Color in other nomenclature.
  28472. */
  28473. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  28474. /**
  28475. * AKA Specular Color in other nomenclature.
  28476. */
  28477. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  28478. _this.reflectionColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  28479. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  28480. /**
  28481. * AKA Glossiness in other nomenclature.
  28482. */
  28483. _this.microSurface = 0.9;
  28484. /**
  28485. * source material index of refraction (IOR)' / 'destination material IOR.
  28486. */
  28487. _this.indexOfRefraction = 0.66;
  28488. /**
  28489. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  28490. */
  28491. _this.invertRefractionY = false;
  28492. /**
  28493. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  28494. * Materials half opaque for instance using refraction could benefit from this control.
  28495. */
  28496. _this.linkRefractionWithTransparency = false;
  28497. /**
  28498. * The emissive and albedo are linked to never be more than one (Energy conservation).
  28499. */
  28500. _this.linkEmissiveWithAlbedo = false;
  28501. _this.useLightmapAsShadowmap = false;
  28502. /**
  28503. * In this mode, the emissive informtaion will always be added to the lighting once.
  28504. * A light for instance can be thought as emissive.
  28505. */
  28506. _this.useEmissiveAsIllumination = false;
  28507. /**
  28508. * Secifies that the alpha is coming form the albedo channel alpha channel.
  28509. */
  28510. _this.useAlphaFromAlbedoTexture = false;
  28511. /**
  28512. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  28513. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  28514. */
  28515. _this.useSpecularOverAlpha = true;
  28516. /**
  28517. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  28518. */
  28519. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  28520. /**
  28521. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  28522. */
  28523. _this.useRoughnessFromMetallicTextureAlpha = true;
  28524. /**
  28525. * Specifies if the metallic texture contains the roughness information in its green channel.
  28526. */
  28527. _this.useRoughnessFromMetallicTextureGreen = false;
  28528. /**
  28529. * Specifies if the metallic texture contains the metallness information in its blue channel.
  28530. */
  28531. _this.useMetallnessFromMetallicTextureBlue = false;
  28532. /**
  28533. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  28534. */
  28535. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  28536. /**
  28537. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  28538. */
  28539. _this.useAmbientInGrayScale = false;
  28540. /**
  28541. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  28542. * The material will try to infer what glossiness each pixel should be.
  28543. */
  28544. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  28545. /**
  28546. * Allows to work with scalar in linear mode. This is definitely a matter of preferences and tools used during
  28547. * the creation of the material.
  28548. */
  28549. _this.useScalarInLinearSpace = false;
  28550. /**
  28551. * BJS is using an harcoded light falloff based on a manually sets up range.
  28552. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  28553. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  28554. */
  28555. _this.usePhysicalLightFalloff = true;
  28556. /**
  28557. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  28558. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  28559. */
  28560. _this.useRadianceOverAlpha = true;
  28561. /**
  28562. * Allows using the bump map in parallax mode.
  28563. */
  28564. _this.useParallax = false;
  28565. /**
  28566. * Allows using the bump map in parallax occlusion mode.
  28567. */
  28568. _this.useParallaxOcclusion = false;
  28569. /**
  28570. * Controls the scale bias of the parallax mode.
  28571. */
  28572. _this.parallaxScaleBias = 0.05;
  28573. /**
  28574. * If sets to true, disables all the lights affecting the material.
  28575. */
  28576. _this.disableLighting = false;
  28577. /**
  28578. * Number of Simultaneous lights allowed on the material.
  28579. */
  28580. _this.maxSimultaneousLights = 4;
  28581. /**
  28582. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  28583. */
  28584. _this.invertNormalMapX = false;
  28585. /**
  28586. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  28587. */
  28588. _this.invertNormalMapY = false;
  28589. /**
  28590. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  28591. */
  28592. _this.twoSidedLighting = false;
  28593. _this._renderTargets = new BABYLON.SmartArray(16);
  28594. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  28595. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  28596. _this._tempColor = new BABYLON.Color3();
  28597. _this._defines = new PBRMaterialDefines();
  28598. _this._cachedDefines = new PBRMaterialDefines();
  28599. _this._myScene = null;
  28600. _this._myShadowGenerator = null;
  28601. _this._cachedDefines.BonesPerMesh = -1;
  28602. _this.getRenderTargetTextures = function () {
  28603. _this._renderTargets.reset();
  28604. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  28605. _this._renderTargets.push(_this.reflectionTexture);
  28606. }
  28607. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  28608. _this._renderTargets.push(_this.refractionTexture);
  28609. }
  28610. return _this._renderTargets;
  28611. };
  28612. return _this;
  28613. }
  28614. PBRMaterial.prototype.getClassName = function () {
  28615. return "PBRMaterial";
  28616. };
  28617. Object.defineProperty(PBRMaterial.prototype, "useLogarithmicDepth", {
  28618. get: function () {
  28619. return this._useLogarithmicDepth;
  28620. },
  28621. set: function (value) {
  28622. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  28623. },
  28624. enumerable: true,
  28625. configurable: true
  28626. });
  28627. PBRMaterial.prototype.needAlphaBlending = function () {
  28628. if (this.linkRefractionWithTransparency) {
  28629. return false;
  28630. }
  28631. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  28632. };
  28633. PBRMaterial.prototype.needAlphaTesting = function () {
  28634. if (this.linkRefractionWithTransparency) {
  28635. return false;
  28636. }
  28637. return this.albedoTexture != null && this.albedoTexture.hasAlpha;
  28638. };
  28639. PBRMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  28640. return this.albedoTexture != null && this.albedoTexture.hasAlpha && this.useAlphaFromAlbedoTexture;
  28641. };
  28642. PBRMaterial.prototype.getAlphaTestTexture = function () {
  28643. return this.albedoTexture;
  28644. };
  28645. PBRMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  28646. if (!mesh) {
  28647. return true;
  28648. }
  28649. if (this._defines.INSTANCES !== useInstances) {
  28650. return false;
  28651. }
  28652. return false;
  28653. };
  28654. PBRMaterial.prototype.convertColorToLinearSpaceToRef = function (color, ref) {
  28655. PBRMaterial.convertColorToLinearSpaceToRef(color, ref, this.useScalarInLinearSpace);
  28656. };
  28657. PBRMaterial.convertColorToLinearSpaceToRef = function (color, ref, useScalarInLinear) {
  28658. if (!useScalarInLinear) {
  28659. color.toLinearSpaceToRef(ref);
  28660. }
  28661. else {
  28662. ref.r = color.r;
  28663. ref.g = color.g;
  28664. ref.b = color.b;
  28665. }
  28666. };
  28667. PBRMaterial.BindLights = function (scene, mesh, effect, defines, useScalarInLinearSpace, maxSimultaneousLights, usePhysicalLightFalloff) {
  28668. var lightIndex = 0;
  28669. var depthValuesAlreadySet = false;
  28670. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  28671. var light = _a[_i];
  28672. var useUbo = light._uniformBuffer.useUbo;
  28673. light._uniformBuffer.bindToEffect(effect, "Light" + lightIndex);
  28674. BABYLON.MaterialHelper.BindLightProperties(light, effect, lightIndex);
  28675. // GAMMA CORRECTION.
  28676. this.convertColorToLinearSpaceToRef(light.diffuse, PBRMaterial._scaledAlbedo, useScalarInLinearSpace);
  28677. PBRMaterial._scaledAlbedo.scaleToRef(light.intensity, PBRMaterial._scaledAlbedo);
  28678. light._uniformBuffer.updateColor4(useUbo ? "vLightDiffuse" : "vLightDiffuse" + lightIndex, PBRMaterial._scaledAlbedo, usePhysicalLightFalloff ? light.radius : light.range);
  28679. if (defines["SPECULARTERM"]) {
  28680. this.convertColorToLinearSpaceToRef(light.specular, PBRMaterial._scaledReflectivity, useScalarInLinearSpace);
  28681. PBRMaterial._scaledReflectivity.scaleToRef(light.intensity, PBRMaterial._scaledReflectivity);
  28682. light._uniformBuffer.updateColor3(useUbo ? "vLightSpecular" : "vLightSpecular" + lightIndex, PBRMaterial._scaledReflectivity);
  28683. }
  28684. // Shadows
  28685. if (scene.shadowsEnabled) {
  28686. depthValuesAlreadySet = BABYLON.MaterialHelper.BindLightShadow(light, scene, mesh, lightIndex + "", effect, depthValuesAlreadySet);
  28687. }
  28688. light._uniformBuffer.update();
  28689. lightIndex++;
  28690. if (lightIndex === maxSimultaneousLights)
  28691. break;
  28692. }
  28693. };
  28694. PBRMaterial.prototype.isReady = function (mesh, useInstances) {
  28695. if (this.isFrozen) {
  28696. if (this._wasPreviouslyReady) {
  28697. return true;
  28698. }
  28699. }
  28700. var scene = this.getScene();
  28701. var engine = scene.getEngine();
  28702. var needUVs = false;
  28703. this._defines.reset();
  28704. if (scene.lightsEnabled && !this.disableLighting) {
  28705. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, true, this.maxSimultaneousLights);
  28706. }
  28707. if (!this.checkReadyOnEveryCall) {
  28708. if (this._renderId === scene.getRenderId()) {
  28709. if (this._checkCache(scene, mesh, useInstances)) {
  28710. return true;
  28711. }
  28712. }
  28713. }
  28714. if (scene.texturesEnabled) {
  28715. if (scene.getEngine().getCaps().textureLOD) {
  28716. this._defines.LODBASEDMICROSFURACE = true;
  28717. }
  28718. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  28719. if (!this.albedoTexture.isReady()) {
  28720. return false;
  28721. }
  28722. needUVs = true;
  28723. this._defines.ALBEDO = true;
  28724. }
  28725. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  28726. if (!this.ambientTexture.isReady()) {
  28727. return false;
  28728. }
  28729. needUVs = true;
  28730. this._defines.AMBIENT = true;
  28731. this._defines.AMBIENTINGRAYSCALE = this.useAmbientInGrayScale;
  28732. }
  28733. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  28734. if (!this.opacityTexture.isReady()) {
  28735. return false;
  28736. }
  28737. needUVs = true;
  28738. this._defines.OPACITY = true;
  28739. if (this.opacityTexture.getAlphaFromRGB) {
  28740. this._defines.OPACITYRGB = true;
  28741. }
  28742. }
  28743. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  28744. if (!this.reflectionTexture.isReady()) {
  28745. return false;
  28746. }
  28747. this._defines.REFLECTION = true;
  28748. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  28749. this._defines.INVERTCUBICMAP = true;
  28750. }
  28751. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  28752. switch (this.reflectionTexture.coordinatesMode) {
  28753. case BABYLON.Texture.CUBIC_MODE:
  28754. case BABYLON.Texture.INVCUBIC_MODE:
  28755. this._defines.REFLECTIONMAP_CUBIC = true;
  28756. break;
  28757. case BABYLON.Texture.EXPLICIT_MODE:
  28758. this._defines.REFLECTIONMAP_EXPLICIT = true;
  28759. break;
  28760. case BABYLON.Texture.PLANAR_MODE:
  28761. this._defines.REFLECTIONMAP_PLANAR = true;
  28762. break;
  28763. case BABYLON.Texture.PROJECTION_MODE:
  28764. this._defines.REFLECTIONMAP_PROJECTION = true;
  28765. break;
  28766. case BABYLON.Texture.SKYBOX_MODE:
  28767. this._defines.REFLECTIONMAP_SKYBOX = true;
  28768. break;
  28769. case BABYLON.Texture.SPHERICAL_MODE:
  28770. this._defines.REFLECTIONMAP_SPHERICAL = true;
  28771. break;
  28772. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  28773. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  28774. break;
  28775. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  28776. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  28777. break;
  28778. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  28779. this._defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  28780. break;
  28781. }
  28782. if (this.reflectionTexture instanceof BABYLON.HDRCubeTexture && this.reflectionTexture) {
  28783. this._defines.USESPHERICALFROMREFLECTIONMAP = true;
  28784. if (this.reflectionTexture.isPMREM) {
  28785. this._defines.USEPMREMREFLECTION = true;
  28786. }
  28787. }
  28788. }
  28789. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  28790. if (!this.lightmapTexture.isReady()) {
  28791. return false;
  28792. }
  28793. needUVs = true;
  28794. this._defines.LIGHTMAP = true;
  28795. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  28796. }
  28797. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  28798. if (!this.emissiveTexture.isReady()) {
  28799. return false;
  28800. }
  28801. needUVs = true;
  28802. this._defines.EMISSIVE = true;
  28803. }
  28804. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  28805. if (this.metallicTexture) {
  28806. if (!this.metallicTexture.isReady()) {
  28807. return false;
  28808. }
  28809. needUVs = true;
  28810. this._defines.METALLICWORKFLOW = true;
  28811. this._defines.METALLICMAP = true;
  28812. this._defines.ROUGHNESSSTOREINMETALMAPALPHA = this.useRoughnessFromMetallicTextureAlpha;
  28813. this._defines.ROUGHNESSSTOREINMETALMAPGREEN = !this.useRoughnessFromMetallicTextureAlpha && this.useRoughnessFromMetallicTextureGreen;
  28814. this._defines.METALLNESSSTOREINMETALMAPBLUE = this.useMetallnessFromMetallicTextureBlue;
  28815. this._defines.AOSTOREINMETALMAPRED = this.useAmbientOcclusionFromMetallicTextureRed;
  28816. }
  28817. else if (this.reflectivityTexture) {
  28818. if (!this.reflectivityTexture.isReady()) {
  28819. return false;
  28820. }
  28821. needUVs = true;
  28822. this._defines.REFLECTIVITY = true;
  28823. this._defines.MICROSURFACEFROMREFLECTIVITYMAP = this.useMicroSurfaceFromReflectivityMapAlpha;
  28824. this._defines.MICROSURFACEAUTOMATIC = this.useAutoMicroSurfaceFromReflectivityMap;
  28825. }
  28826. if (this.microSurfaceTexture) {
  28827. if (!this.microSurfaceTexture.isReady()) {
  28828. return false;
  28829. }
  28830. needUVs = true;
  28831. this._defines.MICROSURFACEMAP = true;
  28832. }
  28833. }
  28834. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  28835. if (!this.bumpTexture.isReady()) {
  28836. return false;
  28837. }
  28838. needUVs = true;
  28839. this._defines.BUMP = true;
  28840. if (this.useParallax && this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  28841. this._defines.PARALLAX = true;
  28842. if (this.useParallaxOcclusion) {
  28843. this._defines.PARALLAXOCCLUSION = true;
  28844. }
  28845. }
  28846. if (this.invertNormalMapX) {
  28847. this._defines.INVERTNORMALMAPX = true;
  28848. }
  28849. if (this.invertNormalMapY) {
  28850. this._defines.INVERTNORMALMAPY = true;
  28851. }
  28852. if (scene._mirroredCameraPosition) {
  28853. this._defines.INVERTNORMALMAPX = !this._defines.INVERTNORMALMAPX;
  28854. this._defines.INVERTNORMALMAPY = !this._defines.INVERTNORMALMAPY;
  28855. }
  28856. }
  28857. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  28858. if (!this.refractionTexture.isReady()) {
  28859. return false;
  28860. }
  28861. needUVs = true;
  28862. this._defines.REFRACTION = true;
  28863. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  28864. if (this.linkRefractionWithTransparency) {
  28865. this._defines.LINKREFRACTIONTOTRANSPARENCY = true;
  28866. }
  28867. if (this.refractionTexture instanceof BABYLON.HDRCubeTexture) {
  28868. this._defines.REFRACTIONMAPINLINEARSPACE = true;
  28869. if (this.refractionTexture.isPMREM) {
  28870. this._defines.USEPMREMREFRACTION = true;
  28871. }
  28872. }
  28873. }
  28874. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  28875. if (!this.cameraColorGradingTexture.isReady()) {
  28876. return false;
  28877. }
  28878. this._defines.CAMERACOLORGRADING = true;
  28879. }
  28880. if (!this.backFaceCulling && this.twoSidedLighting) {
  28881. this._defines.TWOSIDEDLIGHTING = true;
  28882. }
  28883. }
  28884. // Effect
  28885. if (scene.clipPlane) {
  28886. this._defines.CLIPPLANE = true;
  28887. }
  28888. if (engine.getAlphaTesting()) {
  28889. this._defines.ALPHATEST = true;
  28890. }
  28891. if (this._shouldUseAlphaFromAlbedoTexture()) {
  28892. this._defines.ALPHAFROMALBEDO = true;
  28893. }
  28894. if (this.useEmissiveAsIllumination) {
  28895. this._defines.EMISSIVEASILLUMINATION = true;
  28896. }
  28897. if (this.linkEmissiveWithAlbedo) {
  28898. this._defines.LINKEMISSIVEWITHALBEDO = true;
  28899. }
  28900. if (this.useLogarithmicDepth) {
  28901. this._defines.LOGARITHMICDEPTH = true;
  28902. }
  28903. if (this.cameraContrast != 1) {
  28904. this._defines.CAMERACONTRAST = true;
  28905. }
  28906. if (this.cameraExposure != 1) {
  28907. this._defines.CAMERATONEMAP = true;
  28908. }
  28909. if (this.cameraColorCurves) {
  28910. this._defines.CAMERACOLORCURVES = true;
  28911. }
  28912. if (this.overloadedShadeIntensity != 1 ||
  28913. this.overloadedShadowIntensity != 1) {
  28914. this._defines.OVERLOADEDSHADOWVALUES = true;
  28915. }
  28916. if (this.overloadedMicroSurfaceIntensity > 0 ||
  28917. this.overloadedEmissiveIntensity > 0 ||
  28918. this.overloadedReflectivityIntensity > 0 ||
  28919. this.overloadedAlbedoIntensity > 0 ||
  28920. this.overloadedAmbientIntensity > 0 ||
  28921. this.overloadedReflectionIntensity > 0) {
  28922. this._defines.OVERLOADEDVALUES = true;
  28923. }
  28924. // Point size
  28925. if (this.pointsCloud || scene.forcePointsCloud) {
  28926. this._defines.POINTSIZE = true;
  28927. }
  28928. // Fog
  28929. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  28930. this._defines.FOG = true;
  28931. }
  28932. if (BABYLON.StandardMaterial.FresnelEnabled) {
  28933. // Fresnel
  28934. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  28935. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  28936. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  28937. this._defines.OPACITYFRESNEL = true;
  28938. }
  28939. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  28940. this._defines.EMISSIVEFRESNEL = true;
  28941. }
  28942. this._defines.FRESNEL = true;
  28943. }
  28944. }
  28945. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  28946. this._defines.SPECULAROVERALPHA = true;
  28947. }
  28948. if (this.usePhysicalLightFalloff) {
  28949. this._defines.USEPHYSICALLIGHTFALLOFF = true;
  28950. }
  28951. if (this.useRadianceOverAlpha) {
  28952. this._defines.RADIANCEOVERALPHA = true;
  28953. }
  28954. if ((this.metallic !== undefined && this.metallic !== null) || (this.roughness !== undefined && this.roughness !== null)) {
  28955. this._defines.METALLICWORKFLOW = true;
  28956. }
  28957. // Attribs
  28958. if (mesh) {
  28959. if (!mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  28960. mesh.createNormals(true);
  28961. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  28962. }
  28963. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  28964. this._defines.NORMAL = true;
  28965. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  28966. this._defines.TANGENT = true;
  28967. }
  28968. }
  28969. if (needUVs) {
  28970. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28971. this._defines.UV1 = true;
  28972. }
  28973. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  28974. this._defines.UV2 = true;
  28975. }
  28976. }
  28977. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  28978. this._defines.VERTEXCOLOR = true;
  28979. if (mesh.hasVertexAlpha) {
  28980. this._defines.VERTEXALPHA = true;
  28981. }
  28982. }
  28983. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  28984. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  28985. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  28986. }
  28987. // Instances
  28988. if (useInstances) {
  28989. this._defines.INSTANCES = true;
  28990. }
  28991. if (mesh.morphTargetManager) {
  28992. var manager = mesh.morphTargetManager;
  28993. this._defines.MORPHTARGETS_TANGENT = manager.supportsTangents && this._defines.TANGENT;
  28994. this._defines.MORPHTARGETS_NORMAL = manager.supportsNormals && this._defines.NORMAL;
  28995. this._defines.MORPHTARGETS = (manager.numInfluencers > 0);
  28996. this._defines.NUM_MORPH_INFLUENCERS = manager.numInfluencers;
  28997. }
  28998. }
  28999. // Get correct effect
  29000. if (!this._defines.isEqual(this._cachedDefines)) {
  29001. this._defines.cloneTo(this._cachedDefines);
  29002. scene.resetCachedMaterial();
  29003. // Fallbacks
  29004. var fallbacks = new BABYLON.EffectFallbacks();
  29005. if (this._defines.REFLECTION) {
  29006. fallbacks.addFallback(0, "REFLECTION");
  29007. }
  29008. if (this._defines.REFRACTION) {
  29009. fallbacks.addFallback(0, "REFRACTION");
  29010. }
  29011. if (this._defines.REFLECTIVITY) {
  29012. fallbacks.addFallback(0, "REFLECTIVITY");
  29013. }
  29014. if (this._defines.BUMP) {
  29015. fallbacks.addFallback(0, "BUMP");
  29016. }
  29017. if (this._defines.PARALLAX) {
  29018. fallbacks.addFallback(1, "PARALLAX");
  29019. }
  29020. if (this._defines.PARALLAXOCCLUSION) {
  29021. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  29022. }
  29023. if (this._defines.SPECULAROVERALPHA) {
  29024. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  29025. }
  29026. if (this._defines.FOG) {
  29027. fallbacks.addFallback(1, "FOG");
  29028. }
  29029. if (this._defines.POINTSIZE) {
  29030. fallbacks.addFallback(0, "POINTSIZE");
  29031. }
  29032. if (this._defines.LOGARITHMICDEPTH) {
  29033. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  29034. }
  29035. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  29036. if (this._defines.SPECULARTERM) {
  29037. fallbacks.addFallback(0, "SPECULARTERM");
  29038. }
  29039. if (this._defines.OPACITYFRESNEL) {
  29040. fallbacks.addFallback(1, "OPACITYFRESNEL");
  29041. }
  29042. if (this._defines.EMISSIVEFRESNEL) {
  29043. fallbacks.addFallback(2, "EMISSIVEFRESNEL");
  29044. }
  29045. if (this._defines.FRESNEL) {
  29046. fallbacks.addFallback(3, "FRESNEL");
  29047. }
  29048. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  29049. fallbacks.addCPUSkinningFallback(0, mesh);
  29050. }
  29051. //Attributes
  29052. var attribs = [BABYLON.VertexBuffer.PositionKind];
  29053. if (this._defines.NORMAL) {
  29054. attribs.push(BABYLON.VertexBuffer.NormalKind);
  29055. }
  29056. if (this._defines.TANGENT) {
  29057. attribs.push(BABYLON.VertexBuffer.TangentKind);
  29058. }
  29059. if (this._defines.UV1) {
  29060. attribs.push(BABYLON.VertexBuffer.UVKind);
  29061. }
  29062. if (this._defines.UV2) {
  29063. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  29064. }
  29065. if (this._defines.VERTEXCOLOR) {
  29066. attribs.push(BABYLON.VertexBuffer.ColorKind);
  29067. }
  29068. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  29069. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  29070. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, this._defines);
  29071. // Legacy browser patch
  29072. var join = this._defines.toString();
  29073. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  29074. "vFogInfos", "vFogColor", "pointSize",
  29075. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  29076. "mBones",
  29077. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  29078. "depthValues",
  29079. "opacityParts", "emissiveLeftColor", "emissiveRightColor",
  29080. "vLightingIntensity", "vOverloadedShadowIntensity", "vOverloadedIntensity", "vOverloadedAlbedo", "vOverloadedReflection", "vOverloadedReflectivity", "vOverloadedEmissive", "vOverloadedMicroSurface",
  29081. "logarithmicDepthConstant",
  29082. "vSphericalX", "vSphericalY", "vSphericalZ",
  29083. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  29084. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  29085. "vMicrosurfaceTextureLods",
  29086. "vCameraInfos"
  29087. ];
  29088. var samplers = ["albedoSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "reflectivitySampler", "microSurfaceSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  29089. var uniformBuffers = ["Material", "Scene"];
  29090. if (this._defines.CAMERACOLORCURVES) {
  29091. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  29092. }
  29093. if (this._defines.CAMERACOLORGRADING) {
  29094. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  29095. }
  29096. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  29097. uniformsNames: uniforms,
  29098. uniformBuffersNames: uniformBuffers,
  29099. samplers: samplers,
  29100. defines: this._defines,
  29101. maxSimultaneousLights: this.maxSimultaneousLights
  29102. });
  29103. var onCompiled = function (effect) {
  29104. if (this.onCompiled) {
  29105. this.onCompiled(effect);
  29106. }
  29107. this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  29108. }.bind(this);
  29109. this._effect = scene.getEngine().createEffect("pbr", {
  29110. attributes: attribs,
  29111. uniformsNames: uniforms,
  29112. uniformBuffersNames: uniformBuffers,
  29113. samplers: samplers,
  29114. defines: join,
  29115. fallbacks: fallbacks,
  29116. onCompiled: onCompiled,
  29117. onError: this.onError,
  29118. indexParameters: { maxSimultaneousLights: this.maxSimultaneousLights, maxSimultaneousMorphTargets: this._defines.NUM_MORPH_INFLUENCERS }
  29119. }, engine);
  29120. this.buildUniformLayout();
  29121. }
  29122. if (!this._effect.isReady()) {
  29123. return false;
  29124. }
  29125. this._renderId = scene.getRenderId();
  29126. this._wasPreviouslyReady = true;
  29127. return true;
  29128. };
  29129. PBRMaterial.prototype.buildUniformLayout = function () {
  29130. // Order is important !
  29131. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  29132. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  29133. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  29134. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  29135. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  29136. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  29137. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  29138. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  29139. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  29140. this._uniformBuffer.addUniform("vBumpInfos", 3);
  29141. this._uniformBuffer.addUniform("albedoMatrix", 16);
  29142. this._uniformBuffer.addUniform("ambientMatrix", 16);
  29143. this._uniformBuffer.addUniform("opacityMatrix", 16);
  29144. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  29145. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  29146. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  29147. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  29148. this._uniformBuffer.addUniform("bumpMatrix", 16);
  29149. this._uniformBuffer.addUniform("refractionMatrix", 16);
  29150. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  29151. this._uniformBuffer.addUniform("vReflectionColor", 3);
  29152. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  29153. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  29154. this._uniformBuffer.addUniform("vMicrosurfaceTextureLods", 2);
  29155. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  29156. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  29157. this._uniformBuffer.addUniform("opacityParts", 4);
  29158. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  29159. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  29160. this._uniformBuffer.addUniform("vOverloadedIntensity", 4);
  29161. this._uniformBuffer.addUniform("vOverloadedAmbient", 3);
  29162. this._uniformBuffer.addUniform("vOverloadedAlbedo", 3);
  29163. this._uniformBuffer.addUniform("vOverloadedReflectivity", 3);
  29164. this._uniformBuffer.addUniform("vOverloadedEmissive", 3);
  29165. this._uniformBuffer.addUniform("vOverloadedReflection", 3);
  29166. this._uniformBuffer.addUniform("vOverloadedMicroSurface", 3);
  29167. this._uniformBuffer.addUniform("vOverloadedShadowIntensity", 4);
  29168. this._uniformBuffer.addUniform("pointSize", 1);
  29169. this._uniformBuffer.create();
  29170. };
  29171. PBRMaterial.prototype.unbind = function () {
  29172. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  29173. this._uniformBuffer.setTexture("reflection2DSampler", null);
  29174. }
  29175. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  29176. this._uniformBuffer.setTexture("refraction2DSampler", null);
  29177. }
  29178. _super.prototype.unbind.call(this);
  29179. };
  29180. PBRMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  29181. this._effect.setMatrix("world", world);
  29182. };
  29183. PBRMaterial.prototype.bind = function (world, mesh) {
  29184. this._myScene = this.getScene();
  29185. var effect = this._effect;
  29186. // Matrices
  29187. this.bindOnlyWorldMatrix(world);
  29188. // Bones
  29189. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  29190. if (this._myScene.getCachedMaterial() !== this) {
  29191. this._uniformBuffer.bindToEffect(effect, "Material");
  29192. this.bindViewProjection(effect);
  29193. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  29194. // Fresnel
  29195. if (BABYLON.StandardMaterial.FresnelEnabled) {
  29196. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  29197. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  29198. }
  29199. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  29200. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  29201. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  29202. }
  29203. }
  29204. // Texture uniforms
  29205. if (this._myScene.texturesEnabled) {
  29206. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  29207. this._uniformBuffer.updateFloat2("vAlbedoInfos", this.albedoTexture.coordinatesIndex, this.albedoTexture.level);
  29208. this._uniformBuffer.updateMatrix("albedoMatrix", this.albedoTexture.getTextureMatrix());
  29209. }
  29210. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  29211. this._uniformBuffer.updateFloat3("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level, this.ambientTextureStrength);
  29212. this._uniformBuffer.updateMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  29213. }
  29214. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  29215. this._uniformBuffer.updateFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  29216. this._uniformBuffer.updateMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  29217. }
  29218. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  29219. this._microsurfaceTextureLods.x = Math.round(Math.log(this.reflectionTexture.getSize().width) * Math.LOG2E);
  29220. this._uniformBuffer.updateMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  29221. this._uniformBuffer.updateFloat2("vReflectionInfos", this.reflectionTexture.level, 0);
  29222. if (this._defines.USESPHERICALFROMREFLECTIONMAP) {
  29223. this._effect.setFloat3("vSphericalX", this.reflectionTexture.sphericalPolynomial.x.x, this.reflectionTexture.sphericalPolynomial.x.y, this.reflectionTexture.sphericalPolynomial.x.z);
  29224. this._effect.setFloat3("vSphericalY", this.reflectionTexture.sphericalPolynomial.y.x, this.reflectionTexture.sphericalPolynomial.y.y, this.reflectionTexture.sphericalPolynomial.y.z);
  29225. this._effect.setFloat3("vSphericalZ", this.reflectionTexture.sphericalPolynomial.z.x, this.reflectionTexture.sphericalPolynomial.z.y, this.reflectionTexture.sphericalPolynomial.z.z);
  29226. this._effect.setFloat3("vSphericalXX", this.reflectionTexture.sphericalPolynomial.xx.x, this.reflectionTexture.sphericalPolynomial.xx.y, this.reflectionTexture.sphericalPolynomial.xx.z);
  29227. this._effect.setFloat3("vSphericalYY", this.reflectionTexture.sphericalPolynomial.yy.x, this.reflectionTexture.sphericalPolynomial.yy.y, this.reflectionTexture.sphericalPolynomial.yy.z);
  29228. this._effect.setFloat3("vSphericalZZ", this.reflectionTexture.sphericalPolynomial.zz.x, this.reflectionTexture.sphericalPolynomial.zz.y, this.reflectionTexture.sphericalPolynomial.zz.z);
  29229. this._effect.setFloat3("vSphericalXY", this.reflectionTexture.sphericalPolynomial.xy.x, this.reflectionTexture.sphericalPolynomial.xy.y, this.reflectionTexture.sphericalPolynomial.xy.z);
  29230. this._effect.setFloat3("vSphericalYZ", this.reflectionTexture.sphericalPolynomial.yz.x, this.reflectionTexture.sphericalPolynomial.yz.y, this.reflectionTexture.sphericalPolynomial.yz.z);
  29231. this._effect.setFloat3("vSphericalZX", this.reflectionTexture.sphericalPolynomial.zx.x, this.reflectionTexture.sphericalPolynomial.zx.y, this.reflectionTexture.sphericalPolynomial.zx.z);
  29232. }
  29233. }
  29234. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  29235. this._uniformBuffer.updateFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  29236. this._uniformBuffer.updateMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  29237. }
  29238. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  29239. this._uniformBuffer.updateFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  29240. this._uniformBuffer.updateMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  29241. }
  29242. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  29243. if (this.metallicTexture) {
  29244. this._uniformBuffer.updateFloat3("vReflectivityInfos", this.metallicTexture.coordinatesIndex, this.metallicTexture.level, this.ambientTextureStrength);
  29245. this._uniformBuffer.updateMatrix("reflectivityMatrix", this.metallicTexture.getTextureMatrix());
  29246. }
  29247. else if (this.reflectivityTexture) {
  29248. this._uniformBuffer.updateFloat3("vReflectivityInfos", this.reflectivityTexture.coordinatesIndex, this.reflectivityTexture.level, 1.0);
  29249. this._uniformBuffer.updateMatrix("reflectivityMatrix", this.reflectivityTexture.getTextureMatrix());
  29250. }
  29251. if (this.microSurfaceTexture) {
  29252. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this.microSurfaceTexture.coordinatesIndex, this.microSurfaceTexture.level);
  29253. this._uniformBuffer.updateMatrix("microSurfaceSamplerMatrix", this.microSurfaceTexture.getTextureMatrix());
  29254. }
  29255. }
  29256. if (this.bumpTexture && this._myScene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  29257. this._uniformBuffer.updateFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  29258. this._uniformBuffer.updateMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  29259. }
  29260. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  29261. this._microsurfaceTextureLods.y = Math.round(Math.log(this.refractionTexture.getSize().width) * Math.LOG2E);
  29262. var depth = 1.0;
  29263. if (!this.refractionTexture.isCube) {
  29264. this._uniformBuffer.updateMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  29265. if (this.refractionTexture.depth) {
  29266. depth = this.refractionTexture.depth;
  29267. }
  29268. }
  29269. this._uniformBuffer.updateFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  29270. }
  29271. if ((this.reflectionTexture || this.refractionTexture)) {
  29272. this._uniformBuffer.updateFloat2("vMicrosurfaceTextureLods", this._microsurfaceTextureLods.x, this._microsurfaceTextureLods.y);
  29273. }
  29274. }
  29275. // Point size
  29276. if (this.pointsCloud) {
  29277. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  29278. }
  29279. // Colors
  29280. if (this._defines.METALLICWORKFLOW) {
  29281. PBRMaterial._scaledReflectivity.r = (this.metallic === undefined || this.metallic === null) ? 1 : this.metallic;
  29282. PBRMaterial._scaledReflectivity.g = (this.roughness === undefined || this.roughness === null) ? 1 : this.roughness;
  29283. this._uniformBuffer.updateColor4("vReflectivityColor", PBRMaterial._scaledReflectivity, 0);
  29284. }
  29285. else {
  29286. // GAMMA CORRECTION.
  29287. this.convertColorToLinearSpaceToRef(this.reflectivityColor, PBRMaterial._scaledReflectivity);
  29288. this._uniformBuffer.updateColor4("vReflectivityColor", PBRMaterial._scaledReflectivity, this.microSurface);
  29289. }
  29290. // GAMMA CORRECTION.
  29291. this.convertColorToLinearSpaceToRef(this.emissiveColor, PBRMaterial._scaledEmissive);
  29292. this._uniformBuffer.updateColor3("vEmissiveColor", PBRMaterial._scaledEmissive);
  29293. // GAMMA CORRECTION.
  29294. this.convertColorToLinearSpaceToRef(this.reflectionColor, PBRMaterial._scaledReflection);
  29295. this._uniformBuffer.updateColor3("vReflectionColor", PBRMaterial._scaledReflection);
  29296. // GAMMA CORRECTION.
  29297. this.convertColorToLinearSpaceToRef(this.albedoColor, PBRMaterial._scaledAlbedo);
  29298. this._uniformBuffer.updateColor4("vAlbedoColor", PBRMaterial._scaledAlbedo, this.alpha * mesh.visibility);
  29299. // Misc
  29300. this._lightingInfos.x = this.directIntensity;
  29301. this._lightingInfos.y = this.emissiveIntensity;
  29302. this._lightingInfos.z = this.environmentIntensity;
  29303. this._lightingInfos.w = this.specularIntensity;
  29304. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  29305. // Overloaded params
  29306. this._overloadedShadowInfos.x = this.overloadedShadowIntensity;
  29307. this._overloadedShadowInfos.y = this.overloadedShadeIntensity;
  29308. this._uniformBuffer.updateVector4("vOverloadedShadowIntensity", this._overloadedShadowInfos);
  29309. this._overloadedIntensity.x = this.overloadedAmbientIntensity;
  29310. this._overloadedIntensity.y = this.overloadedAlbedoIntensity;
  29311. this._overloadedIntensity.z = this.overloadedReflectivityIntensity;
  29312. this._overloadedIntensity.w = this.overloadedEmissiveIntensity;
  29313. this._uniformBuffer.updateVector4("vOverloadedIntensity", this._overloadedIntensity);
  29314. this._uniformBuffer.updateColor3("vOverloadedAmbient", this.overloadedAmbient);
  29315. this.convertColorToLinearSpaceToRef(this.overloadedAlbedo, this._tempColor);
  29316. this._uniformBuffer.updateColor3("vOverloadedAlbedo", this._tempColor);
  29317. this.convertColorToLinearSpaceToRef(this.overloadedReflectivity, this._tempColor);
  29318. this._uniformBuffer.updateColor3("vOverloadedReflectivity", this._tempColor);
  29319. this.convertColorToLinearSpaceToRef(this.overloadedEmissive, this._tempColor);
  29320. this._uniformBuffer.updateColor3("vOverloadedEmissive", this._tempColor);
  29321. this.convertColorToLinearSpaceToRef(this.overloadedReflection, this._tempColor);
  29322. this._uniformBuffer.updateColor3("vOverloadedReflection", this._tempColor);
  29323. this._overloadedMicroSurface.x = this.overloadedMicroSurface;
  29324. this._overloadedMicroSurface.y = this.overloadedMicroSurfaceIntensity;
  29325. this._overloadedMicroSurface.z = this.overloadedReflectionIntensity;
  29326. this._uniformBuffer.updateVector3("vOverloadedMicroSurface", this._overloadedMicroSurface);
  29327. }
  29328. // Textures
  29329. if (this._myScene.texturesEnabled) {
  29330. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  29331. this._uniformBuffer.setTexture("albedoSampler", this.albedoTexture);
  29332. }
  29333. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  29334. this._uniformBuffer.setTexture("ambientSampler", this.ambientTexture);
  29335. }
  29336. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  29337. this._uniformBuffer.setTexture("opacitySampler", this.opacityTexture);
  29338. }
  29339. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  29340. if (this.reflectionTexture.isCube) {
  29341. this._uniformBuffer.setTexture("reflectionCubeSampler", this.reflectionTexture);
  29342. }
  29343. else {
  29344. this._uniformBuffer.setTexture("reflection2DSampler", this.reflectionTexture);
  29345. }
  29346. }
  29347. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  29348. this._uniformBuffer.setTexture("emissiveSampler", this.emissiveTexture);
  29349. }
  29350. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  29351. this._uniformBuffer.setTexture("lightmapSampler", this.lightmapTexture);
  29352. }
  29353. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  29354. if (this.metallicTexture) {
  29355. this._uniformBuffer.setTexture("reflectivitySampler", this.metallicTexture);
  29356. }
  29357. else if (this.reflectivityTexture) {
  29358. this._uniformBuffer.setTexture("reflectivitySampler", this.reflectivityTexture);
  29359. }
  29360. if (this.microSurfaceTexture) {
  29361. this._uniformBuffer.setTexture("microSurfaceSampler", this.microSurfaceTexture);
  29362. }
  29363. }
  29364. if (this.bumpTexture && this._myScene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  29365. this._uniformBuffer.setTexture("bumpSampler", this.bumpTexture);
  29366. }
  29367. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  29368. if (this.refractionTexture.isCube) {
  29369. this._uniformBuffer.setTexture("refractionCubeSampler", this.refractionTexture);
  29370. }
  29371. else {
  29372. this._uniformBuffer.setTexture("refraction2DSampler", this.refractionTexture);
  29373. }
  29374. }
  29375. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  29376. BABYLON.ColorGradingTexture.Bind(this.cameraColorGradingTexture, this._effect);
  29377. }
  29378. }
  29379. // Clip plane
  29380. BABYLON.MaterialHelper.BindClipPlane(this._effect, this._myScene);
  29381. // Colors
  29382. this._myScene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  29383. effect.setVector3("vEyePosition", this._myScene._mirroredCameraPosition ? this._myScene._mirroredCameraPosition : this._myScene.activeCamera.position);
  29384. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  29385. }
  29386. if (this._myScene.getCachedMaterial() !== this || !this.isFrozen) {
  29387. // Lights
  29388. if (this._myScene.lightsEnabled && !this.disableLighting) {
  29389. PBRMaterial.BindLights(this._myScene, mesh, this._effect, this._defines, this.useScalarInLinearSpace, this.maxSimultaneousLights, this.usePhysicalLightFalloff);
  29390. }
  29391. // View
  29392. if (this._myScene.fogEnabled && mesh.applyFog && this._myScene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  29393. this.bindView(effect);
  29394. }
  29395. // Fog
  29396. BABYLON.MaterialHelper.BindFogParameters(this._myScene, mesh, this._effect);
  29397. // Morph targets
  29398. if (this._defines.NUM_MORPH_INFLUENCERS) {
  29399. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  29400. }
  29401. this._cameraInfos.x = this.cameraExposure;
  29402. this._cameraInfos.y = this.cameraContrast;
  29403. effect.setVector4("vCameraInfos", this._cameraInfos);
  29404. if (this.cameraColorCurves) {
  29405. BABYLON.ColorCurves.Bind(this.cameraColorCurves, this._effect);
  29406. }
  29407. // Log. depth
  29408. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, this._myScene);
  29409. }
  29410. this._uniformBuffer.update();
  29411. this._afterBind(mesh);
  29412. this._myScene = null;
  29413. };
  29414. PBRMaterial.prototype.getAnimatables = function () {
  29415. var results = [];
  29416. if (this.albedoTexture && this.albedoTexture.animations && this.albedoTexture.animations.length > 0) {
  29417. results.push(this.albedoTexture);
  29418. }
  29419. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  29420. results.push(this.ambientTexture);
  29421. }
  29422. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  29423. results.push(this.opacityTexture);
  29424. }
  29425. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  29426. results.push(this.reflectionTexture);
  29427. }
  29428. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  29429. results.push(this.emissiveTexture);
  29430. }
  29431. if (this.metallicTexture && this.metallicTexture.animations && this.metallicTexture.animations.length > 0) {
  29432. results.push(this.metallicTexture);
  29433. }
  29434. else if (this.reflectivityTexture && this.reflectivityTexture.animations && this.reflectivityTexture.animations.length > 0) {
  29435. results.push(this.reflectivityTexture);
  29436. }
  29437. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  29438. results.push(this.bumpTexture);
  29439. }
  29440. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  29441. results.push(this.lightmapTexture);
  29442. }
  29443. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  29444. results.push(this.refractionTexture);
  29445. }
  29446. if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
  29447. results.push(this.cameraColorGradingTexture);
  29448. }
  29449. return results;
  29450. };
  29451. PBRMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  29452. if (forceDisposeTextures) {
  29453. if (this.albedoTexture) {
  29454. this.albedoTexture.dispose();
  29455. }
  29456. if (this.ambientTexture) {
  29457. this.ambientTexture.dispose();
  29458. }
  29459. if (this.opacityTexture) {
  29460. this.opacityTexture.dispose();
  29461. }
  29462. if (this.reflectionTexture) {
  29463. this.reflectionTexture.dispose();
  29464. }
  29465. if (this.emissiveTexture) {
  29466. this.emissiveTexture.dispose();
  29467. }
  29468. if (this.metallicTexture) {
  29469. this.metallicTexture.dispose();
  29470. }
  29471. if (this.reflectivityTexture) {
  29472. this.reflectivityTexture.dispose();
  29473. }
  29474. if (this.bumpTexture) {
  29475. this.bumpTexture.dispose();
  29476. }
  29477. if (this.lightmapTexture) {
  29478. this.lightmapTexture.dispose();
  29479. }
  29480. if (this.refractionTexture) {
  29481. this.refractionTexture.dispose();
  29482. }
  29483. if (this.cameraColorGradingTexture) {
  29484. this.cameraColorGradingTexture.dispose();
  29485. }
  29486. }
  29487. this._renderTargets.dispose();
  29488. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  29489. };
  29490. PBRMaterial.prototype.clone = function (name) {
  29491. var _this = this;
  29492. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  29493. };
  29494. PBRMaterial.prototype.serialize = function () {
  29495. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  29496. serializationObject.customType = "BABYLON.PBRMaterial";
  29497. return serializationObject;
  29498. };
  29499. // Statics
  29500. PBRMaterial.Parse = function (source, scene, rootUrl) {
  29501. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  29502. };
  29503. return PBRMaterial;
  29504. }(BABYLON.Material));
  29505. PBRMaterial._scaledAlbedo = new BABYLON.Color3();
  29506. PBRMaterial._scaledReflectivity = new BABYLON.Color3();
  29507. PBRMaterial._scaledEmissive = new BABYLON.Color3();
  29508. PBRMaterial._scaledReflection = new BABYLON.Color3();
  29509. __decorate([
  29510. BABYLON.serialize()
  29511. ], PBRMaterial.prototype, "directIntensity", void 0);
  29512. __decorate([
  29513. BABYLON.serialize()
  29514. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  29515. __decorate([
  29516. BABYLON.serialize()
  29517. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  29518. __decorate([
  29519. BABYLON.serialize()
  29520. ], PBRMaterial.prototype, "specularIntensity", void 0);
  29521. __decorate([
  29522. BABYLON.serialize()
  29523. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  29524. __decorate([
  29525. BABYLON.serialize()
  29526. ], PBRMaterial.prototype, "overloadedShadowIntensity", void 0);
  29527. __decorate([
  29528. BABYLON.serialize()
  29529. ], PBRMaterial.prototype, "overloadedShadeIntensity", void 0);
  29530. __decorate([
  29531. BABYLON.serialize()
  29532. ], PBRMaterial.prototype, "cameraExposure", void 0);
  29533. __decorate([
  29534. BABYLON.serialize()
  29535. ], PBRMaterial.prototype, "cameraContrast", void 0);
  29536. __decorate([
  29537. BABYLON.serializeAsTexture()
  29538. ], PBRMaterial.prototype, "cameraColorGradingTexture", void 0);
  29539. __decorate([
  29540. BABYLON.serializeAsColorCurves()
  29541. ], PBRMaterial.prototype, "cameraColorCurves", void 0);
  29542. __decorate([
  29543. BABYLON.serializeAsColor3()
  29544. ], PBRMaterial.prototype, "overloadedAmbient", void 0);
  29545. __decorate([
  29546. BABYLON.serialize()
  29547. ], PBRMaterial.prototype, "overloadedAmbientIntensity", void 0);
  29548. __decorate([
  29549. BABYLON.serializeAsColor3()
  29550. ], PBRMaterial.prototype, "overloadedAlbedo", void 0);
  29551. __decorate([
  29552. BABYLON.serialize()
  29553. ], PBRMaterial.prototype, "overloadedAlbedoIntensity", void 0);
  29554. __decorate([
  29555. BABYLON.serializeAsColor3()
  29556. ], PBRMaterial.prototype, "overloadedReflectivity", void 0);
  29557. __decorate([
  29558. BABYLON.serialize()
  29559. ], PBRMaterial.prototype, "overloadedReflectivityIntensity", void 0);
  29560. __decorate([
  29561. BABYLON.serializeAsColor3()
  29562. ], PBRMaterial.prototype, "overloadedEmissive", void 0);
  29563. __decorate([
  29564. BABYLON.serialize()
  29565. ], PBRMaterial.prototype, "overloadedEmissiveIntensity", void 0);
  29566. __decorate([
  29567. BABYLON.serializeAsColor3()
  29568. ], PBRMaterial.prototype, "overloadedReflection", void 0);
  29569. __decorate([
  29570. BABYLON.serialize()
  29571. ], PBRMaterial.prototype, "overloadedReflectionIntensity", void 0);
  29572. __decorate([
  29573. BABYLON.serialize()
  29574. ], PBRMaterial.prototype, "overloadedMicroSurface", void 0);
  29575. __decorate([
  29576. BABYLON.serialize()
  29577. ], PBRMaterial.prototype, "overloadedMicroSurfaceIntensity", void 0);
  29578. __decorate([
  29579. BABYLON.serializeAsTexture()
  29580. ], PBRMaterial.prototype, "albedoTexture", void 0);
  29581. __decorate([
  29582. BABYLON.serializeAsTexture()
  29583. ], PBRMaterial.prototype, "ambientTexture", void 0);
  29584. __decorate([
  29585. BABYLON.serialize()
  29586. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  29587. __decorate([
  29588. BABYLON.serializeAsTexture()
  29589. ], PBRMaterial.prototype, "opacityTexture", void 0);
  29590. __decorate([
  29591. BABYLON.serializeAsTexture()
  29592. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  29593. __decorate([
  29594. BABYLON.serializeAsTexture()
  29595. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  29596. __decorate([
  29597. BABYLON.serializeAsTexture()
  29598. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  29599. __decorate([
  29600. BABYLON.serializeAsTexture()
  29601. ], PBRMaterial.prototype, "metallicTexture", void 0);
  29602. __decorate([
  29603. BABYLON.serialize()
  29604. ], PBRMaterial.prototype, "metallic", void 0);
  29605. __decorate([
  29606. BABYLON.serialize()
  29607. ], PBRMaterial.prototype, "roughness", void 0);
  29608. __decorate([
  29609. BABYLON.serializeAsTexture()
  29610. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  29611. __decorate([
  29612. BABYLON.serializeAsTexture()
  29613. ], PBRMaterial.prototype, "bumpTexture", void 0);
  29614. __decorate([
  29615. BABYLON.serializeAsTexture()
  29616. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  29617. __decorate([
  29618. BABYLON.serializeAsTexture()
  29619. ], PBRMaterial.prototype, "refractionTexture", void 0);
  29620. __decorate([
  29621. BABYLON.serializeAsColor3("ambient")
  29622. ], PBRMaterial.prototype, "ambientColor", void 0);
  29623. __decorate([
  29624. BABYLON.serializeAsColor3("albedo")
  29625. ], PBRMaterial.prototype, "albedoColor", void 0);
  29626. __decorate([
  29627. BABYLON.serializeAsColor3("reflectivity")
  29628. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  29629. __decorate([
  29630. BABYLON.serializeAsColor3("reflection")
  29631. ], PBRMaterial.prototype, "reflectionColor", void 0);
  29632. __decorate([
  29633. BABYLON.serializeAsColor3("emissive")
  29634. ], PBRMaterial.prototype, "emissiveColor", void 0);
  29635. __decorate([
  29636. BABYLON.serialize()
  29637. ], PBRMaterial.prototype, "microSurface", void 0);
  29638. __decorate([
  29639. BABYLON.serialize()
  29640. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  29641. __decorate([
  29642. BABYLON.serialize()
  29643. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  29644. __decorate([
  29645. BABYLON.serializeAsFresnelParameters()
  29646. ], PBRMaterial.prototype, "opacityFresnelParameters", void 0);
  29647. __decorate([
  29648. BABYLON.serializeAsFresnelParameters()
  29649. ], PBRMaterial.prototype, "emissiveFresnelParameters", void 0);
  29650. __decorate([
  29651. BABYLON.serialize()
  29652. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  29653. __decorate([
  29654. BABYLON.serialize()
  29655. ], PBRMaterial.prototype, "linkEmissiveWithAlbedo", void 0);
  29656. __decorate([
  29657. BABYLON.serialize()
  29658. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  29659. __decorate([
  29660. BABYLON.serialize()
  29661. ], PBRMaterial.prototype, "useEmissiveAsIllumination", void 0);
  29662. __decorate([
  29663. BABYLON.serialize()
  29664. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  29665. __decorate([
  29666. BABYLON.serialize()
  29667. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  29668. __decorate([
  29669. BABYLON.serialize()
  29670. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  29671. __decorate([
  29672. BABYLON.serialize()
  29673. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  29674. __decorate([
  29675. BABYLON.serialize()
  29676. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  29677. __decorate([
  29678. BABYLON.serialize()
  29679. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  29680. __decorate([
  29681. BABYLON.serialize()
  29682. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  29683. __decorate([
  29684. BABYLON.serialize()
  29685. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  29686. __decorate([
  29687. BABYLON.serialize()
  29688. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  29689. __decorate([
  29690. BABYLON.serialize()
  29691. ], PBRMaterial.prototype, "useScalarInLinearSpace", void 0);
  29692. __decorate([
  29693. BABYLON.serialize()
  29694. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  29695. __decorate([
  29696. BABYLON.serialize()
  29697. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  29698. __decorate([
  29699. BABYLON.serialize()
  29700. ], PBRMaterial.prototype, "useParallax", void 0);
  29701. __decorate([
  29702. BABYLON.serialize()
  29703. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  29704. __decorate([
  29705. BABYLON.serialize()
  29706. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  29707. __decorate([
  29708. BABYLON.serialize()
  29709. ], PBRMaterial.prototype, "disableLighting", void 0);
  29710. __decorate([
  29711. BABYLON.serialize()
  29712. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  29713. __decorate([
  29714. BABYLON.serialize()
  29715. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  29716. __decorate([
  29717. BABYLON.serialize()
  29718. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  29719. __decorate([
  29720. BABYLON.serialize()
  29721. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  29722. __decorate([
  29723. BABYLON.serialize()
  29724. ], PBRMaterial.prototype, "useLogarithmicDepth", null);
  29725. BABYLON.PBRMaterial = PBRMaterial;
  29726. })(BABYLON || (BABYLON = {}));
  29727. //# sourceMappingURL=babylon.pbrMaterial.js.map
  29728. var BABYLON;
  29729. (function (BABYLON) {
  29730. BABYLON.CameraInputTypes = {};
  29731. var CameraInputsManager = (function () {
  29732. function CameraInputsManager(camera) {
  29733. this.attached = {};
  29734. this.camera = camera;
  29735. this.checkInputs = function () { };
  29736. }
  29737. CameraInputsManager.prototype.add = function (input) {
  29738. var type = input.getSimpleName();
  29739. if (this.attached[type]) {
  29740. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  29741. return;
  29742. }
  29743. this.attached[type] = input;
  29744. input.camera = this.camera;
  29745. //for checkInputs, we are dynamically creating a function
  29746. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  29747. if (input.checkInputs) {
  29748. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  29749. }
  29750. if (this.attachedElement) {
  29751. input.attachControl(this.attachedElement);
  29752. }
  29753. };
  29754. CameraInputsManager.prototype.remove = function (inputToRemove) {
  29755. for (var cam in this.attached) {
  29756. var input = this.attached[cam];
  29757. if (input === inputToRemove) {
  29758. input.detachControl(this.attachedElement);
  29759. delete this.attached[cam];
  29760. this.rebuildInputCheck();
  29761. }
  29762. }
  29763. };
  29764. CameraInputsManager.prototype.removeByType = function (inputType) {
  29765. for (var cam in this.attached) {
  29766. var input = this.attached[cam];
  29767. if (input.getTypeName() === inputType) {
  29768. input.detachControl(this.attachedElement);
  29769. delete this.attached[cam];
  29770. this.rebuildInputCheck();
  29771. }
  29772. }
  29773. };
  29774. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  29775. var current = this.checkInputs;
  29776. return function () {
  29777. current();
  29778. fn();
  29779. };
  29780. };
  29781. CameraInputsManager.prototype.attachInput = function (input) {
  29782. input.attachControl(this.attachedElement, this.noPreventDefault);
  29783. };
  29784. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  29785. if (this.attachedElement) {
  29786. return;
  29787. }
  29788. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  29789. this.attachedElement = element;
  29790. this.noPreventDefault = noPreventDefault;
  29791. for (var cam in this.attached) {
  29792. var input = this.attached[cam];
  29793. this.attached[cam].attachControl(element, noPreventDefault);
  29794. }
  29795. };
  29796. CameraInputsManager.prototype.detachElement = function (element) {
  29797. if (this.attachedElement !== element) {
  29798. return;
  29799. }
  29800. for (var cam in this.attached) {
  29801. var input = this.attached[cam];
  29802. this.attached[cam].detachControl(element);
  29803. }
  29804. this.attachedElement = null;
  29805. };
  29806. CameraInputsManager.prototype.rebuildInputCheck = function () {
  29807. this.checkInputs = function () { };
  29808. for (var cam in this.attached) {
  29809. var input = this.attached[cam];
  29810. if (input.checkInputs) {
  29811. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  29812. }
  29813. }
  29814. };
  29815. CameraInputsManager.prototype.clear = function () {
  29816. if (this.attachedElement) {
  29817. this.detachElement(this.attachedElement);
  29818. }
  29819. this.attached = {};
  29820. this.attachedElement = null;
  29821. this.checkInputs = function () { };
  29822. };
  29823. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  29824. var inputs = {};
  29825. for (var cam in this.attached) {
  29826. var input = this.attached[cam];
  29827. var res = BABYLON.SerializationHelper.Serialize(input);
  29828. inputs[input.getTypeName()] = res;
  29829. }
  29830. serializedCamera.inputsmgr = inputs;
  29831. };
  29832. CameraInputsManager.prototype.parse = function (parsedCamera) {
  29833. var parsedInputs = parsedCamera.inputsmgr;
  29834. if (parsedInputs) {
  29835. this.clear();
  29836. for (var n in parsedInputs) {
  29837. var construct = BABYLON.CameraInputTypes[n];
  29838. if (construct) {
  29839. var parsedinput = parsedInputs[n];
  29840. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  29841. this.add(input);
  29842. }
  29843. }
  29844. }
  29845. else {
  29846. //2016-03-08 this part is for managing backward compatibility
  29847. for (var n in this.attached) {
  29848. var construct = BABYLON.CameraInputTypes[this.attached[n].getTypeName()];
  29849. if (construct) {
  29850. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  29851. this.remove(this.attached[n]);
  29852. this.add(input);
  29853. }
  29854. }
  29855. }
  29856. };
  29857. return CameraInputsManager;
  29858. }());
  29859. BABYLON.CameraInputsManager = CameraInputsManager;
  29860. })(BABYLON || (BABYLON = {}));
  29861. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  29862. var BABYLON;
  29863. (function (BABYLON) {
  29864. var FreeCameraMouseInput = (function () {
  29865. function FreeCameraMouseInput(touchEnabled) {
  29866. if (touchEnabled === void 0) { touchEnabled = true; }
  29867. this.touchEnabled = touchEnabled;
  29868. this.buttons = [0, 1, 2];
  29869. this.angularSensibility = 2000.0;
  29870. }
  29871. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  29872. var _this = this;
  29873. var engine = this.camera.getEngine();
  29874. if (!this._pointerInput) {
  29875. this._pointerInput = function (p, s) {
  29876. var evt = p.event;
  29877. if (!_this.touchEnabled && evt.pointerType === "touch") {
  29878. return;
  29879. }
  29880. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  29881. return;
  29882. }
  29883. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  29884. try {
  29885. evt.srcElement.setPointerCapture(evt.pointerId);
  29886. }
  29887. catch (e) {
  29888. //Nothing to do with the error. Execution will continue.
  29889. }
  29890. _this.previousPosition = {
  29891. x: evt.clientX,
  29892. y: evt.clientY
  29893. };
  29894. if (!noPreventDefault) {
  29895. evt.preventDefault();
  29896. element.focus();
  29897. }
  29898. }
  29899. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  29900. try {
  29901. evt.srcElement.releasePointerCapture(evt.pointerId);
  29902. }
  29903. catch (e) {
  29904. //Nothing to do with the error.
  29905. }
  29906. _this.previousPosition = null;
  29907. if (!noPreventDefault) {
  29908. evt.preventDefault();
  29909. }
  29910. }
  29911. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  29912. if (!_this.previousPosition || engine.isPointerLock) {
  29913. return;
  29914. }
  29915. var offsetX = evt.clientX - _this.previousPosition.x;
  29916. var offsetY = evt.clientY - _this.previousPosition.y;
  29917. if (_this.camera.getScene().useRightHandedSystem) {
  29918. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  29919. }
  29920. else {
  29921. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  29922. }
  29923. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  29924. _this.previousPosition = {
  29925. x: evt.clientX,
  29926. y: evt.clientY
  29927. };
  29928. if (!noPreventDefault) {
  29929. evt.preventDefault();
  29930. }
  29931. }
  29932. };
  29933. }
  29934. this._onMouseMove = function (evt) {
  29935. if (!engine.isPointerLock) {
  29936. return;
  29937. }
  29938. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  29939. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  29940. if (_this.camera.getScene().useRightHandedSystem) {
  29941. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  29942. }
  29943. else {
  29944. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  29945. }
  29946. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  29947. _this.previousPosition = null;
  29948. if (!noPreventDefault) {
  29949. evt.preventDefault();
  29950. }
  29951. };
  29952. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  29953. element.addEventListener("mousemove", this._onMouseMove, false);
  29954. };
  29955. FreeCameraMouseInput.prototype.detachControl = function (element) {
  29956. if (this._observer && element) {
  29957. this.camera.getScene().onPointerObservable.remove(this._observer);
  29958. element.removeEventListener("mousemove", this._onMouseMove);
  29959. this._observer = null;
  29960. this._onMouseMove = null;
  29961. this.previousPosition = null;
  29962. }
  29963. };
  29964. FreeCameraMouseInput.prototype.getTypeName = function () {
  29965. return "FreeCameraMouseInput";
  29966. };
  29967. FreeCameraMouseInput.prototype.getSimpleName = function () {
  29968. return "mouse";
  29969. };
  29970. return FreeCameraMouseInput;
  29971. }());
  29972. __decorate([
  29973. BABYLON.serialize()
  29974. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  29975. __decorate([
  29976. BABYLON.serialize()
  29977. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  29978. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  29979. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  29980. })(BABYLON || (BABYLON = {}));
  29981. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  29982. var BABYLON;
  29983. (function (BABYLON) {
  29984. var FreeCameraKeyboardMoveInput = (function () {
  29985. function FreeCameraKeyboardMoveInput() {
  29986. this._keys = [];
  29987. this.keysUp = [38];
  29988. this.keysDown = [40];
  29989. this.keysLeft = [37];
  29990. this.keysRight = [39];
  29991. }
  29992. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  29993. var _this = this;
  29994. if (!this._onKeyDown) {
  29995. element.tabIndex = 1;
  29996. this._onKeyDown = function (evt) {
  29997. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  29998. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  29999. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  30000. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  30001. var index = _this._keys.indexOf(evt.keyCode);
  30002. if (index === -1) {
  30003. _this._keys.push(evt.keyCode);
  30004. }
  30005. if (!noPreventDefault) {
  30006. evt.preventDefault();
  30007. }
  30008. }
  30009. };
  30010. this._onKeyUp = function (evt) {
  30011. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  30012. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  30013. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  30014. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  30015. var index = _this._keys.indexOf(evt.keyCode);
  30016. if (index >= 0) {
  30017. _this._keys.splice(index, 1);
  30018. }
  30019. if (!noPreventDefault) {
  30020. evt.preventDefault();
  30021. }
  30022. }
  30023. };
  30024. element.addEventListener("keydown", this._onKeyDown, false);
  30025. element.addEventListener("keyup", this._onKeyUp, false);
  30026. BABYLON.Tools.RegisterTopRootEvents([
  30027. { name: "blur", handler: this._onLostFocus }
  30028. ]);
  30029. }
  30030. };
  30031. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  30032. if (this._onKeyDown) {
  30033. element.removeEventListener("keydown", this._onKeyDown);
  30034. element.removeEventListener("keyup", this._onKeyUp);
  30035. BABYLON.Tools.UnregisterTopRootEvents([
  30036. { name: "blur", handler: this._onLostFocus }
  30037. ]);
  30038. this._keys = [];
  30039. this._onKeyDown = null;
  30040. this._onKeyUp = null;
  30041. }
  30042. };
  30043. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  30044. if (this._onKeyDown) {
  30045. var camera = this.camera;
  30046. // Keyboard
  30047. for (var index = 0; index < this._keys.length; index++) {
  30048. var keyCode = this._keys[index];
  30049. var speed = camera._computeLocalCameraSpeed();
  30050. if (this.keysLeft.indexOf(keyCode) !== -1) {
  30051. camera._localDirection.copyFromFloats(-speed, 0, 0);
  30052. }
  30053. else if (this.keysUp.indexOf(keyCode) !== -1) {
  30054. camera._localDirection.copyFromFloats(0, 0, speed);
  30055. }
  30056. else if (this.keysRight.indexOf(keyCode) !== -1) {
  30057. camera._localDirection.copyFromFloats(speed, 0, 0);
  30058. }
  30059. else if (this.keysDown.indexOf(keyCode) !== -1) {
  30060. camera._localDirection.copyFromFloats(0, 0, -speed);
  30061. }
  30062. if (camera.getScene().useRightHandedSystem) {
  30063. camera._localDirection.z *= -1;
  30064. }
  30065. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  30066. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  30067. camera.cameraDirection.addInPlace(camera._transformedDirection);
  30068. }
  30069. }
  30070. };
  30071. FreeCameraKeyboardMoveInput.prototype.getTypeName = function () {
  30072. return "FreeCameraKeyboardMoveInput";
  30073. };
  30074. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  30075. this._keys = [];
  30076. };
  30077. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  30078. return "keyboard";
  30079. };
  30080. return FreeCameraKeyboardMoveInput;
  30081. }());
  30082. __decorate([
  30083. BABYLON.serialize()
  30084. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  30085. __decorate([
  30086. BABYLON.serialize()
  30087. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  30088. __decorate([
  30089. BABYLON.serialize()
  30090. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  30091. __decorate([
  30092. BABYLON.serialize()
  30093. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  30094. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  30095. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  30096. })(BABYLON || (BABYLON = {}));
  30097. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  30098. var BABYLON;
  30099. (function (BABYLON) {
  30100. var FreeCameraInputsManager = (function (_super) {
  30101. __extends(FreeCameraInputsManager, _super);
  30102. function FreeCameraInputsManager(camera) {
  30103. return _super.call(this, camera) || this;
  30104. }
  30105. FreeCameraInputsManager.prototype.addKeyboard = function () {
  30106. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  30107. return this;
  30108. };
  30109. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  30110. if (touchEnabled === void 0) { touchEnabled = true; }
  30111. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  30112. return this;
  30113. };
  30114. FreeCameraInputsManager.prototype.addGamepad = function () {
  30115. this.add(new BABYLON.FreeCameraGamepadInput());
  30116. return this;
  30117. };
  30118. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  30119. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  30120. return this;
  30121. };
  30122. FreeCameraInputsManager.prototype.addTouch = function () {
  30123. this.add(new BABYLON.FreeCameraTouchInput());
  30124. return this;
  30125. };
  30126. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  30127. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  30128. return this;
  30129. };
  30130. return FreeCameraInputsManager;
  30131. }(BABYLON.CameraInputsManager));
  30132. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  30133. })(BABYLON || (BABYLON = {}));
  30134. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  30135. /// <reference path="babylon.camera.ts" />
  30136. var BABYLON;
  30137. (function (BABYLON) {
  30138. var TargetCamera = (function (_super) {
  30139. __extends(TargetCamera, _super);
  30140. function TargetCamera(name, position, scene) {
  30141. var _this = _super.call(this, name, position, scene) || this;
  30142. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  30143. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  30144. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  30145. _this.speed = 2.0;
  30146. _this.noRotationConstraint = false;
  30147. _this.lockedTarget = null;
  30148. _this._currentTarget = BABYLON.Vector3.Zero();
  30149. _this._viewMatrix = BABYLON.Matrix.Zero();
  30150. _this._camMatrix = BABYLON.Matrix.Zero();
  30151. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  30152. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  30153. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  30154. _this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  30155. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  30156. _this._lookAtTemp = BABYLON.Matrix.Zero();
  30157. _this._tempMatrix = BABYLON.Matrix.Zero();
  30158. return _this;
  30159. }
  30160. TargetCamera.prototype.getFrontPosition = function (distance) {
  30161. var direction = this.getTarget().subtract(this.position);
  30162. direction.normalize();
  30163. direction.scaleInPlace(distance);
  30164. return this.globalPosition.add(direction);
  30165. };
  30166. TargetCamera.prototype._getLockedTargetPosition = function () {
  30167. if (!this.lockedTarget) {
  30168. return null;
  30169. }
  30170. if (this.lockedTarget.absolutePosition) {
  30171. this.lockedTarget.computeWorldMatrix();
  30172. }
  30173. return this.lockedTarget.absolutePosition || this.lockedTarget;
  30174. };
  30175. // Cache
  30176. TargetCamera.prototype._initCache = function () {
  30177. _super.prototype._initCache.call(this);
  30178. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  30179. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  30180. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  30181. };
  30182. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  30183. if (!ignoreParentClass) {
  30184. _super.prototype._updateCache.call(this);
  30185. }
  30186. var lockedTargetPosition = this._getLockedTargetPosition();
  30187. if (!lockedTargetPosition) {
  30188. this._cache.lockedTarget = null;
  30189. }
  30190. else {
  30191. if (!this._cache.lockedTarget) {
  30192. this._cache.lockedTarget = lockedTargetPosition.clone();
  30193. }
  30194. else {
  30195. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  30196. }
  30197. }
  30198. this._cache.rotation.copyFrom(this.rotation);
  30199. if (this.rotationQuaternion)
  30200. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  30201. };
  30202. // Synchronized
  30203. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  30204. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  30205. return false;
  30206. }
  30207. var lockedTargetPosition = this._getLockedTargetPosition();
  30208. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  30209. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  30210. };
  30211. // Methods
  30212. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  30213. var engine = this.getEngine();
  30214. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  30215. };
  30216. // Target
  30217. TargetCamera.prototype.setTarget = function (target) {
  30218. this.upVector.normalize();
  30219. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  30220. this._camMatrix.invert();
  30221. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  30222. var vDir = target.subtract(this.position);
  30223. if (vDir.x >= 0.0) {
  30224. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  30225. }
  30226. else {
  30227. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  30228. }
  30229. this.rotation.z = 0;
  30230. if (isNaN(this.rotation.x)) {
  30231. this.rotation.x = 0;
  30232. }
  30233. if (isNaN(this.rotation.y)) {
  30234. this.rotation.y = 0;
  30235. }
  30236. if (isNaN(this.rotation.z)) {
  30237. this.rotation.z = 0;
  30238. }
  30239. if (this.rotationQuaternion) {
  30240. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  30241. }
  30242. };
  30243. /**
  30244. * Return the current target position of the camera. This value is expressed in local space.
  30245. */
  30246. TargetCamera.prototype.getTarget = function () {
  30247. return this._currentTarget;
  30248. };
  30249. TargetCamera.prototype._decideIfNeedsToMove = function () {
  30250. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  30251. };
  30252. TargetCamera.prototype._updatePosition = function () {
  30253. if (this.parent) {
  30254. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  30255. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  30256. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  30257. return;
  30258. }
  30259. this.position.addInPlace(this.cameraDirection);
  30260. };
  30261. TargetCamera.prototype._checkInputs = function () {
  30262. var needToMove = this._decideIfNeedsToMove();
  30263. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  30264. // Move
  30265. if (needToMove) {
  30266. this._updatePosition();
  30267. }
  30268. // Rotate
  30269. if (needToRotate) {
  30270. this.rotation.x += this.cameraRotation.x;
  30271. this.rotation.y += this.cameraRotation.y;
  30272. //rotate, if quaternion is set and rotation was used
  30273. if (this.rotationQuaternion) {
  30274. var len = this.rotation.lengthSquared();
  30275. if (len) {
  30276. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  30277. }
  30278. }
  30279. if (!this.noRotationConstraint) {
  30280. var limit = (Math.PI / 2) * 0.95;
  30281. if (this.rotation.x > limit)
  30282. this.rotation.x = limit;
  30283. if (this.rotation.x < -limit)
  30284. this.rotation.x = -limit;
  30285. }
  30286. }
  30287. // Inertia
  30288. if (needToMove) {
  30289. if (Math.abs(this.cameraDirection.x) < BABYLON.Epsilon) {
  30290. this.cameraDirection.x = 0;
  30291. }
  30292. if (Math.abs(this.cameraDirection.y) < BABYLON.Epsilon) {
  30293. this.cameraDirection.y = 0;
  30294. }
  30295. if (Math.abs(this.cameraDirection.z) < BABYLON.Epsilon) {
  30296. this.cameraDirection.z = 0;
  30297. }
  30298. this.cameraDirection.scaleInPlace(this.inertia);
  30299. }
  30300. if (needToRotate) {
  30301. if (Math.abs(this.cameraRotation.x) < BABYLON.Epsilon) {
  30302. this.cameraRotation.x = 0;
  30303. }
  30304. if (Math.abs(this.cameraRotation.y) < BABYLON.Epsilon) {
  30305. this.cameraRotation.y = 0;
  30306. }
  30307. this.cameraRotation.scaleInPlace(this.inertia);
  30308. }
  30309. _super.prototype._checkInputs.call(this);
  30310. };
  30311. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  30312. if (this.rotationQuaternion) {
  30313. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  30314. //update the up vector!
  30315. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  30316. }
  30317. else {
  30318. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  30319. }
  30320. };
  30321. TargetCamera.prototype._getViewMatrix = function () {
  30322. if (!this.lockedTarget) {
  30323. // Compute
  30324. this._updateCameraRotationMatrix();
  30325. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  30326. // Computing target and final matrix
  30327. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  30328. }
  30329. else {
  30330. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  30331. }
  30332. if (this.getScene().useRightHandedSystem) {
  30333. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  30334. }
  30335. else {
  30336. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  30337. }
  30338. return this._viewMatrix;
  30339. };
  30340. /**
  30341. * @override
  30342. * Override Camera.createRigCamera
  30343. */
  30344. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  30345. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  30346. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  30347. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  30348. if (!this.rotationQuaternion) {
  30349. this.rotationQuaternion = new BABYLON.Quaternion();
  30350. }
  30351. rigCamera._cameraRigParams = {};
  30352. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  30353. }
  30354. return rigCamera;
  30355. }
  30356. return null;
  30357. };
  30358. /**
  30359. * @override
  30360. * Override Camera._updateRigCameras
  30361. */
  30362. TargetCamera.prototype._updateRigCameras = function () {
  30363. var camLeft = this._rigCameras[0];
  30364. var camRight = this._rigCameras[1];
  30365. switch (this.cameraRigMode) {
  30366. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  30367. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  30368. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  30369. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  30370. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  30371. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  30372. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  30373. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  30374. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  30375. camLeft.setTarget(this.getTarget());
  30376. camRight.setTarget(this.getTarget());
  30377. break;
  30378. case BABYLON.Camera.RIG_MODE_VR:
  30379. if (camLeft.rotationQuaternion) {
  30380. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  30381. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  30382. }
  30383. else {
  30384. camLeft.rotation.copyFrom(this.rotation);
  30385. camRight.rotation.copyFrom(this.rotation);
  30386. }
  30387. camLeft.position.copyFrom(this.position);
  30388. camRight.position.copyFrom(this.position);
  30389. break;
  30390. }
  30391. _super.prototype._updateRigCameras.call(this);
  30392. };
  30393. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  30394. if (!this._rigCamTransformMatrix) {
  30395. this._rigCamTransformMatrix = new BABYLON.Matrix();
  30396. }
  30397. var target = this.getTarget();
  30398. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  30399. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  30400. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  30401. };
  30402. TargetCamera.prototype.getClassName = function () {
  30403. return "TargetCamera";
  30404. };
  30405. return TargetCamera;
  30406. }(BABYLON.Camera));
  30407. __decorate([
  30408. BABYLON.serializeAsVector3()
  30409. ], TargetCamera.prototype, "rotation", void 0);
  30410. __decorate([
  30411. BABYLON.serialize()
  30412. ], TargetCamera.prototype, "speed", void 0);
  30413. __decorate([
  30414. BABYLON.serializeAsMeshReference("lockedTargetId")
  30415. ], TargetCamera.prototype, "lockedTarget", void 0);
  30416. BABYLON.TargetCamera = TargetCamera;
  30417. })(BABYLON || (BABYLON = {}));
  30418. //# sourceMappingURL=babylon.targetCamera.js.map
  30419. var BABYLON;
  30420. (function (BABYLON) {
  30421. var FreeCamera = (function (_super) {
  30422. __extends(FreeCamera, _super);
  30423. function FreeCamera(name, position, scene) {
  30424. var _this = _super.call(this, name, position, scene) || this;
  30425. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  30426. _this.checkCollisions = false;
  30427. _this.applyGravity = false;
  30428. _this._needMoveForGravity = false;
  30429. _this._oldPosition = BABYLON.Vector3.Zero();
  30430. _this._diffPosition = BABYLON.Vector3.Zero();
  30431. _this._newPosition = BABYLON.Vector3.Zero();
  30432. // Collisions
  30433. _this._collisionMask = -1;
  30434. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  30435. if (collidedMesh === void 0) { collidedMesh = null; }
  30436. //TODO move this to the collision coordinator!
  30437. if (_this.getScene().workerCollisions)
  30438. newPosition.multiplyInPlace(_this._collider.radius);
  30439. var updatePosition = function (newPos) {
  30440. _this._newPosition.copyFrom(newPos);
  30441. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  30442. var oldPosition = _this.position.clone();
  30443. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  30444. _this.position.addInPlace(_this._diffPosition);
  30445. if (_this.onCollide && collidedMesh) {
  30446. _this.onCollide(collidedMesh);
  30447. }
  30448. }
  30449. };
  30450. updatePosition(newPosition);
  30451. };
  30452. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  30453. _this.inputs.addKeyboard().addMouse();
  30454. return _this;
  30455. }
  30456. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  30457. //-- begin properties for backward compatibility for inputs
  30458. get: function () {
  30459. var mouse = this.inputs.attached["mouse"];
  30460. if (mouse)
  30461. return mouse.angularSensibility;
  30462. },
  30463. set: function (value) {
  30464. var mouse = this.inputs.attached["mouse"];
  30465. if (mouse)
  30466. mouse.angularSensibility = value;
  30467. },
  30468. enumerable: true,
  30469. configurable: true
  30470. });
  30471. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  30472. get: function () {
  30473. var keyboard = this.inputs.attached["keyboard"];
  30474. if (keyboard)
  30475. return keyboard.keysUp;
  30476. },
  30477. set: function (value) {
  30478. var keyboard = this.inputs.attached["keyboard"];
  30479. if (keyboard)
  30480. keyboard.keysUp = value;
  30481. },
  30482. enumerable: true,
  30483. configurable: true
  30484. });
  30485. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  30486. get: function () {
  30487. var keyboard = this.inputs.attached["keyboard"];
  30488. if (keyboard)
  30489. return keyboard.keysDown;
  30490. },
  30491. set: function (value) {
  30492. var keyboard = this.inputs.attached["keyboard"];
  30493. if (keyboard)
  30494. keyboard.keysDown = value;
  30495. },
  30496. enumerable: true,
  30497. configurable: true
  30498. });
  30499. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  30500. get: function () {
  30501. var keyboard = this.inputs.attached["keyboard"];
  30502. if (keyboard)
  30503. return keyboard.keysLeft;
  30504. },
  30505. set: function (value) {
  30506. var keyboard = this.inputs.attached["keyboard"];
  30507. if (keyboard)
  30508. keyboard.keysLeft = value;
  30509. },
  30510. enumerable: true,
  30511. configurable: true
  30512. });
  30513. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  30514. get: function () {
  30515. var keyboard = this.inputs.attached["keyboard"];
  30516. if (keyboard)
  30517. return keyboard.keysRight;
  30518. },
  30519. set: function (value) {
  30520. var keyboard = this.inputs.attached["keyboard"];
  30521. if (keyboard)
  30522. keyboard.keysRight = value;
  30523. },
  30524. enumerable: true,
  30525. configurable: true
  30526. });
  30527. // Controls
  30528. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  30529. this.inputs.attachElement(element, noPreventDefault);
  30530. };
  30531. FreeCamera.prototype.detachControl = function (element) {
  30532. this.inputs.detachElement(element);
  30533. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  30534. this.cameraRotation = new BABYLON.Vector2(0, 0);
  30535. };
  30536. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  30537. get: function () {
  30538. return this._collisionMask;
  30539. },
  30540. set: function (mask) {
  30541. this._collisionMask = !isNaN(mask) ? mask : -1;
  30542. },
  30543. enumerable: true,
  30544. configurable: true
  30545. });
  30546. FreeCamera.prototype._collideWithWorld = function (velocity) {
  30547. var globalPosition;
  30548. if (this.parent) {
  30549. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  30550. }
  30551. else {
  30552. globalPosition = this.position;
  30553. }
  30554. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  30555. if (!this._collider) {
  30556. this._collider = new BABYLON.Collider();
  30557. }
  30558. this._collider.radius = this.ellipsoid;
  30559. this._collider.collisionMask = this._collisionMask;
  30560. //no need for clone, as long as gravity is not on.
  30561. var actualVelocity = velocity;
  30562. //add gravity to the velocity to prevent the dual-collision checking
  30563. if (this.applyGravity) {
  30564. //this prevents mending with cameraDirection, a global variable of the free camera class.
  30565. actualVelocity = velocity.add(this.getScene().gravity);
  30566. }
  30567. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  30568. };
  30569. FreeCamera.prototype._checkInputs = function () {
  30570. if (!this._localDirection) {
  30571. this._localDirection = BABYLON.Vector3.Zero();
  30572. this._transformedDirection = BABYLON.Vector3.Zero();
  30573. }
  30574. this.inputs.checkInputs();
  30575. _super.prototype._checkInputs.call(this);
  30576. };
  30577. FreeCamera.prototype._decideIfNeedsToMove = function () {
  30578. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  30579. };
  30580. FreeCamera.prototype._updatePosition = function () {
  30581. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  30582. this._collideWithWorld(this.cameraDirection);
  30583. }
  30584. else {
  30585. _super.prototype._updatePosition.call(this);
  30586. }
  30587. };
  30588. FreeCamera.prototype.dispose = function () {
  30589. this.inputs.clear();
  30590. _super.prototype.dispose.call(this);
  30591. };
  30592. FreeCamera.prototype.getClassName = function () {
  30593. return "FreeCamera";
  30594. };
  30595. return FreeCamera;
  30596. }(BABYLON.TargetCamera));
  30597. __decorate([
  30598. BABYLON.serializeAsVector3()
  30599. ], FreeCamera.prototype, "ellipsoid", void 0);
  30600. __decorate([
  30601. BABYLON.serialize()
  30602. ], FreeCamera.prototype, "checkCollisions", void 0);
  30603. __decorate([
  30604. BABYLON.serialize()
  30605. ], FreeCamera.prototype, "applyGravity", void 0);
  30606. BABYLON.FreeCamera = FreeCamera;
  30607. })(BABYLON || (BABYLON = {}));
  30608. //# sourceMappingURL=babylon.freeCamera.js.map
  30609. var BABYLON;
  30610. (function (BABYLON) {
  30611. var ArcRotateCameraKeyboardMoveInput = (function () {
  30612. function ArcRotateCameraKeyboardMoveInput() {
  30613. this._keys = [];
  30614. this.keysUp = [38];
  30615. this.keysDown = [40];
  30616. this.keysLeft = [37];
  30617. this.keysRight = [39];
  30618. }
  30619. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  30620. var _this = this;
  30621. element.tabIndex = 1;
  30622. this._onKeyDown = function (evt) {
  30623. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  30624. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  30625. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  30626. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  30627. var index = _this._keys.indexOf(evt.keyCode);
  30628. if (index === -1) {
  30629. _this._keys.push(evt.keyCode);
  30630. }
  30631. if (evt.preventDefault) {
  30632. if (!noPreventDefault) {
  30633. evt.preventDefault();
  30634. }
  30635. }
  30636. }
  30637. };
  30638. this._onKeyUp = function (evt) {
  30639. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  30640. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  30641. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  30642. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  30643. var index = _this._keys.indexOf(evt.keyCode);
  30644. if (index >= 0) {
  30645. _this._keys.splice(index, 1);
  30646. }
  30647. if (evt.preventDefault) {
  30648. if (!noPreventDefault) {
  30649. evt.preventDefault();
  30650. }
  30651. }
  30652. }
  30653. };
  30654. this._onLostFocus = function () {
  30655. _this._keys = [];
  30656. };
  30657. element.addEventListener("keydown", this._onKeyDown, false);
  30658. element.addEventListener("keyup", this._onKeyUp, false);
  30659. BABYLON.Tools.RegisterTopRootEvents([
  30660. { name: "blur", handler: this._onLostFocus }
  30661. ]);
  30662. };
  30663. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  30664. if (element) {
  30665. element.removeEventListener("keydown", this._onKeyDown);
  30666. element.removeEventListener("keyup", this._onKeyUp);
  30667. }
  30668. BABYLON.Tools.UnregisterTopRootEvents([
  30669. { name: "blur", handler: this._onLostFocus }
  30670. ]);
  30671. this._keys = [];
  30672. this._onKeyDown = null;
  30673. this._onKeyUp = null;
  30674. this._onLostFocus = null;
  30675. };
  30676. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  30677. if (this._onKeyDown) {
  30678. var camera = this.camera;
  30679. for (var index = 0; index < this._keys.length; index++) {
  30680. var keyCode = this._keys[index];
  30681. if (this.keysLeft.indexOf(keyCode) !== -1) {
  30682. camera.inertialAlphaOffset -= 0.01;
  30683. }
  30684. else if (this.keysUp.indexOf(keyCode) !== -1) {
  30685. camera.inertialBetaOffset -= 0.01;
  30686. }
  30687. else if (this.keysRight.indexOf(keyCode) !== -1) {
  30688. camera.inertialAlphaOffset += 0.01;
  30689. }
  30690. else if (this.keysDown.indexOf(keyCode) !== -1) {
  30691. camera.inertialBetaOffset += 0.01;
  30692. }
  30693. }
  30694. }
  30695. };
  30696. ArcRotateCameraKeyboardMoveInput.prototype.getTypeName = function () {
  30697. return "ArcRotateCameraKeyboardMoveInput";
  30698. };
  30699. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  30700. return "keyboard";
  30701. };
  30702. return ArcRotateCameraKeyboardMoveInput;
  30703. }());
  30704. __decorate([
  30705. BABYLON.serialize()
  30706. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  30707. __decorate([
  30708. BABYLON.serialize()
  30709. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  30710. __decorate([
  30711. BABYLON.serialize()
  30712. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  30713. __decorate([
  30714. BABYLON.serialize()
  30715. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  30716. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  30717. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  30718. })(BABYLON || (BABYLON = {}));
  30719. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  30720. var BABYLON;
  30721. (function (BABYLON) {
  30722. var ArcRotateCameraMouseWheelInput = (function () {
  30723. function ArcRotateCameraMouseWheelInput() {
  30724. this.wheelPrecision = 3.0;
  30725. }
  30726. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  30727. var _this = this;
  30728. this._wheel = function (p, s) {
  30729. //sanity check - this should be a PointerWheel event.
  30730. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  30731. return;
  30732. var event = p.event;
  30733. var delta = 0;
  30734. if (event.wheelDelta) {
  30735. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  30736. }
  30737. else if (event.detail) {
  30738. delta = -event.detail / _this.wheelPrecision;
  30739. }
  30740. if (delta)
  30741. _this.camera.inertialRadiusOffset += delta;
  30742. if (event.preventDefault) {
  30743. if (!noPreventDefault) {
  30744. event.preventDefault();
  30745. }
  30746. }
  30747. };
  30748. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  30749. };
  30750. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  30751. if (this._observer && element) {
  30752. this.camera.getScene().onPointerObservable.remove(this._observer);
  30753. this._observer = null;
  30754. this._wheel = null;
  30755. }
  30756. };
  30757. ArcRotateCameraMouseWheelInput.prototype.getTypeName = function () {
  30758. return "ArcRotateCameraMouseWheelInput";
  30759. };
  30760. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  30761. return "mousewheel";
  30762. };
  30763. return ArcRotateCameraMouseWheelInput;
  30764. }());
  30765. __decorate([
  30766. BABYLON.serialize()
  30767. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  30768. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  30769. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  30770. })(BABYLON || (BABYLON = {}));
  30771. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  30772. var BABYLON;
  30773. (function (BABYLON) {
  30774. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  30775. var ArcRotateCameraPointersInput = (function () {
  30776. function ArcRotateCameraPointersInput() {
  30777. this.buttons = [0, 1, 2];
  30778. this.angularSensibilityX = 1000.0;
  30779. this.angularSensibilityY = 1000.0;
  30780. this.pinchPrecision = 6.0;
  30781. this.panningSensibility = 50.0;
  30782. this._isPanClick = false;
  30783. this.pinchInwards = true;
  30784. }
  30785. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  30786. var _this = this;
  30787. var engine = this.camera.getEngine();
  30788. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  30789. var pointA, pointB;
  30790. var previousPinchDistance = 0;
  30791. this._pointerInput = function (p, s) {
  30792. var evt = p.event;
  30793. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  30794. return;
  30795. }
  30796. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  30797. try {
  30798. evt.srcElement.setPointerCapture(evt.pointerId);
  30799. }
  30800. catch (e) {
  30801. //Nothing to do with the error. Execution will continue.
  30802. }
  30803. // Manage panning with pan button click
  30804. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  30805. // manage pointers
  30806. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  30807. if (pointA === undefined) {
  30808. pointA = cacheSoloPointer;
  30809. }
  30810. else if (pointB === undefined) {
  30811. pointB = cacheSoloPointer;
  30812. }
  30813. if (!noPreventDefault) {
  30814. evt.preventDefault();
  30815. element.focus();
  30816. }
  30817. }
  30818. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  30819. try {
  30820. evt.srcElement.releasePointerCapture(evt.pointerId);
  30821. }
  30822. catch (e) {
  30823. //Nothing to do with the error.
  30824. }
  30825. cacheSoloPointer = null;
  30826. previousPinchDistance = 0;
  30827. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  30828. //but emptying completly pointers collection is required to fix a bug on iPhone :
  30829. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  30830. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  30831. pointA = pointB = undefined;
  30832. if (!noPreventDefault) {
  30833. evt.preventDefault();
  30834. }
  30835. }
  30836. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  30837. if (!noPreventDefault) {
  30838. evt.preventDefault();
  30839. }
  30840. // One button down
  30841. if (pointA && pointB === undefined) {
  30842. if (_this.panningSensibility !== 0 &&
  30843. ((evt.ctrlKey && _this.camera._useCtrlForPanning) ||
  30844. (!_this.camera._useCtrlForPanning && _this._isPanClick))) {
  30845. _this.camera
  30846. .inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  30847. _this.camera
  30848. .inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  30849. }
  30850. else {
  30851. var offsetX = evt.clientX - cacheSoloPointer.x;
  30852. var offsetY = evt.clientY - cacheSoloPointer.y;
  30853. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  30854. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  30855. }
  30856. cacheSoloPointer.x = evt.clientX;
  30857. cacheSoloPointer.y = evt.clientY;
  30858. }
  30859. else if (pointA && pointB) {
  30860. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  30861. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  30862. ed.x = evt.clientX;
  30863. ed.y = evt.clientY;
  30864. var direction = _this.pinchInwards ? 1 : -1;
  30865. var distX = pointA.x - pointB.x;
  30866. var distY = pointA.y - pointB.y;
  30867. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  30868. if (previousPinchDistance === 0) {
  30869. previousPinchDistance = pinchSquaredDistance;
  30870. return;
  30871. }
  30872. if (pinchSquaredDistance !== previousPinchDistance) {
  30873. _this.camera
  30874. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) /
  30875. (_this.pinchPrecision *
  30876. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  30877. direction);
  30878. previousPinchDistance = pinchSquaredDistance;
  30879. }
  30880. }
  30881. }
  30882. };
  30883. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  30884. this._onContextMenu = function (evt) {
  30885. evt.preventDefault();
  30886. };
  30887. if (!this.camera._useCtrlForPanning) {
  30888. element.addEventListener("contextmenu", this._onContextMenu, false);
  30889. }
  30890. this._onLostFocus = function () {
  30891. //this._keys = [];
  30892. pointA = pointB = undefined;
  30893. previousPinchDistance = 0;
  30894. cacheSoloPointer = null;
  30895. };
  30896. this._onMouseMove = function (evt) {
  30897. if (!engine.isPointerLock) {
  30898. return;
  30899. }
  30900. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  30901. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  30902. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  30903. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  30904. if (!noPreventDefault) {
  30905. evt.preventDefault();
  30906. }
  30907. };
  30908. this._onGestureStart = function (e) {
  30909. if (window.MSGesture === undefined) {
  30910. return;
  30911. }
  30912. if (!_this._MSGestureHandler) {
  30913. _this._MSGestureHandler = new MSGesture();
  30914. _this._MSGestureHandler.target = element;
  30915. }
  30916. _this._MSGestureHandler.addPointer(e.pointerId);
  30917. };
  30918. this._onGesture = function (e) {
  30919. _this.camera.radius *= e.scale;
  30920. if (e.preventDefault) {
  30921. if (!noPreventDefault) {
  30922. e.stopPropagation();
  30923. e.preventDefault();
  30924. }
  30925. }
  30926. };
  30927. element.addEventListener("mousemove", this._onMouseMove, false);
  30928. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  30929. element.addEventListener("MSGestureChange", this._onGesture, false);
  30930. element.addEventListener("keydown", this._onKeyDown, false);
  30931. element.addEventListener("keyup", this._onKeyUp, false);
  30932. BABYLON.Tools.RegisterTopRootEvents([
  30933. { name: "blur", handler: this._onLostFocus }
  30934. ]);
  30935. };
  30936. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  30937. if (element && this._observer) {
  30938. this.camera.getScene().onPointerObservable.remove(this._observer);
  30939. this._observer = null;
  30940. element.removeEventListener("contextmenu", this._onContextMenu);
  30941. element.removeEventListener("mousemove", this._onMouseMove);
  30942. element.removeEventListener("MSPointerDown", this._onGestureStart);
  30943. element.removeEventListener("MSGestureChange", this._onGesture);
  30944. element.removeEventListener("keydown", this._onKeyDown);
  30945. element.removeEventListener("keyup", this._onKeyUp);
  30946. this._isPanClick = false;
  30947. this.pinchInwards = true;
  30948. this._onKeyDown = null;
  30949. this._onKeyUp = null;
  30950. this._onMouseMove = null;
  30951. this._onGestureStart = null;
  30952. this._onGesture = null;
  30953. this._MSGestureHandler = null;
  30954. this._onLostFocus = null;
  30955. this._onContextMenu = null;
  30956. }
  30957. BABYLON.Tools.UnregisterTopRootEvents([
  30958. { name: "blur", handler: this._onLostFocus }
  30959. ]);
  30960. };
  30961. ArcRotateCameraPointersInput.prototype.getTypeName = function () {
  30962. return "ArcRotateCameraPointersInput";
  30963. };
  30964. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  30965. return "pointers";
  30966. };
  30967. return ArcRotateCameraPointersInput;
  30968. }());
  30969. __decorate([
  30970. BABYLON.serialize()
  30971. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  30972. __decorate([
  30973. BABYLON.serialize()
  30974. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  30975. __decorate([
  30976. BABYLON.serialize()
  30977. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  30978. __decorate([
  30979. BABYLON.serialize()
  30980. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  30981. __decorate([
  30982. BABYLON.serialize()
  30983. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  30984. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  30985. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  30986. })(BABYLON || (BABYLON = {}));
  30987. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  30988. /// <reference path="babylon.targetCamera.ts" />
  30989. /// <reference path="..\Tools\babylon.tools.ts" />
  30990. var BABYLON;
  30991. (function (BABYLON) {
  30992. var ArcRotateCamera = (function (_super) {
  30993. __extends(ArcRotateCamera, _super);
  30994. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  30995. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  30996. _this.inertialAlphaOffset = 0;
  30997. _this.inertialBetaOffset = 0;
  30998. _this.inertialRadiusOffset = 0;
  30999. _this.lowerAlphaLimit = null;
  31000. _this.upperAlphaLimit = null;
  31001. _this.lowerBetaLimit = 0.01;
  31002. _this.upperBetaLimit = Math.PI;
  31003. _this.lowerRadiusLimit = null;
  31004. _this.upperRadiusLimit = null;
  31005. _this.inertialPanningX = 0;
  31006. _this.inertialPanningY = 0;
  31007. //-- end properties for backward compatibility for inputs
  31008. _this.zoomOnFactor = 1;
  31009. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  31010. _this.allowUpsideDown = true;
  31011. _this._viewMatrix = new BABYLON.Matrix();
  31012. // Panning
  31013. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  31014. _this.checkCollisions = false;
  31015. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  31016. _this._previousPosition = BABYLON.Vector3.Zero();
  31017. _this._collisionVelocity = BABYLON.Vector3.Zero();
  31018. _this._newPosition = BABYLON.Vector3.Zero();
  31019. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  31020. if (collidedMesh === void 0) { collidedMesh = null; }
  31021. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  31022. newPosition.multiplyInPlace(_this._collider.radius);
  31023. }
  31024. if (!collidedMesh) {
  31025. _this._previousPosition.copyFrom(_this.position);
  31026. }
  31027. else {
  31028. _this.setPosition(newPosition);
  31029. if (_this.onCollide) {
  31030. _this.onCollide(collidedMesh);
  31031. }
  31032. }
  31033. // Recompute because of constraints
  31034. var cosa = Math.cos(_this.alpha);
  31035. var sina = Math.sin(_this.alpha);
  31036. var cosb = Math.cos(_this.beta);
  31037. var sinb = Math.sin(_this.beta);
  31038. if (sinb === 0) {
  31039. sinb = 0.0001;
  31040. }
  31041. var target = _this._getTargetPosition();
  31042. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  31043. _this.position.copyFrom(_this._newPosition);
  31044. var up = _this.upVector;
  31045. if (_this.allowUpsideDown && _this.beta < 0) {
  31046. up = up.clone();
  31047. up = up.negate();
  31048. }
  31049. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  31050. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  31051. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  31052. _this._collisionTriggered = false;
  31053. };
  31054. _this._target = BABYLON.Vector3.Zero();
  31055. if (target) {
  31056. _this.setTarget(target);
  31057. }
  31058. _this.alpha = alpha;
  31059. _this.beta = beta;
  31060. _this.radius = radius;
  31061. _this.getViewMatrix();
  31062. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  31063. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  31064. return _this;
  31065. }
  31066. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  31067. get: function () {
  31068. return this._target;
  31069. },
  31070. set: function (value) {
  31071. this.setTarget(value);
  31072. },
  31073. enumerable: true,
  31074. configurable: true
  31075. });
  31076. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  31077. //-- begin properties for backward compatibility for inputs
  31078. get: function () {
  31079. var pointers = this.inputs.attached["pointers"];
  31080. if (pointers)
  31081. return pointers.angularSensibilityX;
  31082. },
  31083. set: function (value) {
  31084. var pointers = this.inputs.attached["pointers"];
  31085. if (pointers) {
  31086. pointers.angularSensibilityX = value;
  31087. }
  31088. },
  31089. enumerable: true,
  31090. configurable: true
  31091. });
  31092. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  31093. get: function () {
  31094. var pointers = this.inputs.attached["pointers"];
  31095. if (pointers)
  31096. return pointers.angularSensibilityY;
  31097. },
  31098. set: function (value) {
  31099. var pointers = this.inputs.attached["pointers"];
  31100. if (pointers) {
  31101. pointers.angularSensibilityY = value;
  31102. }
  31103. },
  31104. enumerable: true,
  31105. configurable: true
  31106. });
  31107. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  31108. get: function () {
  31109. var pointers = this.inputs.attached["pointers"];
  31110. if (pointers)
  31111. return pointers.pinchPrecision;
  31112. },
  31113. set: function (value) {
  31114. var pointers = this.inputs.attached["pointers"];
  31115. if (pointers) {
  31116. pointers.pinchPrecision = value;
  31117. }
  31118. },
  31119. enumerable: true,
  31120. configurable: true
  31121. });
  31122. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  31123. get: function () {
  31124. var pointers = this.inputs.attached["pointers"];
  31125. if (pointers)
  31126. return pointers.panningSensibility;
  31127. },
  31128. set: function (value) {
  31129. var pointers = this.inputs.attached["pointers"];
  31130. if (pointers) {
  31131. pointers.panningSensibility = value;
  31132. }
  31133. },
  31134. enumerable: true,
  31135. configurable: true
  31136. });
  31137. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  31138. get: function () {
  31139. var keyboard = this.inputs.attached["keyboard"];
  31140. if (keyboard)
  31141. return keyboard.keysUp;
  31142. },
  31143. set: function (value) {
  31144. var keyboard = this.inputs.attached["keyboard"];
  31145. if (keyboard)
  31146. keyboard.keysUp = value;
  31147. },
  31148. enumerable: true,
  31149. configurable: true
  31150. });
  31151. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  31152. get: function () {
  31153. var keyboard = this.inputs.attached["keyboard"];
  31154. if (keyboard)
  31155. return keyboard.keysDown;
  31156. },
  31157. set: function (value) {
  31158. var keyboard = this.inputs.attached["keyboard"];
  31159. if (keyboard)
  31160. keyboard.keysDown = value;
  31161. },
  31162. enumerable: true,
  31163. configurable: true
  31164. });
  31165. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  31166. get: function () {
  31167. var keyboard = this.inputs.attached["keyboard"];
  31168. if (keyboard)
  31169. return keyboard.keysLeft;
  31170. },
  31171. set: function (value) {
  31172. var keyboard = this.inputs.attached["keyboard"];
  31173. if (keyboard)
  31174. keyboard.keysLeft = value;
  31175. },
  31176. enumerable: true,
  31177. configurable: true
  31178. });
  31179. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  31180. get: function () {
  31181. var keyboard = this.inputs.attached["keyboard"];
  31182. if (keyboard)
  31183. return keyboard.keysRight;
  31184. },
  31185. set: function (value) {
  31186. var keyboard = this.inputs.attached["keyboard"];
  31187. if (keyboard)
  31188. keyboard.keysRight = value;
  31189. },
  31190. enumerable: true,
  31191. configurable: true
  31192. });
  31193. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  31194. get: function () {
  31195. var mousewheel = this.inputs.attached["mousewheel"];
  31196. if (mousewheel)
  31197. return mousewheel.wheelPrecision;
  31198. },
  31199. set: function (value) {
  31200. var mousewheel = this.inputs.attached["mousewheel"];
  31201. if (mousewheel)
  31202. mousewheel.wheelPrecision = value;
  31203. },
  31204. enumerable: true,
  31205. configurable: true
  31206. });
  31207. // Cache
  31208. ArcRotateCamera.prototype._initCache = function () {
  31209. _super.prototype._initCache.call(this);
  31210. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  31211. this._cache.alpha = undefined;
  31212. this._cache.beta = undefined;
  31213. this._cache.radius = undefined;
  31214. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  31215. };
  31216. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  31217. if (!ignoreParentClass) {
  31218. _super.prototype._updateCache.call(this);
  31219. }
  31220. this._cache._target.copyFrom(this._getTargetPosition());
  31221. this._cache.alpha = this.alpha;
  31222. this._cache.beta = this.beta;
  31223. this._cache.radius = this.radius;
  31224. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  31225. };
  31226. ArcRotateCamera.prototype._getTargetPosition = function () {
  31227. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  31228. var pos = this._targetHost.getAbsolutePosition();
  31229. if (this._targetBoundingCenter) {
  31230. pos.addToRef(this._targetBoundingCenter, this._target);
  31231. }
  31232. else {
  31233. this._target.copyFrom(pos);
  31234. }
  31235. }
  31236. return this._target;
  31237. };
  31238. // Synchronized
  31239. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  31240. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  31241. return false;
  31242. return this._cache._target.equals(this._target)
  31243. && this._cache.alpha === this.alpha
  31244. && this._cache.beta === this.beta
  31245. && this._cache.radius === this.radius
  31246. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  31247. };
  31248. // Methods
  31249. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  31250. var _this = this;
  31251. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  31252. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  31253. this._useCtrlForPanning = useCtrlForPanning;
  31254. this._panningMouseButton = panningMouseButton;
  31255. this.inputs.attachElement(element, noPreventDefault);
  31256. this._reset = function () {
  31257. _this.inertialAlphaOffset = 0;
  31258. _this.inertialBetaOffset = 0;
  31259. _this.inertialRadiusOffset = 0;
  31260. };
  31261. };
  31262. ArcRotateCamera.prototype.detachControl = function (element) {
  31263. this.inputs.detachElement(element);
  31264. if (this._reset) {
  31265. this._reset();
  31266. }
  31267. };
  31268. ArcRotateCamera.prototype._checkInputs = function () {
  31269. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  31270. if (this._collisionTriggered) {
  31271. return;
  31272. }
  31273. this.inputs.checkInputs();
  31274. // Inertia
  31275. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  31276. if (this.getScene().useRightHandedSystem) {
  31277. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  31278. }
  31279. else {
  31280. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  31281. }
  31282. this.beta += this.inertialBetaOffset;
  31283. this.radius -= this.inertialRadiusOffset;
  31284. this.inertialAlphaOffset *= this.inertia;
  31285. this.inertialBetaOffset *= this.inertia;
  31286. this.inertialRadiusOffset *= this.inertia;
  31287. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  31288. this.inertialAlphaOffset = 0;
  31289. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  31290. this.inertialBetaOffset = 0;
  31291. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Epsilon)
  31292. this.inertialRadiusOffset = 0;
  31293. }
  31294. // Panning inertia
  31295. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  31296. if (!this._localDirection) {
  31297. this._localDirection = BABYLON.Vector3.Zero();
  31298. this._transformedDirection = BABYLON.Vector3.Zero();
  31299. }
  31300. this.inertialPanningX *= this.inertia;
  31301. this.inertialPanningY *= this.inertia;
  31302. if (Math.abs(this.inertialPanningX) < BABYLON.Epsilon)
  31303. this.inertialPanningX = 0;
  31304. if (Math.abs(this.inertialPanningY) < BABYLON.Epsilon)
  31305. this.inertialPanningY = 0;
  31306. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  31307. this._localDirection.multiplyInPlace(this.panningAxis);
  31308. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  31309. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  31310. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  31311. if (!this.panningAxis.y) {
  31312. this._transformedDirection.y = 0;
  31313. }
  31314. if (!this._targetHost) {
  31315. this._target.addInPlace(this._transformedDirection);
  31316. }
  31317. }
  31318. // Limits
  31319. this._checkLimits();
  31320. _super.prototype._checkInputs.call(this);
  31321. };
  31322. ArcRotateCamera.prototype._checkLimits = function () {
  31323. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  31324. if (this.allowUpsideDown && this.beta > Math.PI) {
  31325. this.beta = this.beta - (2 * Math.PI);
  31326. }
  31327. }
  31328. else {
  31329. if (this.beta < this.lowerBetaLimit) {
  31330. this.beta = this.lowerBetaLimit;
  31331. }
  31332. }
  31333. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  31334. if (this.allowUpsideDown && this.beta < -Math.PI) {
  31335. this.beta = this.beta + (2 * Math.PI);
  31336. }
  31337. }
  31338. else {
  31339. if (this.beta > this.upperBetaLimit) {
  31340. this.beta = this.upperBetaLimit;
  31341. }
  31342. }
  31343. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  31344. this.alpha = this.lowerAlphaLimit;
  31345. }
  31346. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  31347. this.alpha = this.upperAlphaLimit;
  31348. }
  31349. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  31350. this.radius = this.lowerRadiusLimit;
  31351. }
  31352. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  31353. this.radius = this.upperRadiusLimit;
  31354. }
  31355. };
  31356. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  31357. var radiusv3 = this.position.subtract(this._getTargetPosition());
  31358. this.radius = radiusv3.length();
  31359. // Alpha
  31360. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  31361. if (radiusv3.z < 0) {
  31362. this.alpha = 2 * Math.PI - this.alpha;
  31363. }
  31364. // Beta
  31365. this.beta = Math.acos(radiusv3.y / this.radius);
  31366. this._checkLimits();
  31367. };
  31368. ArcRotateCamera.prototype.setPosition = function (position) {
  31369. if (this.position.equals(position)) {
  31370. return;
  31371. }
  31372. this.position.copyFrom(position);
  31373. this.rebuildAnglesAndRadius();
  31374. };
  31375. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  31376. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  31377. if (allowSamePosition === void 0) { allowSamePosition = false; }
  31378. if (target.getBoundingInfo) {
  31379. if (toBoundingCenter) {
  31380. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  31381. }
  31382. else {
  31383. this._targetBoundingCenter = null;
  31384. }
  31385. this._targetHost = target;
  31386. this._target = this._getTargetPosition();
  31387. }
  31388. else {
  31389. var newTarget = target;
  31390. var currentTarget = this._getTargetPosition();
  31391. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  31392. return;
  31393. }
  31394. this._target = newTarget;
  31395. this._targetBoundingCenter = null;
  31396. }
  31397. this.rebuildAnglesAndRadius();
  31398. };
  31399. ArcRotateCamera.prototype._getViewMatrix = function () {
  31400. // Compute
  31401. var cosa = Math.cos(this.alpha);
  31402. var sina = Math.sin(this.alpha);
  31403. var cosb = Math.cos(this.beta);
  31404. var sinb = Math.sin(this.beta);
  31405. if (sinb === 0) {
  31406. sinb = 0.0001;
  31407. }
  31408. var target = this._getTargetPosition();
  31409. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  31410. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  31411. if (!this._collider) {
  31412. this._collider = new BABYLON.Collider();
  31413. }
  31414. this._collider.radius = this.collisionRadius;
  31415. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  31416. this._collisionTriggered = true;
  31417. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  31418. }
  31419. else {
  31420. this.position.copyFrom(this._newPosition);
  31421. var up = this.upVector;
  31422. if (this.allowUpsideDown && sinb < 0) {
  31423. up = up.clone();
  31424. up = up.negate();
  31425. }
  31426. if (this.getScene().useRightHandedSystem) {
  31427. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  31428. }
  31429. else {
  31430. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  31431. }
  31432. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  31433. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  31434. }
  31435. this._currentTarget = target;
  31436. return this._viewMatrix;
  31437. };
  31438. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  31439. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  31440. meshes = meshes || this.getScene().meshes;
  31441. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  31442. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  31443. this.radius = distance * this.zoomOnFactor;
  31444. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  31445. };
  31446. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  31447. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  31448. var meshesOrMinMaxVector;
  31449. var distance;
  31450. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  31451. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  31452. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  31453. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  31454. }
  31455. else {
  31456. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  31457. distance = meshesOrMinMaxVectorAndDistance.distance;
  31458. }
  31459. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  31460. if (!doNotUpdateMaxZ) {
  31461. this.maxZ = distance * 2;
  31462. }
  31463. };
  31464. /**
  31465. * @override
  31466. * Override Camera.createRigCamera
  31467. */
  31468. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  31469. var alphaShift;
  31470. switch (this.cameraRigMode) {
  31471. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  31472. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  31473. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  31474. case BABYLON.Camera.RIG_MODE_VR:
  31475. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  31476. break;
  31477. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  31478. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  31479. break;
  31480. }
  31481. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  31482. rigCam._cameraRigParams = {};
  31483. return rigCam;
  31484. };
  31485. /**
  31486. * @override
  31487. * Override Camera._updateRigCameras
  31488. */
  31489. ArcRotateCamera.prototype._updateRigCameras = function () {
  31490. var camLeft = this._rigCameras[0];
  31491. var camRight = this._rigCameras[1];
  31492. camLeft.beta = camRight.beta = this.beta;
  31493. camLeft.radius = camRight.radius = this.radius;
  31494. switch (this.cameraRigMode) {
  31495. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  31496. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  31497. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  31498. case BABYLON.Camera.RIG_MODE_VR:
  31499. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  31500. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  31501. break;
  31502. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  31503. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  31504. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  31505. break;
  31506. }
  31507. _super.prototype._updateRigCameras.call(this);
  31508. };
  31509. ArcRotateCamera.prototype.dispose = function () {
  31510. this.inputs.clear();
  31511. _super.prototype.dispose.call(this);
  31512. };
  31513. ArcRotateCamera.prototype.getClassName = function () {
  31514. return "ArcRotateCamera";
  31515. };
  31516. return ArcRotateCamera;
  31517. }(BABYLON.TargetCamera));
  31518. __decorate([
  31519. BABYLON.serialize()
  31520. ], ArcRotateCamera.prototype, "alpha", void 0);
  31521. __decorate([
  31522. BABYLON.serialize()
  31523. ], ArcRotateCamera.prototype, "beta", void 0);
  31524. __decorate([
  31525. BABYLON.serialize()
  31526. ], ArcRotateCamera.prototype, "radius", void 0);
  31527. __decorate([
  31528. BABYLON.serializeAsVector3("target")
  31529. ], ArcRotateCamera.prototype, "_target", void 0);
  31530. __decorate([
  31531. BABYLON.serialize()
  31532. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  31533. __decorate([
  31534. BABYLON.serialize()
  31535. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  31536. __decorate([
  31537. BABYLON.serialize()
  31538. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  31539. __decorate([
  31540. BABYLON.serialize()
  31541. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  31542. __decorate([
  31543. BABYLON.serialize()
  31544. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  31545. __decorate([
  31546. BABYLON.serialize()
  31547. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  31548. __decorate([
  31549. BABYLON.serialize()
  31550. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  31551. __decorate([
  31552. BABYLON.serialize()
  31553. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  31554. __decorate([
  31555. BABYLON.serialize()
  31556. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  31557. __decorate([
  31558. BABYLON.serialize()
  31559. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  31560. __decorate([
  31561. BABYLON.serialize()
  31562. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  31563. __decorate([
  31564. BABYLON.serialize()
  31565. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  31566. __decorate([
  31567. BABYLON.serialize()
  31568. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  31569. BABYLON.ArcRotateCamera = ArcRotateCamera;
  31570. })(BABYLON || (BABYLON = {}));
  31571. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  31572. /// <reference path="..\Cameras\babylon.cameraInputsManager.ts" />
  31573. var BABYLON;
  31574. (function (BABYLON) {
  31575. var ArcRotateCameraInputsManager = (function (_super) {
  31576. __extends(ArcRotateCameraInputsManager, _super);
  31577. function ArcRotateCameraInputsManager(camera) {
  31578. return _super.call(this, camera) || this;
  31579. }
  31580. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  31581. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  31582. return this;
  31583. };
  31584. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  31585. this.add(new BABYLON.ArcRotateCameraPointersInput());
  31586. return this;
  31587. };
  31588. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  31589. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  31590. return this;
  31591. };
  31592. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  31593. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  31594. return this;
  31595. };
  31596. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  31597. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  31598. return this;
  31599. };
  31600. return ArcRotateCameraInputsManager;
  31601. }(BABYLON.CameraInputsManager));
  31602. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  31603. })(BABYLON || (BABYLON = {}));
  31604. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  31605. var BABYLON;
  31606. (function (BABYLON) {
  31607. var HemisphericLight = (function (_super) {
  31608. __extends(HemisphericLight, _super);
  31609. /**
  31610. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  31611. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  31612. * The HemisphericLight can't cast shadows.
  31613. * Documentation : http://doc.babylonjs.com/tutorials/lights
  31614. */
  31615. function HemisphericLight(name, direction, scene) {
  31616. var _this = _super.call(this, name, scene) || this;
  31617. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  31618. _this.direction = direction;
  31619. return _this;
  31620. }
  31621. HemisphericLight.prototype._buildUniformLayout = function () {
  31622. this._uniformBuffer.addUniform("vLightData", 4);
  31623. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  31624. this._uniformBuffer.addUniform("vLightSpecular", 3);
  31625. this._uniformBuffer.addUniform("vLightGround", 3);
  31626. this._uniformBuffer.addUniform("shadowsInfo", 3);
  31627. this._uniformBuffer.create();
  31628. };
  31629. /**
  31630. * Returns the string "HemisphericLight".
  31631. */
  31632. HemisphericLight.prototype.getClassName = function () {
  31633. return "HemisphericLight";
  31634. };
  31635. /**
  31636. * Sets the HemisphericLight direction towards the passed target (Vector3).
  31637. * Returns the updated direction.
  31638. */
  31639. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  31640. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  31641. return this.direction;
  31642. };
  31643. HemisphericLight.prototype.getShadowGenerator = function () {
  31644. return null;
  31645. };
  31646. /**
  31647. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  31648. * Returns the HemisphericLight.
  31649. */
  31650. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  31651. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  31652. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  31653. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  31654. return this;
  31655. };
  31656. HemisphericLight.prototype._getWorldMatrix = function () {
  31657. if (!this._worldMatrix) {
  31658. this._worldMatrix = BABYLON.Matrix.Identity();
  31659. }
  31660. return this._worldMatrix;
  31661. };
  31662. /**
  31663. * Returns the integer 3.
  31664. */
  31665. HemisphericLight.prototype.getTypeID = function () {
  31666. return 3;
  31667. };
  31668. return HemisphericLight;
  31669. }(BABYLON.Light));
  31670. __decorate([
  31671. BABYLON.serializeAsColor3()
  31672. ], HemisphericLight.prototype, "groundColor", void 0);
  31673. __decorate([
  31674. BABYLON.serializeAsVector3()
  31675. ], HemisphericLight.prototype, "direction", void 0);
  31676. BABYLON.HemisphericLight = HemisphericLight;
  31677. })(BABYLON || (BABYLON = {}));
  31678. //# sourceMappingURL=babylon.hemisphericLight.js.map
  31679. var BABYLON;
  31680. (function (BABYLON) {
  31681. var PointLight = (function (_super) {
  31682. __extends(PointLight, _super);
  31683. /**
  31684. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  31685. * A PointLight emits the light in every direction.
  31686. * It can cast shadows.
  31687. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  31688. * ```javascript
  31689. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  31690. * ```
  31691. * Documentation : http://doc.babylonjs.com/tutorials/lights
  31692. */
  31693. function PointLight(name, position, scene) {
  31694. var _this = _super.call(this, name, scene) || this;
  31695. _this.position = position;
  31696. return _this;
  31697. }
  31698. PointLight.prototype._buildUniformLayout = function () {
  31699. this._uniformBuffer.addUniform("vLightData", 4);
  31700. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  31701. this._uniformBuffer.addUniform("vLightSpecular", 3);
  31702. this._uniformBuffer.addUniform("shadowsInfo", 3);
  31703. this._uniformBuffer.create();
  31704. };
  31705. /**
  31706. * Returns the string "PointLight"
  31707. */
  31708. PointLight.prototype.getClassName = function () {
  31709. return "PointLight";
  31710. };
  31711. /**
  31712. * Returns a Vector3, the PointLight absolute position in the World.
  31713. */
  31714. PointLight.prototype.getAbsolutePosition = function () {
  31715. return this.transformedPosition ? this.transformedPosition : this.position;
  31716. };
  31717. /**
  31718. * Computes the PointLight transformed position if parented. Returns true if ok, false if not parented.
  31719. */
  31720. PointLight.prototype.computeTransformedPosition = function () {
  31721. if (this.parent && this.parent.getWorldMatrix) {
  31722. if (!this.transformedPosition) {
  31723. this.transformedPosition = BABYLON.Vector3.Zero();
  31724. }
  31725. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  31726. return true;
  31727. }
  31728. return false;
  31729. };
  31730. /**
  31731. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  31732. * Returns the PointLight.
  31733. */
  31734. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  31735. if (this.parent && this.parent.getWorldMatrix) {
  31736. this.computeTransformedPosition();
  31737. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  31738. return this;
  31739. }
  31740. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  31741. return this;
  31742. };
  31743. /**
  31744. * Boolean : returns true by default.
  31745. */
  31746. PointLight.prototype.needCube = function () {
  31747. return true;
  31748. };
  31749. /**
  31750. * Boolean : returns false by default.
  31751. */
  31752. PointLight.prototype.needRefreshPerFrame = function () {
  31753. return false;
  31754. };
  31755. /**
  31756. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  31757. */
  31758. PointLight.prototype.getShadowDirection = function (faceIndex) {
  31759. switch (faceIndex) {
  31760. case 0:
  31761. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  31762. case 1:
  31763. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  31764. case 2:
  31765. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  31766. case 3:
  31767. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  31768. case 4:
  31769. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  31770. case 5:
  31771. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  31772. }
  31773. return BABYLON.Vector3.Zero();
  31774. };
  31775. /**
  31776. * Return the depth scale used for the shadow map.
  31777. */
  31778. PointLight.prototype.getDepthScale = function () {
  31779. return 30.0;
  31780. };
  31781. /**
  31782. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  31783. * - fov = PI / 2
  31784. * - aspect ratio : 1.0
  31785. * - z-near and far equal to the active camera minZ and maxZ.
  31786. * Returns the PointLight.
  31787. */
  31788. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  31789. if (this.customProjectionMatrixBuilder) {
  31790. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  31791. }
  31792. else {
  31793. var activeCamera = this.getScene().activeCamera;
  31794. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  31795. }
  31796. return this;
  31797. };
  31798. PointLight.prototype._getWorldMatrix = function () {
  31799. if (!this._worldMatrix) {
  31800. this._worldMatrix = BABYLON.Matrix.Identity();
  31801. }
  31802. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  31803. return this._worldMatrix;
  31804. };
  31805. /**
  31806. * Returns the integer 0.
  31807. */
  31808. PointLight.prototype.getTypeID = function () {
  31809. return 0;
  31810. };
  31811. return PointLight;
  31812. }(BABYLON.Light));
  31813. __decorate([
  31814. BABYLON.serializeAsVector3()
  31815. ], PointLight.prototype, "position", void 0);
  31816. __decorate([
  31817. BABYLON.serialize()
  31818. ], PointLight.prototype, "shadowMinZ", void 0);
  31819. __decorate([
  31820. BABYLON.serialize()
  31821. ], PointLight.prototype, "shadowMaxZ", void 0);
  31822. BABYLON.PointLight = PointLight;
  31823. })(BABYLON || (BABYLON = {}));
  31824. //# sourceMappingURL=babylon.pointLight.js.map
  31825. /// <reference path="babylon.light.ts" />
  31826. var BABYLON;
  31827. (function (BABYLON) {
  31828. var DirectionalLight = (function (_super) {
  31829. __extends(DirectionalLight, _super);
  31830. /**
  31831. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  31832. * The directional light is emitted from everywhere in the given direction.
  31833. * It can cast shawdows.
  31834. * Documentation : http://doc.babylonjs.com/tutorials/lights
  31835. */
  31836. function DirectionalLight(name, direction, scene) {
  31837. var _this = _super.call(this, name, scene) || this;
  31838. _this.shadowOrthoScale = 0.5;
  31839. _this.autoUpdateExtends = true;
  31840. // Cache
  31841. _this._orthoLeft = Number.MAX_VALUE;
  31842. _this._orthoRight = Number.MIN_VALUE;
  31843. _this._orthoTop = Number.MIN_VALUE;
  31844. _this._orthoBottom = Number.MAX_VALUE;
  31845. _this.position = direction.scale(-1.0);
  31846. _this.direction = direction;
  31847. return _this;
  31848. }
  31849. DirectionalLight.prototype._buildUniformLayout = function () {
  31850. this._uniformBuffer.addUniform("vLightData", 4);
  31851. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  31852. this._uniformBuffer.addUniform("vLightSpecular", 3);
  31853. this._uniformBuffer.addUniform("shadowsInfo", 3);
  31854. this._uniformBuffer.create();
  31855. };
  31856. /**
  31857. * Returns the string "DirectionalLight".
  31858. */
  31859. DirectionalLight.prototype.getClassName = function () {
  31860. return "DirectionalLight";
  31861. };
  31862. /**
  31863. * Returns the DirectionalLight absolute position in the World.
  31864. */
  31865. DirectionalLight.prototype.getAbsolutePosition = function () {
  31866. return this.transformedPosition ? this.transformedPosition : this.position;
  31867. };
  31868. /**
  31869. * Sets the DirectionalLight direction toward the passed target (Vector3).
  31870. * Returns the updated DirectionalLight direction (Vector3).
  31871. */
  31872. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  31873. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  31874. return this.direction;
  31875. };
  31876. /**
  31877. * Return the depth scale used for the shadow map.
  31878. */
  31879. DirectionalLight.prototype.getDepthScale = function () {
  31880. return 30.0;
  31881. };
  31882. /**
  31883. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  31884. * Returns the DirectionalLight.
  31885. */
  31886. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  31887. if (this.customProjectionMatrixBuilder) {
  31888. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  31889. }
  31890. else {
  31891. var activeCamera = this.getScene().activeCamera;
  31892. // Check extends
  31893. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  31894. var tempVector3 = BABYLON.Vector3.Zero();
  31895. this._orthoLeft = Number.MAX_VALUE;
  31896. this._orthoRight = Number.MIN_VALUE;
  31897. this._orthoTop = Number.MIN_VALUE;
  31898. this._orthoBottom = Number.MAX_VALUE;
  31899. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  31900. var mesh = renderList[meshIndex];
  31901. if (!mesh) {
  31902. continue;
  31903. }
  31904. var boundingInfo = mesh.getBoundingInfo();
  31905. if (!boundingInfo) {
  31906. continue;
  31907. }
  31908. var boundingBox = boundingInfo.boundingBox;
  31909. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  31910. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  31911. if (tempVector3.x < this._orthoLeft)
  31912. this._orthoLeft = tempVector3.x;
  31913. if (tempVector3.y < this._orthoBottom)
  31914. this._orthoBottom = tempVector3.y;
  31915. if (tempVector3.x > this._orthoRight)
  31916. this._orthoRight = tempVector3.x;
  31917. if (tempVector3.y > this._orthoTop)
  31918. this._orthoTop = tempVector3.y;
  31919. }
  31920. }
  31921. }
  31922. var xOffset = this._orthoRight - this._orthoLeft;
  31923. var yOffset = this._orthoTop - this._orthoBottom;
  31924. 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);
  31925. }
  31926. return this;
  31927. };
  31928. /**
  31929. * Boolean : true by default.
  31930. */
  31931. DirectionalLight.prototype.needRefreshPerFrame = function () {
  31932. return true;
  31933. };
  31934. /**
  31935. * Boolean : false by default.
  31936. */
  31937. DirectionalLight.prototype.needCube = function () {
  31938. return false;
  31939. };
  31940. /**
  31941. * Returns the light direction (Vector3) for any passed face index.
  31942. */
  31943. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  31944. return this.direction;
  31945. };
  31946. /**
  31947. * Computes the light transformed position in case the light is parented. Returns true if parented, else false.
  31948. */
  31949. DirectionalLight.prototype.computeTransformedPosition = function () {
  31950. if (this.parent && this.parent.getWorldMatrix) {
  31951. if (!this.transformedPosition) {
  31952. this.transformedPosition = BABYLON.Vector3.Zero();
  31953. }
  31954. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  31955. return true;
  31956. }
  31957. return false;
  31958. };
  31959. /**
  31960. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  31961. * Returns the DirectionalLight.
  31962. */
  31963. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  31964. if (this.parent && this.parent.getWorldMatrix) {
  31965. if (!this._transformedDirection) {
  31966. this._transformedDirection = BABYLON.Vector3.Zero();
  31967. }
  31968. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  31969. this._uniformBuffer.updateFloat4("vLightData", this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1, lightIndex);
  31970. return this;
  31971. }
  31972. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  31973. return this;
  31974. };
  31975. DirectionalLight.prototype._getWorldMatrix = function () {
  31976. if (!this._worldMatrix) {
  31977. this._worldMatrix = BABYLON.Matrix.Identity();
  31978. }
  31979. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  31980. return this._worldMatrix;
  31981. };
  31982. /**
  31983. * Returns the integer 1.
  31984. */
  31985. DirectionalLight.prototype.getTypeID = function () {
  31986. return 1;
  31987. };
  31988. return DirectionalLight;
  31989. }(BABYLON.Light));
  31990. __decorate([
  31991. BABYLON.serializeAsVector3()
  31992. ], DirectionalLight.prototype, "position", void 0);
  31993. __decorate([
  31994. BABYLON.serializeAsVector3()
  31995. ], DirectionalLight.prototype, "direction", void 0);
  31996. __decorate([
  31997. BABYLON.serialize()
  31998. ], DirectionalLight.prototype, "shadowOrthoScale", void 0);
  31999. __decorate([
  32000. BABYLON.serialize()
  32001. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  32002. __decorate([
  32003. BABYLON.serialize()
  32004. ], DirectionalLight.prototype, "shadowMinZ", void 0);
  32005. __decorate([
  32006. BABYLON.serialize()
  32007. ], DirectionalLight.prototype, "shadowMaxZ", void 0);
  32008. BABYLON.DirectionalLight = DirectionalLight;
  32009. })(BABYLON || (BABYLON = {}));
  32010. //# sourceMappingURL=babylon.directionalLight.js.map
  32011. var BABYLON;
  32012. (function (BABYLON) {
  32013. var SpotLight = (function (_super) {
  32014. __extends(SpotLight, _super);
  32015. /**
  32016. * Creates a SpotLight object in the scene with the passed parameters :
  32017. * - `position` (Vector3) is the initial SpotLight position,
  32018. * - `direction` (Vector3) is the initial SpotLight direction,
  32019. * - `angle` (float, in radians) is the spot light cone angle,
  32020. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  32021. * A spot light is a simply light oriented cone.
  32022. * It can cast shadows.
  32023. * Documentation : http://doc.babylonjs.com/tutorials/lights
  32024. */
  32025. function SpotLight(name, position, direction, angle, exponent, scene) {
  32026. var _this = _super.call(this, name, scene) || this;
  32027. _this.position = position;
  32028. _this.direction = direction;
  32029. _this.angle = angle;
  32030. _this.exponent = exponent;
  32031. return _this;
  32032. }
  32033. SpotLight.prototype._buildUniformLayout = function () {
  32034. this._uniformBuffer.addUniform("vLightData", 4);
  32035. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  32036. this._uniformBuffer.addUniform("vLightSpecular", 3);
  32037. this._uniformBuffer.addUniform("vLightDirection", 3);
  32038. this._uniformBuffer.addUniform("shadowsInfo", 3);
  32039. this._uniformBuffer.create();
  32040. };
  32041. /**
  32042. * Returns the string "SpotLight".
  32043. */
  32044. SpotLight.prototype.getClassName = function () {
  32045. return "SpotLight";
  32046. };
  32047. /**
  32048. * Returns the SpotLight absolute position in the World (Vector3).
  32049. */
  32050. SpotLight.prototype.getAbsolutePosition = function () {
  32051. return this.transformedPosition ? this.transformedPosition : this.position;
  32052. };
  32053. /**
  32054. * Return the depth scale used for the shadow map.
  32055. */
  32056. SpotLight.prototype.getDepthScale = function () {
  32057. return 30.0;
  32058. };
  32059. /**
  32060. * 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.
  32061. * Returns the SpotLight.
  32062. */
  32063. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  32064. if (this.customProjectionMatrixBuilder) {
  32065. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  32066. }
  32067. else {
  32068. var activeCamera = this.getScene().activeCamera;
  32069. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  32070. }
  32071. return this;
  32072. };
  32073. /**
  32074. * Boolean : false by default.
  32075. */
  32076. SpotLight.prototype.needCube = function () {
  32077. return false;
  32078. };
  32079. /**
  32080. * Boolean : false by default.
  32081. */
  32082. SpotLight.prototype.needRefreshPerFrame = function () {
  32083. return false;
  32084. };
  32085. /**
  32086. * Returns the SpotLight direction (Vector3) for any passed face index.
  32087. */
  32088. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  32089. return this.direction;
  32090. };
  32091. /**
  32092. * Updates the SpotLight direction towards the passed target (Vector3).
  32093. * Returns the updated direction.
  32094. */
  32095. SpotLight.prototype.setDirectionToTarget = function (target) {
  32096. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  32097. return this.direction;
  32098. };
  32099. /**
  32100. * Computes the SpotLight transformed position if parented. Returns true if parented, else false.
  32101. */
  32102. SpotLight.prototype.computeTransformedPosition = function () {
  32103. if (this.parent && this.parent.getWorldMatrix) {
  32104. if (!this.transformedPosition) {
  32105. this.transformedPosition = BABYLON.Vector3.Zero();
  32106. }
  32107. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  32108. return true;
  32109. }
  32110. return false;
  32111. };
  32112. /**
  32113. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  32114. * Return the SpotLight.
  32115. */
  32116. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  32117. var normalizeDirection;
  32118. if (this.parent && this.parent.getWorldMatrix) {
  32119. if (!this._transformedDirection) {
  32120. this._transformedDirection = BABYLON.Vector3.Zero();
  32121. }
  32122. this.computeTransformedPosition();
  32123. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  32124. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  32125. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  32126. }
  32127. else {
  32128. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  32129. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  32130. }
  32131. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  32132. return this;
  32133. };
  32134. SpotLight.prototype._getWorldMatrix = function () {
  32135. if (!this._worldMatrix) {
  32136. this._worldMatrix = BABYLON.Matrix.Identity();
  32137. }
  32138. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  32139. return this._worldMatrix;
  32140. };
  32141. /**
  32142. * Returns the integer 2.
  32143. */
  32144. SpotLight.prototype.getTypeID = function () {
  32145. return 2;
  32146. };
  32147. /**
  32148. * Returns the SpotLight rotation (Vector3).
  32149. */
  32150. SpotLight.prototype.getRotation = function () {
  32151. this.direction.normalize();
  32152. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  32153. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  32154. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  32155. };
  32156. return SpotLight;
  32157. }(BABYLON.Light));
  32158. __decorate([
  32159. BABYLON.serializeAsVector3()
  32160. ], SpotLight.prototype, "position", void 0);
  32161. __decorate([
  32162. BABYLON.serializeAsVector3()
  32163. ], SpotLight.prototype, "direction", void 0);
  32164. __decorate([
  32165. BABYLON.serialize()
  32166. ], SpotLight.prototype, "angle", void 0);
  32167. __decorate([
  32168. BABYLON.serialize()
  32169. ], SpotLight.prototype, "exponent", void 0);
  32170. __decorate([
  32171. BABYLON.serialize()
  32172. ], SpotLight.prototype, "shadowMinZ", void 0);
  32173. __decorate([
  32174. BABYLON.serialize()
  32175. ], SpotLight.prototype, "shadowMaxZ", void 0);
  32176. BABYLON.SpotLight = SpotLight;
  32177. })(BABYLON || (BABYLON = {}));
  32178. //# sourceMappingURL=babylon.spotLight.js.map
  32179. var BABYLON;
  32180. (function (BABYLON) {
  32181. var AnimationRange = (function () {
  32182. function AnimationRange(name, from, to) {
  32183. this.name = name;
  32184. this.from = from;
  32185. this.to = to;
  32186. }
  32187. AnimationRange.prototype.clone = function () {
  32188. return new AnimationRange(this.name, this.from, this.to);
  32189. };
  32190. return AnimationRange;
  32191. }());
  32192. BABYLON.AnimationRange = AnimationRange;
  32193. /**
  32194. * Composed of a frame, and an action function
  32195. */
  32196. var AnimationEvent = (function () {
  32197. function AnimationEvent(frame, action, onlyOnce) {
  32198. this.frame = frame;
  32199. this.action = action;
  32200. this.onlyOnce = onlyOnce;
  32201. this.isDone = false;
  32202. }
  32203. return AnimationEvent;
  32204. }());
  32205. BABYLON.AnimationEvent = AnimationEvent;
  32206. var PathCursor = (function () {
  32207. function PathCursor(path) {
  32208. this.path = path;
  32209. this._onchange = new Array();
  32210. this.value = 0;
  32211. this.animations = new Array();
  32212. }
  32213. PathCursor.prototype.getPoint = function () {
  32214. var point = this.path.getPointAtLengthPosition(this.value);
  32215. return new BABYLON.Vector3(point.x, 0, point.y);
  32216. };
  32217. PathCursor.prototype.moveAhead = function (step) {
  32218. if (step === void 0) { step = 0.002; }
  32219. this.move(step);
  32220. return this;
  32221. };
  32222. PathCursor.prototype.moveBack = function (step) {
  32223. if (step === void 0) { step = 0.002; }
  32224. this.move(-step);
  32225. return this;
  32226. };
  32227. PathCursor.prototype.move = function (step) {
  32228. if (Math.abs(step) > 1) {
  32229. throw "step size should be less than 1.";
  32230. }
  32231. this.value += step;
  32232. this.ensureLimits();
  32233. this.raiseOnChange();
  32234. return this;
  32235. };
  32236. PathCursor.prototype.ensureLimits = function () {
  32237. while (this.value > 1) {
  32238. this.value -= 1;
  32239. }
  32240. while (this.value < 0) {
  32241. this.value += 1;
  32242. }
  32243. return this;
  32244. };
  32245. // used by animation engine
  32246. PathCursor.prototype.markAsDirty = function (propertyName) {
  32247. this.ensureLimits();
  32248. this.raiseOnChange();
  32249. return this;
  32250. };
  32251. PathCursor.prototype.raiseOnChange = function () {
  32252. var _this = this;
  32253. this._onchange.forEach(function (f) { return f(_this); });
  32254. return this;
  32255. };
  32256. PathCursor.prototype.onchange = function (f) {
  32257. this._onchange.push(f);
  32258. return this;
  32259. };
  32260. return PathCursor;
  32261. }());
  32262. BABYLON.PathCursor = PathCursor;
  32263. var Animation = (function () {
  32264. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  32265. this.name = name;
  32266. this.targetProperty = targetProperty;
  32267. this.framePerSecond = framePerSecond;
  32268. this.dataType = dataType;
  32269. this.loopMode = loopMode;
  32270. this.enableBlending = enableBlending;
  32271. this._offsetsCache = {};
  32272. this._highLimitsCache = {};
  32273. this._stopped = false;
  32274. this._blendingFactor = 0;
  32275. // The set of event that will be linked to this animation
  32276. this._events = new Array();
  32277. this.allowMatricesInterpolation = false;
  32278. this.blendingSpeed = 0.01;
  32279. this._ranges = {};
  32280. this.targetPropertyPath = targetProperty.split(".");
  32281. this.dataType = dataType;
  32282. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  32283. }
  32284. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  32285. var dataType = undefined;
  32286. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  32287. dataType = Animation.ANIMATIONTYPE_FLOAT;
  32288. }
  32289. else if (from instanceof BABYLON.Quaternion) {
  32290. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  32291. }
  32292. else if (from instanceof BABYLON.Vector3) {
  32293. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  32294. }
  32295. else if (from instanceof BABYLON.Vector2) {
  32296. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  32297. }
  32298. else if (from instanceof BABYLON.Color3) {
  32299. dataType = Animation.ANIMATIONTYPE_COLOR3;
  32300. }
  32301. else if (from instanceof BABYLON.Size) {
  32302. dataType = Animation.ANIMATIONTYPE_SIZE;
  32303. }
  32304. if (dataType == undefined) {
  32305. return null;
  32306. }
  32307. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  32308. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  32309. animation.setKeys(keys);
  32310. if (easingFunction !== undefined) {
  32311. animation.setEasingFunction(easingFunction);
  32312. }
  32313. return animation;
  32314. };
  32315. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  32316. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  32317. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  32318. };
  32319. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  32320. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  32321. node.animations.push(animation);
  32322. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  32323. };
  32324. // Methods
  32325. /**
  32326. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  32327. */
  32328. Animation.prototype.toString = function (fullDetails) {
  32329. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  32330. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  32331. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  32332. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  32333. if (fullDetails) {
  32334. ret += ", Ranges: {";
  32335. var first = true;
  32336. for (var name in this._ranges) {
  32337. if (first) {
  32338. ret += ", ";
  32339. first = false;
  32340. }
  32341. ret += name;
  32342. }
  32343. ret += "}";
  32344. }
  32345. return ret;
  32346. };
  32347. /**
  32348. * Add an event to this animation.
  32349. */
  32350. Animation.prototype.addEvent = function (event) {
  32351. this._events.push(event);
  32352. };
  32353. /**
  32354. * Remove all events found at the given frame
  32355. * @param frame
  32356. */
  32357. Animation.prototype.removeEvents = function (frame) {
  32358. for (var index = 0; index < this._events.length; index++) {
  32359. if (this._events[index].frame === frame) {
  32360. this._events.splice(index, 1);
  32361. index--;
  32362. }
  32363. }
  32364. };
  32365. Animation.prototype.createRange = function (name, from, to) {
  32366. // check name not already in use; could happen for bones after serialized
  32367. if (!this._ranges[name]) {
  32368. this._ranges[name] = new AnimationRange(name, from, to);
  32369. }
  32370. };
  32371. Animation.prototype.deleteRange = function (name, deleteFrames) {
  32372. if (deleteFrames === void 0) { deleteFrames = true; }
  32373. if (this._ranges[name]) {
  32374. if (deleteFrames) {
  32375. var from = this._ranges[name].from;
  32376. var to = this._ranges[name].to;
  32377. // this loop MUST go high to low for multiple splices to work
  32378. for (var key = this._keys.length - 1; key >= 0; key--) {
  32379. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  32380. this._keys.splice(key, 1);
  32381. }
  32382. }
  32383. }
  32384. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  32385. }
  32386. };
  32387. Animation.prototype.getRange = function (name) {
  32388. return this._ranges[name];
  32389. };
  32390. Animation.prototype.reset = function () {
  32391. this._offsetsCache = {};
  32392. this._highLimitsCache = {};
  32393. this.currentFrame = 0;
  32394. this._blendingFactor = 0;
  32395. this._originalBlendValue = null;
  32396. };
  32397. Animation.prototype.isStopped = function () {
  32398. return this._stopped;
  32399. };
  32400. Animation.prototype.getKeys = function () {
  32401. return this._keys;
  32402. };
  32403. Animation.prototype.getHighestFrame = function () {
  32404. var ret = 0;
  32405. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  32406. if (ret < this._keys[key].frame) {
  32407. ret = this._keys[key].frame;
  32408. }
  32409. }
  32410. return ret;
  32411. };
  32412. Animation.prototype.getEasingFunction = function () {
  32413. return this._easingFunction;
  32414. };
  32415. Animation.prototype.setEasingFunction = function (easingFunction) {
  32416. this._easingFunction = easingFunction;
  32417. };
  32418. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  32419. return startValue + (endValue - startValue) * gradient;
  32420. };
  32421. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  32422. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  32423. };
  32424. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  32425. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  32426. };
  32427. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  32428. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  32429. };
  32430. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  32431. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  32432. };
  32433. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  32434. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  32435. };
  32436. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  32437. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  32438. };
  32439. Animation.prototype.clone = function () {
  32440. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  32441. clone.enableBlending = this.enableBlending;
  32442. clone.blendingSpeed = this.blendingSpeed;
  32443. if (this._keys) {
  32444. clone.setKeys(this._keys);
  32445. }
  32446. if (this._ranges) {
  32447. clone._ranges = {};
  32448. for (var name in this._ranges) {
  32449. clone._ranges[name] = this._ranges[name].clone();
  32450. }
  32451. }
  32452. return clone;
  32453. };
  32454. Animation.prototype.setKeys = function (values) {
  32455. this._keys = values.slice(0);
  32456. this._offsetsCache = {};
  32457. this._highLimitsCache = {};
  32458. };
  32459. Animation.prototype._getKeyValue = function (value) {
  32460. if (typeof value === "function") {
  32461. return value();
  32462. }
  32463. return value;
  32464. };
  32465. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  32466. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  32467. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  32468. }
  32469. this.currentFrame = currentFrame;
  32470. // Try to get a hash to find the right key
  32471. 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));
  32472. if (this._keys[startKey].frame >= currentFrame) {
  32473. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  32474. startKey--;
  32475. }
  32476. }
  32477. for (var key = startKey; key < this._keys.length; key++) {
  32478. if (this._keys[key + 1].frame >= currentFrame) {
  32479. var startValue = this._getKeyValue(this._keys[key].value);
  32480. var endValue = this._getKeyValue(this._keys[key + 1].value);
  32481. // gradient : percent of currentFrame between the frame inf and the frame sup
  32482. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  32483. // check for easingFunction and correction of gradient
  32484. if (this._easingFunction != null) {
  32485. gradient = this._easingFunction.ease(gradient);
  32486. }
  32487. switch (this.dataType) {
  32488. // Float
  32489. case Animation.ANIMATIONTYPE_FLOAT:
  32490. switch (loopMode) {
  32491. case Animation.ANIMATIONLOOPMODE_CYCLE:
  32492. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  32493. return this.floatInterpolateFunction(startValue, endValue, gradient);
  32494. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  32495. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  32496. }
  32497. break;
  32498. // Quaternion
  32499. case Animation.ANIMATIONTYPE_QUATERNION:
  32500. var quaternion = null;
  32501. switch (loopMode) {
  32502. case Animation.ANIMATIONLOOPMODE_CYCLE:
  32503. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  32504. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  32505. break;
  32506. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  32507. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  32508. break;
  32509. }
  32510. return quaternion;
  32511. // Vector3
  32512. case Animation.ANIMATIONTYPE_VECTOR3:
  32513. switch (loopMode) {
  32514. case Animation.ANIMATIONLOOPMODE_CYCLE:
  32515. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  32516. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  32517. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  32518. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  32519. }
  32520. // Vector2
  32521. case Animation.ANIMATIONTYPE_VECTOR2:
  32522. switch (loopMode) {
  32523. case Animation.ANIMATIONLOOPMODE_CYCLE:
  32524. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  32525. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  32526. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  32527. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  32528. }
  32529. // Size
  32530. case Animation.ANIMATIONTYPE_SIZE:
  32531. switch (loopMode) {
  32532. case Animation.ANIMATIONLOOPMODE_CYCLE:
  32533. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  32534. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  32535. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  32536. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  32537. }
  32538. // Color3
  32539. case Animation.ANIMATIONTYPE_COLOR3:
  32540. switch (loopMode) {
  32541. case Animation.ANIMATIONLOOPMODE_CYCLE:
  32542. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  32543. return this.color3InterpolateFunction(startValue, endValue, gradient);
  32544. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  32545. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  32546. }
  32547. // Matrix
  32548. case Animation.ANIMATIONTYPE_MATRIX:
  32549. switch (loopMode) {
  32550. case Animation.ANIMATIONLOOPMODE_CYCLE:
  32551. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  32552. if (this.allowMatricesInterpolation) {
  32553. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  32554. }
  32555. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  32556. return startValue;
  32557. }
  32558. default:
  32559. break;
  32560. }
  32561. break;
  32562. }
  32563. }
  32564. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  32565. };
  32566. Animation.prototype.setValue = function (currentValue, blend) {
  32567. if (blend === void 0) { blend = false; }
  32568. // Set value
  32569. var path;
  32570. var destination;
  32571. if (this.targetPropertyPath.length > 1) {
  32572. var property = this._target[this.targetPropertyPath[0]];
  32573. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  32574. property = property[this.targetPropertyPath[index]];
  32575. }
  32576. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  32577. destination = property;
  32578. }
  32579. else {
  32580. path = this.targetPropertyPath[0];
  32581. destination = this._target;
  32582. }
  32583. // Blending
  32584. if (this.enableBlending && this._blendingFactor <= 1.0) {
  32585. if (!this._originalBlendValue) {
  32586. if (destination[path].clone) {
  32587. this._originalBlendValue = destination[path].clone();
  32588. }
  32589. else {
  32590. this._originalBlendValue = destination[path];
  32591. }
  32592. }
  32593. if (this._originalBlendValue.prototype) {
  32594. if (this._originalBlendValue.prototype.Lerp) {
  32595. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  32596. }
  32597. else {
  32598. destination[path] = currentValue;
  32599. }
  32600. }
  32601. else if (this._originalBlendValue.m) {
  32602. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  32603. }
  32604. else {
  32605. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  32606. }
  32607. this._blendingFactor += this.blendingSpeed;
  32608. }
  32609. else {
  32610. destination[path] = currentValue;
  32611. }
  32612. if (this._target.markAsDirty) {
  32613. this._target.markAsDirty(this.targetProperty);
  32614. }
  32615. };
  32616. Animation.prototype.goToFrame = function (frame) {
  32617. if (frame < this._keys[0].frame) {
  32618. frame = this._keys[0].frame;
  32619. }
  32620. else if (frame > this._keys[this._keys.length - 1].frame) {
  32621. frame = this._keys[this._keys.length - 1].frame;
  32622. }
  32623. var currentValue = this._interpolate(frame, 0, this.loopMode);
  32624. this.setValue(currentValue);
  32625. };
  32626. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  32627. if (blend === void 0) { blend = false; }
  32628. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  32629. this._stopped = true;
  32630. return false;
  32631. }
  32632. var returnValue = true;
  32633. // Adding a start key at frame 0 if missing
  32634. if (this._keys[0].frame !== 0) {
  32635. var newKey = { frame: 0, value: this._keys[0].value };
  32636. this._keys.splice(0, 0, newKey);
  32637. }
  32638. // Check limits
  32639. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  32640. from = this._keys[0].frame;
  32641. }
  32642. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  32643. to = this._keys[this._keys.length - 1].frame;
  32644. }
  32645. //to and from cannot be the same key
  32646. if (from === to) {
  32647. from++;
  32648. }
  32649. // Compute ratio
  32650. var range = to - from;
  32651. var offsetValue;
  32652. // ratio represents the frame delta between from and to
  32653. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  32654. var highLimitValue = 0;
  32655. if (ratio > range && !loop) {
  32656. returnValue = false;
  32657. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  32658. }
  32659. else {
  32660. // Get max value if required
  32661. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  32662. var keyOffset = to.toString() + from.toString();
  32663. if (!this._offsetsCache[keyOffset]) {
  32664. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  32665. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  32666. switch (this.dataType) {
  32667. // Float
  32668. case Animation.ANIMATIONTYPE_FLOAT:
  32669. this._offsetsCache[keyOffset] = toValue - fromValue;
  32670. break;
  32671. // Quaternion
  32672. case Animation.ANIMATIONTYPE_QUATERNION:
  32673. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  32674. break;
  32675. // Vector3
  32676. case Animation.ANIMATIONTYPE_VECTOR3:
  32677. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  32678. // Vector2
  32679. case Animation.ANIMATIONTYPE_VECTOR2:
  32680. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  32681. // Size
  32682. case Animation.ANIMATIONTYPE_SIZE:
  32683. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  32684. // Color3
  32685. case Animation.ANIMATIONTYPE_COLOR3:
  32686. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  32687. default:
  32688. break;
  32689. }
  32690. this._highLimitsCache[keyOffset] = toValue;
  32691. }
  32692. highLimitValue = this._highLimitsCache[keyOffset];
  32693. offsetValue = this._offsetsCache[keyOffset];
  32694. }
  32695. }
  32696. if (offsetValue === undefined) {
  32697. switch (this.dataType) {
  32698. // Float
  32699. case Animation.ANIMATIONTYPE_FLOAT:
  32700. offsetValue = 0;
  32701. break;
  32702. // Quaternion
  32703. case Animation.ANIMATIONTYPE_QUATERNION:
  32704. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  32705. break;
  32706. // Vector3
  32707. case Animation.ANIMATIONTYPE_VECTOR3:
  32708. offsetValue = BABYLON.Vector3.Zero();
  32709. break;
  32710. // Vector2
  32711. case Animation.ANIMATIONTYPE_VECTOR2:
  32712. offsetValue = BABYLON.Vector2.Zero();
  32713. break;
  32714. // Size
  32715. case Animation.ANIMATIONTYPE_SIZE:
  32716. offsetValue = BABYLON.Size.Zero();
  32717. break;
  32718. // Color3
  32719. case Animation.ANIMATIONTYPE_COLOR3:
  32720. offsetValue = BABYLON.Color3.Black();
  32721. }
  32722. }
  32723. // Compute value
  32724. var repeatCount = (ratio / range) >> 0;
  32725. var currentFrame = returnValue ? from + ratio % range : to;
  32726. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  32727. // Set value
  32728. this.setValue(currentValue);
  32729. // Check events
  32730. for (var index = 0; index < this._events.length; index++) {
  32731. if (currentFrame >= this._events[index].frame) {
  32732. var event = this._events[index];
  32733. if (!event.isDone) {
  32734. // If event should be done only once, remove it.
  32735. if (event.onlyOnce) {
  32736. this._events.splice(index, 1);
  32737. index--;
  32738. }
  32739. event.isDone = true;
  32740. event.action();
  32741. } // Don't do anything if the event has already be done.
  32742. }
  32743. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  32744. // reset event, the animation is looping
  32745. this._events[index].isDone = false;
  32746. }
  32747. }
  32748. if (!returnValue) {
  32749. this._stopped = true;
  32750. }
  32751. return returnValue;
  32752. };
  32753. Animation.prototype.serialize = function () {
  32754. var serializationObject = {};
  32755. serializationObject.name = this.name;
  32756. serializationObject.property = this.targetProperty;
  32757. serializationObject.framePerSecond = this.framePerSecond;
  32758. serializationObject.dataType = this.dataType;
  32759. serializationObject.loopBehavior = this.loopMode;
  32760. serializationObject.enableBlending = this.enableBlending;
  32761. serializationObject.blendingSpeed = this.blendingSpeed;
  32762. var dataType = this.dataType;
  32763. serializationObject.keys = [];
  32764. var keys = this.getKeys();
  32765. for (var index = 0; index < keys.length; index++) {
  32766. var animationKey = keys[index];
  32767. var key = {};
  32768. key.frame = animationKey.frame;
  32769. switch (dataType) {
  32770. case Animation.ANIMATIONTYPE_FLOAT:
  32771. key.values = [animationKey.value];
  32772. break;
  32773. case Animation.ANIMATIONTYPE_QUATERNION:
  32774. case Animation.ANIMATIONTYPE_MATRIX:
  32775. case Animation.ANIMATIONTYPE_VECTOR3:
  32776. case Animation.ANIMATIONTYPE_COLOR3:
  32777. key.values = animationKey.value.asArray();
  32778. break;
  32779. }
  32780. serializationObject.keys.push(key);
  32781. }
  32782. serializationObject.ranges = [];
  32783. for (var name in this._ranges) {
  32784. var range = {};
  32785. range.name = name;
  32786. range.from = this._ranges[name].from;
  32787. range.to = this._ranges[name].to;
  32788. serializationObject.ranges.push(range);
  32789. }
  32790. return serializationObject;
  32791. };
  32792. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  32793. get: function () {
  32794. return Animation._ANIMATIONTYPE_FLOAT;
  32795. },
  32796. enumerable: true,
  32797. configurable: true
  32798. });
  32799. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  32800. get: function () {
  32801. return Animation._ANIMATIONTYPE_VECTOR3;
  32802. },
  32803. enumerable: true,
  32804. configurable: true
  32805. });
  32806. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  32807. get: function () {
  32808. return Animation._ANIMATIONTYPE_VECTOR2;
  32809. },
  32810. enumerable: true,
  32811. configurable: true
  32812. });
  32813. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  32814. get: function () {
  32815. return Animation._ANIMATIONTYPE_SIZE;
  32816. },
  32817. enumerable: true,
  32818. configurable: true
  32819. });
  32820. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  32821. get: function () {
  32822. return Animation._ANIMATIONTYPE_QUATERNION;
  32823. },
  32824. enumerable: true,
  32825. configurable: true
  32826. });
  32827. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  32828. get: function () {
  32829. return Animation._ANIMATIONTYPE_MATRIX;
  32830. },
  32831. enumerable: true,
  32832. configurable: true
  32833. });
  32834. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  32835. get: function () {
  32836. return Animation._ANIMATIONTYPE_COLOR3;
  32837. },
  32838. enumerable: true,
  32839. configurable: true
  32840. });
  32841. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  32842. get: function () {
  32843. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  32844. },
  32845. enumerable: true,
  32846. configurable: true
  32847. });
  32848. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  32849. get: function () {
  32850. return Animation._ANIMATIONLOOPMODE_CYCLE;
  32851. },
  32852. enumerable: true,
  32853. configurable: true
  32854. });
  32855. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  32856. get: function () {
  32857. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  32858. },
  32859. enumerable: true,
  32860. configurable: true
  32861. });
  32862. Animation.Parse = function (parsedAnimation) {
  32863. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  32864. var dataType = parsedAnimation.dataType;
  32865. var keys = [];
  32866. var data;
  32867. var index;
  32868. if (parsedAnimation.enableBlending) {
  32869. animation.enableBlending = parsedAnimation.enableBlending;
  32870. }
  32871. if (parsedAnimation.blendingSpeed) {
  32872. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  32873. }
  32874. for (index = 0; index < parsedAnimation.keys.length; index++) {
  32875. var key = parsedAnimation.keys[index];
  32876. switch (dataType) {
  32877. case Animation.ANIMATIONTYPE_FLOAT:
  32878. data = key.values[0];
  32879. break;
  32880. case Animation.ANIMATIONTYPE_QUATERNION:
  32881. data = BABYLON.Quaternion.FromArray(key.values);
  32882. break;
  32883. case Animation.ANIMATIONTYPE_MATRIX:
  32884. data = BABYLON.Matrix.FromArray(key.values);
  32885. break;
  32886. case Animation.ANIMATIONTYPE_COLOR3:
  32887. data = BABYLON.Color3.FromArray(key.values);
  32888. break;
  32889. case Animation.ANIMATIONTYPE_VECTOR3:
  32890. default:
  32891. data = BABYLON.Vector3.FromArray(key.values);
  32892. break;
  32893. }
  32894. keys.push({
  32895. frame: key.frame,
  32896. value: data
  32897. });
  32898. }
  32899. animation.setKeys(keys);
  32900. if (parsedAnimation.ranges) {
  32901. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  32902. data = parsedAnimation.ranges[index];
  32903. animation.createRange(data.name, data.from, data.to);
  32904. }
  32905. }
  32906. return animation;
  32907. };
  32908. Animation.AppendSerializedAnimations = function (source, destination) {
  32909. if (source.animations) {
  32910. destination.animations = [];
  32911. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  32912. var animation = source.animations[animationIndex];
  32913. destination.animations.push(animation.serialize());
  32914. }
  32915. }
  32916. };
  32917. return Animation;
  32918. }());
  32919. // Statics
  32920. Animation._ANIMATIONTYPE_FLOAT = 0;
  32921. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  32922. Animation._ANIMATIONTYPE_QUATERNION = 2;
  32923. Animation._ANIMATIONTYPE_MATRIX = 3;
  32924. Animation._ANIMATIONTYPE_COLOR3 = 4;
  32925. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  32926. Animation._ANIMATIONTYPE_SIZE = 6;
  32927. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  32928. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  32929. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  32930. BABYLON.Animation = Animation;
  32931. })(BABYLON || (BABYLON = {}));
  32932. //# sourceMappingURL=babylon.animation.js.map
  32933. var BABYLON;
  32934. (function (BABYLON) {
  32935. var Animatable = (function () {
  32936. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  32937. if (fromFrame === void 0) { fromFrame = 0; }
  32938. if (toFrame === void 0) { toFrame = 100; }
  32939. if (loopAnimation === void 0) { loopAnimation = false; }
  32940. if (speedRatio === void 0) { speedRatio = 1.0; }
  32941. this.target = target;
  32942. this.fromFrame = fromFrame;
  32943. this.toFrame = toFrame;
  32944. this.loopAnimation = loopAnimation;
  32945. this.speedRatio = speedRatio;
  32946. this.onAnimationEnd = onAnimationEnd;
  32947. this._animations = new Array();
  32948. this._paused = false;
  32949. this.animationStarted = false;
  32950. if (animations) {
  32951. this.appendAnimations(target, animations);
  32952. }
  32953. this._scene = scene;
  32954. scene._activeAnimatables.push(this);
  32955. }
  32956. // Methods
  32957. Animatable.prototype.getAnimations = function () {
  32958. return this._animations;
  32959. };
  32960. Animatable.prototype.appendAnimations = function (target, animations) {
  32961. for (var index = 0; index < animations.length; index++) {
  32962. var animation = animations[index];
  32963. animation._target = target;
  32964. this._animations.push(animation);
  32965. }
  32966. };
  32967. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  32968. var animations = this._animations;
  32969. for (var index = 0; index < animations.length; index++) {
  32970. if (animations[index].targetProperty === property) {
  32971. return animations[index];
  32972. }
  32973. }
  32974. return null;
  32975. };
  32976. Animatable.prototype.reset = function () {
  32977. var animations = this._animations;
  32978. for (var index = 0; index < animations.length; index++) {
  32979. animations[index].reset();
  32980. }
  32981. this._localDelayOffset = null;
  32982. this._pausedDelay = null;
  32983. };
  32984. Animatable.prototype.enableBlending = function (blendingSpeed) {
  32985. var animations = this._animations;
  32986. for (var index = 0; index < animations.length; index++) {
  32987. animations[index].enableBlending = true;
  32988. animations[index].blendingSpeed = blendingSpeed;
  32989. }
  32990. };
  32991. Animatable.prototype.disableBlending = function () {
  32992. var animations = this._animations;
  32993. for (var index = 0; index < animations.length; index++) {
  32994. animations[index].enableBlending = false;
  32995. }
  32996. };
  32997. Animatable.prototype.goToFrame = function (frame) {
  32998. var animations = this._animations;
  32999. if (animations[0]) {
  33000. var fps = animations[0].framePerSecond;
  33001. var currentFrame = animations[0].currentFrame;
  33002. var adjustTime = frame - currentFrame;
  33003. var delay = adjustTime * 1000 / fps;
  33004. this._localDelayOffset -= delay;
  33005. }
  33006. for (var index = 0; index < animations.length; index++) {
  33007. animations[index].goToFrame(frame);
  33008. }
  33009. };
  33010. Animatable.prototype.pause = function () {
  33011. if (this._paused) {
  33012. return;
  33013. }
  33014. this._paused = true;
  33015. };
  33016. Animatable.prototype.restart = function () {
  33017. this._paused = false;
  33018. };
  33019. Animatable.prototype.stop = function (animationName) {
  33020. if (animationName) {
  33021. var idx = this._scene._activeAnimatables.indexOf(this);
  33022. if (idx > -1) {
  33023. var animations = this._animations;
  33024. for (var index = animations.length - 1; index >= 0; index--) {
  33025. if (typeof animationName === "string" && animations[index].name != animationName) {
  33026. continue;
  33027. }
  33028. animations[index].reset();
  33029. animations.splice(index, 1);
  33030. }
  33031. if (animations.length == 0) {
  33032. this._scene._activeAnimatables.splice(idx, 1);
  33033. if (this.onAnimationEnd) {
  33034. this.onAnimationEnd();
  33035. }
  33036. }
  33037. }
  33038. }
  33039. else {
  33040. var index = this._scene._activeAnimatables.indexOf(this);
  33041. if (index > -1) {
  33042. this._scene._activeAnimatables.splice(index, 1);
  33043. var animations = this._animations;
  33044. for (var index = 0; index < animations.length; index++) {
  33045. animations[index].reset();
  33046. }
  33047. if (this.onAnimationEnd) {
  33048. this.onAnimationEnd();
  33049. }
  33050. }
  33051. }
  33052. };
  33053. Animatable.prototype._animate = function (delay) {
  33054. if (this._paused) {
  33055. this.animationStarted = false;
  33056. if (!this._pausedDelay) {
  33057. this._pausedDelay = delay;
  33058. }
  33059. return true;
  33060. }
  33061. if (!this._localDelayOffset) {
  33062. this._localDelayOffset = delay;
  33063. }
  33064. else if (this._pausedDelay) {
  33065. this._localDelayOffset += delay - this._pausedDelay;
  33066. this._pausedDelay = null;
  33067. }
  33068. // Animating
  33069. var running = false;
  33070. var animations = this._animations;
  33071. var index;
  33072. for (index = 0; index < animations.length; index++) {
  33073. var animation = animations[index];
  33074. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  33075. running = running || isRunning;
  33076. }
  33077. this.animationStarted = running;
  33078. if (!running) {
  33079. // Remove from active animatables
  33080. index = this._scene._activeAnimatables.indexOf(this);
  33081. this._scene._activeAnimatables.splice(index, 1);
  33082. }
  33083. if (!running && this.onAnimationEnd) {
  33084. this.onAnimationEnd();
  33085. this.onAnimationEnd = null;
  33086. }
  33087. return running;
  33088. };
  33089. return Animatable;
  33090. }());
  33091. BABYLON.Animatable = Animatable;
  33092. })(BABYLON || (BABYLON = {}));
  33093. //# sourceMappingURL=babylon.animatable.js.map
  33094. var BABYLON;
  33095. (function (BABYLON) {
  33096. var EasingFunction = (function () {
  33097. function EasingFunction() {
  33098. // Properties
  33099. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  33100. }
  33101. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  33102. get: function () {
  33103. return EasingFunction._EASINGMODE_EASEIN;
  33104. },
  33105. enumerable: true,
  33106. configurable: true
  33107. });
  33108. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  33109. get: function () {
  33110. return EasingFunction._EASINGMODE_EASEOUT;
  33111. },
  33112. enumerable: true,
  33113. configurable: true
  33114. });
  33115. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  33116. get: function () {
  33117. return EasingFunction._EASINGMODE_EASEINOUT;
  33118. },
  33119. enumerable: true,
  33120. configurable: true
  33121. });
  33122. EasingFunction.prototype.setEasingMode = function (easingMode) {
  33123. var n = Math.min(Math.max(easingMode, 0), 2);
  33124. this._easingMode = n;
  33125. };
  33126. EasingFunction.prototype.getEasingMode = function () {
  33127. return this._easingMode;
  33128. };
  33129. EasingFunction.prototype.easeInCore = function (gradient) {
  33130. throw new Error('You must implement this method');
  33131. };
  33132. EasingFunction.prototype.ease = function (gradient) {
  33133. switch (this._easingMode) {
  33134. case EasingFunction.EASINGMODE_EASEIN:
  33135. return this.easeInCore(gradient);
  33136. case EasingFunction.EASINGMODE_EASEOUT:
  33137. return (1 - this.easeInCore(1 - gradient));
  33138. }
  33139. if (gradient >= 0.5) {
  33140. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  33141. }
  33142. return (this.easeInCore(gradient * 2) * 0.5);
  33143. };
  33144. return EasingFunction;
  33145. }());
  33146. //Statics
  33147. EasingFunction._EASINGMODE_EASEIN = 0;
  33148. EasingFunction._EASINGMODE_EASEOUT = 1;
  33149. EasingFunction._EASINGMODE_EASEINOUT = 2;
  33150. BABYLON.EasingFunction = EasingFunction;
  33151. var CircleEase = (function (_super) {
  33152. __extends(CircleEase, _super);
  33153. function CircleEase() {
  33154. return _super !== null && _super.apply(this, arguments) || this;
  33155. }
  33156. CircleEase.prototype.easeInCore = function (gradient) {
  33157. gradient = Math.max(0, Math.min(1, gradient));
  33158. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  33159. };
  33160. return CircleEase;
  33161. }(EasingFunction));
  33162. BABYLON.CircleEase = CircleEase;
  33163. var BackEase = (function (_super) {
  33164. __extends(BackEase, _super);
  33165. function BackEase(amplitude) {
  33166. if (amplitude === void 0) { amplitude = 1; }
  33167. var _this = _super.call(this) || this;
  33168. _this.amplitude = amplitude;
  33169. return _this;
  33170. }
  33171. BackEase.prototype.easeInCore = function (gradient) {
  33172. var num = Math.max(0, this.amplitude);
  33173. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  33174. };
  33175. return BackEase;
  33176. }(EasingFunction));
  33177. BABYLON.BackEase = BackEase;
  33178. var BounceEase = (function (_super) {
  33179. __extends(BounceEase, _super);
  33180. function BounceEase(bounces, bounciness) {
  33181. if (bounces === void 0) { bounces = 3; }
  33182. if (bounciness === void 0) { bounciness = 2; }
  33183. var _this = _super.call(this) || this;
  33184. _this.bounces = bounces;
  33185. _this.bounciness = bounciness;
  33186. return _this;
  33187. }
  33188. BounceEase.prototype.easeInCore = function (gradient) {
  33189. var y = Math.max(0.0, this.bounces);
  33190. var bounciness = this.bounciness;
  33191. if (bounciness <= 1.0) {
  33192. bounciness = 1.001;
  33193. }
  33194. var num9 = Math.pow(bounciness, y);
  33195. var num5 = 1.0 - bounciness;
  33196. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  33197. var num15 = gradient * num4;
  33198. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  33199. var num3 = Math.floor(num65);
  33200. var num13 = num3 + 1.0;
  33201. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  33202. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  33203. var num7 = (num8 + num12) * 0.5;
  33204. var num6 = gradient - num7;
  33205. var num2 = num7 - num8;
  33206. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  33207. };
  33208. return BounceEase;
  33209. }(EasingFunction));
  33210. BABYLON.BounceEase = BounceEase;
  33211. var CubicEase = (function (_super) {
  33212. __extends(CubicEase, _super);
  33213. function CubicEase() {
  33214. return _super !== null && _super.apply(this, arguments) || this;
  33215. }
  33216. CubicEase.prototype.easeInCore = function (gradient) {
  33217. return (gradient * gradient * gradient);
  33218. };
  33219. return CubicEase;
  33220. }(EasingFunction));
  33221. BABYLON.CubicEase = CubicEase;
  33222. var ElasticEase = (function (_super) {
  33223. __extends(ElasticEase, _super);
  33224. function ElasticEase(oscillations, springiness) {
  33225. if (oscillations === void 0) { oscillations = 3; }
  33226. if (springiness === void 0) { springiness = 3; }
  33227. var _this = _super.call(this) || this;
  33228. _this.oscillations = oscillations;
  33229. _this.springiness = springiness;
  33230. return _this;
  33231. }
  33232. ElasticEase.prototype.easeInCore = function (gradient) {
  33233. var num2;
  33234. var num3 = Math.max(0.0, this.oscillations);
  33235. var num = Math.max(0.0, this.springiness);
  33236. if (num == 0) {
  33237. num2 = gradient;
  33238. }
  33239. else {
  33240. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  33241. }
  33242. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  33243. };
  33244. return ElasticEase;
  33245. }(EasingFunction));
  33246. BABYLON.ElasticEase = ElasticEase;
  33247. var ExponentialEase = (function (_super) {
  33248. __extends(ExponentialEase, _super);
  33249. function ExponentialEase(exponent) {
  33250. if (exponent === void 0) { exponent = 2; }
  33251. var _this = _super.call(this) || this;
  33252. _this.exponent = exponent;
  33253. return _this;
  33254. }
  33255. ExponentialEase.prototype.easeInCore = function (gradient) {
  33256. if (this.exponent <= 0) {
  33257. return gradient;
  33258. }
  33259. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  33260. };
  33261. return ExponentialEase;
  33262. }(EasingFunction));
  33263. BABYLON.ExponentialEase = ExponentialEase;
  33264. var PowerEase = (function (_super) {
  33265. __extends(PowerEase, _super);
  33266. function PowerEase(power) {
  33267. if (power === void 0) { power = 2; }
  33268. var _this = _super.call(this) || this;
  33269. _this.power = power;
  33270. return _this;
  33271. }
  33272. PowerEase.prototype.easeInCore = function (gradient) {
  33273. var y = Math.max(0.0, this.power);
  33274. return Math.pow(gradient, y);
  33275. };
  33276. return PowerEase;
  33277. }(EasingFunction));
  33278. BABYLON.PowerEase = PowerEase;
  33279. var QuadraticEase = (function (_super) {
  33280. __extends(QuadraticEase, _super);
  33281. function QuadraticEase() {
  33282. return _super !== null && _super.apply(this, arguments) || this;
  33283. }
  33284. QuadraticEase.prototype.easeInCore = function (gradient) {
  33285. return (gradient * gradient);
  33286. };
  33287. return QuadraticEase;
  33288. }(EasingFunction));
  33289. BABYLON.QuadraticEase = QuadraticEase;
  33290. var QuarticEase = (function (_super) {
  33291. __extends(QuarticEase, _super);
  33292. function QuarticEase() {
  33293. return _super !== null && _super.apply(this, arguments) || this;
  33294. }
  33295. QuarticEase.prototype.easeInCore = function (gradient) {
  33296. return (gradient * gradient * gradient * gradient);
  33297. };
  33298. return QuarticEase;
  33299. }(EasingFunction));
  33300. BABYLON.QuarticEase = QuarticEase;
  33301. var QuinticEase = (function (_super) {
  33302. __extends(QuinticEase, _super);
  33303. function QuinticEase() {
  33304. return _super !== null && _super.apply(this, arguments) || this;
  33305. }
  33306. QuinticEase.prototype.easeInCore = function (gradient) {
  33307. return (gradient * gradient * gradient * gradient * gradient);
  33308. };
  33309. return QuinticEase;
  33310. }(EasingFunction));
  33311. BABYLON.QuinticEase = QuinticEase;
  33312. var SineEase = (function (_super) {
  33313. __extends(SineEase, _super);
  33314. function SineEase() {
  33315. return _super !== null && _super.apply(this, arguments) || this;
  33316. }
  33317. SineEase.prototype.easeInCore = function (gradient) {
  33318. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  33319. };
  33320. return SineEase;
  33321. }(EasingFunction));
  33322. BABYLON.SineEase = SineEase;
  33323. var BezierCurveEase = (function (_super) {
  33324. __extends(BezierCurveEase, _super);
  33325. function BezierCurveEase(x1, y1, x2, y2) {
  33326. if (x1 === void 0) { x1 = 0; }
  33327. if (y1 === void 0) { y1 = 0; }
  33328. if (x2 === void 0) { x2 = 1; }
  33329. if (y2 === void 0) { y2 = 1; }
  33330. var _this = _super.call(this) || this;
  33331. _this.x1 = x1;
  33332. _this.y1 = y1;
  33333. _this.x2 = x2;
  33334. _this.y2 = y2;
  33335. return _this;
  33336. }
  33337. BezierCurveEase.prototype.easeInCore = function (gradient) {
  33338. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  33339. };
  33340. return BezierCurveEase;
  33341. }(EasingFunction));
  33342. BABYLON.BezierCurveEase = BezierCurveEase;
  33343. })(BABYLON || (BABYLON = {}));
  33344. //# sourceMappingURL=babylon.easing.js.map
  33345. var BABYLON;
  33346. (function (BABYLON) {
  33347. var Condition = (function () {
  33348. function Condition(actionManager) {
  33349. this._actionManager = actionManager;
  33350. }
  33351. Condition.prototype.isValid = function () {
  33352. return true;
  33353. };
  33354. Condition.prototype._getProperty = function (propertyPath) {
  33355. return this._actionManager._getProperty(propertyPath);
  33356. };
  33357. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  33358. return this._actionManager._getEffectiveTarget(target, propertyPath);
  33359. };
  33360. Condition.prototype.serialize = function () {
  33361. };
  33362. Condition.prototype._serialize = function (serializedCondition) {
  33363. return {
  33364. type: 2,
  33365. children: [],
  33366. name: serializedCondition.name,
  33367. properties: serializedCondition.properties
  33368. };
  33369. };
  33370. return Condition;
  33371. }());
  33372. BABYLON.Condition = Condition;
  33373. var ValueCondition = (function (_super) {
  33374. __extends(ValueCondition, _super);
  33375. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  33376. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  33377. var _this = _super.call(this, actionManager) || this;
  33378. _this.propertyPath = propertyPath;
  33379. _this.value = value;
  33380. _this.operator = operator;
  33381. _this._target = target;
  33382. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  33383. _this._property = _this._getProperty(_this.propertyPath);
  33384. return _this;
  33385. }
  33386. Object.defineProperty(ValueCondition, "IsEqual", {
  33387. get: function () {
  33388. return ValueCondition._IsEqual;
  33389. },
  33390. enumerable: true,
  33391. configurable: true
  33392. });
  33393. Object.defineProperty(ValueCondition, "IsDifferent", {
  33394. get: function () {
  33395. return ValueCondition._IsDifferent;
  33396. },
  33397. enumerable: true,
  33398. configurable: true
  33399. });
  33400. Object.defineProperty(ValueCondition, "IsGreater", {
  33401. get: function () {
  33402. return ValueCondition._IsGreater;
  33403. },
  33404. enumerable: true,
  33405. configurable: true
  33406. });
  33407. Object.defineProperty(ValueCondition, "IsLesser", {
  33408. get: function () {
  33409. return ValueCondition._IsLesser;
  33410. },
  33411. enumerable: true,
  33412. configurable: true
  33413. });
  33414. // Methods
  33415. ValueCondition.prototype.isValid = function () {
  33416. switch (this.operator) {
  33417. case ValueCondition.IsGreater:
  33418. return this._effectiveTarget[this._property] > this.value;
  33419. case ValueCondition.IsLesser:
  33420. return this._effectiveTarget[this._property] < this.value;
  33421. case ValueCondition.IsEqual:
  33422. case ValueCondition.IsDifferent:
  33423. var check;
  33424. if (this.value.equals) {
  33425. check = this.value.equals(this._effectiveTarget[this._property]);
  33426. }
  33427. else {
  33428. check = this.value === this._effectiveTarget[this._property];
  33429. }
  33430. return this.operator === ValueCondition.IsEqual ? check : !check;
  33431. }
  33432. return false;
  33433. };
  33434. ValueCondition.prototype.serialize = function () {
  33435. return this._serialize({
  33436. name: "ValueCondition",
  33437. properties: [
  33438. BABYLON.Action._GetTargetProperty(this._target),
  33439. { name: "propertyPath", value: this.propertyPath },
  33440. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  33441. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  33442. ]
  33443. });
  33444. };
  33445. ValueCondition.GetOperatorName = function (operator) {
  33446. switch (operator) {
  33447. case ValueCondition._IsEqual: return "IsEqual";
  33448. case ValueCondition._IsDifferent: return "IsDifferent";
  33449. case ValueCondition._IsGreater: return "IsGreater";
  33450. case ValueCondition._IsLesser: return "IsLesser";
  33451. default: return "";
  33452. }
  33453. };
  33454. return ValueCondition;
  33455. }(Condition));
  33456. // Statics
  33457. ValueCondition._IsEqual = 0;
  33458. ValueCondition._IsDifferent = 1;
  33459. ValueCondition._IsGreater = 2;
  33460. ValueCondition._IsLesser = 3;
  33461. BABYLON.ValueCondition = ValueCondition;
  33462. var PredicateCondition = (function (_super) {
  33463. __extends(PredicateCondition, _super);
  33464. function PredicateCondition(actionManager, predicate) {
  33465. var _this = _super.call(this, actionManager) || this;
  33466. _this.predicate = predicate;
  33467. return _this;
  33468. }
  33469. PredicateCondition.prototype.isValid = function () {
  33470. return this.predicate();
  33471. };
  33472. return PredicateCondition;
  33473. }(Condition));
  33474. BABYLON.PredicateCondition = PredicateCondition;
  33475. var StateCondition = (function (_super) {
  33476. __extends(StateCondition, _super);
  33477. function StateCondition(actionManager, target, value) {
  33478. var _this = _super.call(this, actionManager) || this;
  33479. _this.value = value;
  33480. _this._target = target;
  33481. return _this;
  33482. }
  33483. // Methods
  33484. StateCondition.prototype.isValid = function () {
  33485. return this._target.state === this.value;
  33486. };
  33487. StateCondition.prototype.serialize = function () {
  33488. return this._serialize({
  33489. name: "StateCondition",
  33490. properties: [
  33491. BABYLON.Action._GetTargetProperty(this._target),
  33492. { name: "value", value: this.value }
  33493. ]
  33494. });
  33495. };
  33496. return StateCondition;
  33497. }(Condition));
  33498. BABYLON.StateCondition = StateCondition;
  33499. })(BABYLON || (BABYLON = {}));
  33500. //# sourceMappingURL=babylon.condition.js.map
  33501. var BABYLON;
  33502. (function (BABYLON) {
  33503. var Action = (function () {
  33504. function Action(triggerOptions, condition) {
  33505. this.triggerOptions = triggerOptions;
  33506. if (triggerOptions.parameter) {
  33507. this.trigger = triggerOptions.trigger;
  33508. this._triggerParameter = triggerOptions.parameter;
  33509. }
  33510. else {
  33511. this.trigger = triggerOptions;
  33512. }
  33513. this._nextActiveAction = this;
  33514. this._condition = condition;
  33515. }
  33516. // Methods
  33517. Action.prototype._prepare = function () {
  33518. };
  33519. Action.prototype.getTriggerParameter = function () {
  33520. return this._triggerParameter;
  33521. };
  33522. Action.prototype._executeCurrent = function (evt) {
  33523. if (this._nextActiveAction._condition) {
  33524. var condition = this._nextActiveAction._condition;
  33525. var currentRenderId = this._actionManager.getScene().getRenderId();
  33526. // We cache the current evaluation for the current frame
  33527. if (condition._evaluationId === currentRenderId) {
  33528. if (!condition._currentResult) {
  33529. return;
  33530. }
  33531. }
  33532. else {
  33533. condition._evaluationId = currentRenderId;
  33534. if (!condition.isValid()) {
  33535. condition._currentResult = false;
  33536. return;
  33537. }
  33538. condition._currentResult = true;
  33539. }
  33540. }
  33541. this._nextActiveAction.execute(evt);
  33542. this.skipToNextActiveAction();
  33543. };
  33544. Action.prototype.execute = function (evt) {
  33545. };
  33546. Action.prototype.skipToNextActiveAction = function () {
  33547. if (this._nextActiveAction._child) {
  33548. if (!this._nextActiveAction._child._actionManager) {
  33549. this._nextActiveAction._child._actionManager = this._actionManager;
  33550. }
  33551. this._nextActiveAction = this._nextActiveAction._child;
  33552. }
  33553. else {
  33554. this._nextActiveAction = this;
  33555. }
  33556. };
  33557. Action.prototype.then = function (action) {
  33558. this._child = action;
  33559. action._actionManager = this._actionManager;
  33560. action._prepare();
  33561. return action;
  33562. };
  33563. Action.prototype._getProperty = function (propertyPath) {
  33564. return this._actionManager._getProperty(propertyPath);
  33565. };
  33566. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  33567. return this._actionManager._getEffectiveTarget(target, propertyPath);
  33568. };
  33569. Action.prototype.serialize = function (parent) {
  33570. };
  33571. // Called by BABYLON.Action objects in serialize(...). Internal use
  33572. Action.prototype._serialize = function (serializedAction, parent) {
  33573. var serializationObject = {
  33574. type: 1,
  33575. children: [],
  33576. name: serializedAction.name,
  33577. properties: serializedAction.properties || []
  33578. };
  33579. // Serialize child
  33580. if (this._child) {
  33581. this._child.serialize(serializationObject);
  33582. }
  33583. // Check if "this" has a condition
  33584. if (this._condition) {
  33585. var serializedCondition = this._condition.serialize();
  33586. serializedCondition.children.push(serializationObject);
  33587. if (parent) {
  33588. parent.children.push(serializedCondition);
  33589. }
  33590. return serializedCondition;
  33591. }
  33592. if (parent) {
  33593. parent.children.push(serializationObject);
  33594. }
  33595. return serializationObject;
  33596. };
  33597. return Action;
  33598. }());
  33599. Action._SerializeValueAsString = function (value) {
  33600. if (typeof value === "number") {
  33601. return value.toString();
  33602. }
  33603. if (typeof value === "boolean") {
  33604. return value ? "true" : "false";
  33605. }
  33606. if (value instanceof BABYLON.Vector2) {
  33607. return value.x + ", " + value.y;
  33608. }
  33609. if (value instanceof BABYLON.Vector3) {
  33610. return value.x + ", " + value.y + ", " + value.z;
  33611. }
  33612. if (value instanceof BABYLON.Color3) {
  33613. return value.r + ", " + value.g + ", " + value.b;
  33614. }
  33615. if (value instanceof BABYLON.Color4) {
  33616. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  33617. }
  33618. return value; // string
  33619. };
  33620. Action._GetTargetProperty = function (target) {
  33621. return {
  33622. name: "target",
  33623. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  33624. : target instanceof BABYLON.Light ? "LightProperties"
  33625. : target instanceof BABYLON.Camera ? "CameraProperties"
  33626. : "SceneProperties",
  33627. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  33628. };
  33629. };
  33630. BABYLON.Action = Action;
  33631. })(BABYLON || (BABYLON = {}));
  33632. //# sourceMappingURL=babylon.action.js.map
  33633. var BABYLON;
  33634. (function (BABYLON) {
  33635. /**
  33636. * ActionEvent is the event beint sent when an action is triggered.
  33637. */
  33638. var ActionEvent = (function () {
  33639. /**
  33640. * @constructor
  33641. * @param source The mesh or sprite that triggered the action.
  33642. * @param pointerX The X mouse cursor position at the time of the event
  33643. * @param pointerY The Y mouse cursor position at the time of the event
  33644. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  33645. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  33646. */
  33647. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  33648. this.source = source;
  33649. this.pointerX = pointerX;
  33650. this.pointerY = pointerY;
  33651. this.meshUnderPointer = meshUnderPointer;
  33652. this.sourceEvent = sourceEvent;
  33653. this.additionalData = additionalData;
  33654. }
  33655. /**
  33656. * Helper function to auto-create an ActionEvent from a source mesh.
  33657. * @param source The source mesh that triggered the event
  33658. * @param evt {Event} The original (browser) event
  33659. */
  33660. ActionEvent.CreateNew = function (source, evt, additionalData) {
  33661. var scene = source.getScene();
  33662. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  33663. };
  33664. /**
  33665. * Helper function to auto-create an ActionEvent from a source mesh.
  33666. * @param source The source sprite that triggered the event
  33667. * @param scene Scene associated with the sprite
  33668. * @param evt {Event} The original (browser) event
  33669. */
  33670. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  33671. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  33672. };
  33673. /**
  33674. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  33675. * @param scene the scene where the event occurred
  33676. * @param evt {Event} The original (browser) event
  33677. */
  33678. ActionEvent.CreateNewFromScene = function (scene, evt) {
  33679. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  33680. };
  33681. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  33682. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  33683. };
  33684. return ActionEvent;
  33685. }());
  33686. BABYLON.ActionEvent = ActionEvent;
  33687. /**
  33688. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  33689. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  33690. */
  33691. var ActionManager = (function () {
  33692. function ActionManager(scene) {
  33693. // Members
  33694. this.actions = new Array();
  33695. this.hoverCursor = '';
  33696. this._scene = scene;
  33697. scene._actionManagers.push(this);
  33698. }
  33699. Object.defineProperty(ActionManager, "NothingTrigger", {
  33700. get: function () {
  33701. return ActionManager._NothingTrigger;
  33702. },
  33703. enumerable: true,
  33704. configurable: true
  33705. });
  33706. Object.defineProperty(ActionManager, "OnPickTrigger", {
  33707. get: function () {
  33708. return ActionManager._OnPickTrigger;
  33709. },
  33710. enumerable: true,
  33711. configurable: true
  33712. });
  33713. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  33714. get: function () {
  33715. return ActionManager._OnLeftPickTrigger;
  33716. },
  33717. enumerable: true,
  33718. configurable: true
  33719. });
  33720. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  33721. get: function () {
  33722. return ActionManager._OnRightPickTrigger;
  33723. },
  33724. enumerable: true,
  33725. configurable: true
  33726. });
  33727. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  33728. get: function () {
  33729. return ActionManager._OnCenterPickTrigger;
  33730. },
  33731. enumerable: true,
  33732. configurable: true
  33733. });
  33734. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  33735. get: function () {
  33736. return ActionManager._OnPickDownTrigger;
  33737. },
  33738. enumerable: true,
  33739. configurable: true
  33740. });
  33741. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  33742. get: function () {
  33743. return ActionManager._OnDoublePickTrigger;
  33744. },
  33745. enumerable: true,
  33746. configurable: true
  33747. });
  33748. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  33749. get: function () {
  33750. return ActionManager._OnPickUpTrigger;
  33751. },
  33752. enumerable: true,
  33753. configurable: true
  33754. });
  33755. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  33756. /// This trigger will only be raised if you also declared a OnPickDown
  33757. get: function () {
  33758. return ActionManager._OnPickOutTrigger;
  33759. },
  33760. enumerable: true,
  33761. configurable: true
  33762. });
  33763. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  33764. get: function () {
  33765. return ActionManager._OnLongPressTrigger;
  33766. },
  33767. enumerable: true,
  33768. configurable: true
  33769. });
  33770. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  33771. get: function () {
  33772. return ActionManager._OnPointerOverTrigger;
  33773. },
  33774. enumerable: true,
  33775. configurable: true
  33776. });
  33777. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  33778. get: function () {
  33779. return ActionManager._OnPointerOutTrigger;
  33780. },
  33781. enumerable: true,
  33782. configurable: true
  33783. });
  33784. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  33785. get: function () {
  33786. return ActionManager._OnEveryFrameTrigger;
  33787. },
  33788. enumerable: true,
  33789. configurable: true
  33790. });
  33791. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  33792. get: function () {
  33793. return ActionManager._OnIntersectionEnterTrigger;
  33794. },
  33795. enumerable: true,
  33796. configurable: true
  33797. });
  33798. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  33799. get: function () {
  33800. return ActionManager._OnIntersectionExitTrigger;
  33801. },
  33802. enumerable: true,
  33803. configurable: true
  33804. });
  33805. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  33806. get: function () {
  33807. return ActionManager._OnKeyDownTrigger;
  33808. },
  33809. enumerable: true,
  33810. configurable: true
  33811. });
  33812. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  33813. get: function () {
  33814. return ActionManager._OnKeyUpTrigger;
  33815. },
  33816. enumerable: true,
  33817. configurable: true
  33818. });
  33819. // Methods
  33820. ActionManager.prototype.dispose = function () {
  33821. var index = this._scene._actionManagers.indexOf(this);
  33822. for (var i = 0; i < this.actions.length; i++) {
  33823. var action = this.actions[i];
  33824. ActionManager.Triggers[action.trigger]--;
  33825. if (ActionManager.Triggers[action.trigger] === 0) {
  33826. delete ActionManager.Triggers[action.trigger];
  33827. }
  33828. }
  33829. if (index > -1) {
  33830. this._scene._actionManagers.splice(index, 1);
  33831. }
  33832. };
  33833. ActionManager.prototype.getScene = function () {
  33834. return this._scene;
  33835. };
  33836. /**
  33837. * Does this action manager handles actions of any of the given triggers
  33838. * @param {number[]} triggers - the triggers to be tested
  33839. * @return {boolean} whether one (or more) of the triggers is handeled
  33840. */
  33841. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  33842. for (var index = 0; index < this.actions.length; index++) {
  33843. var action = this.actions[index];
  33844. if (triggers.indexOf(action.trigger) > -1) {
  33845. return true;
  33846. }
  33847. }
  33848. return false;
  33849. };
  33850. /**
  33851. * Does this action manager handles actions of a given trigger
  33852. * @param {number} trigger - the trigger to be tested
  33853. * @return {boolean} whether the trigger is handeled
  33854. */
  33855. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  33856. for (var index = 0; index < this.actions.length; index++) {
  33857. var action = this.actions[index];
  33858. if (action.trigger === trigger) {
  33859. return true;
  33860. }
  33861. }
  33862. return false;
  33863. };
  33864. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  33865. /**
  33866. * Does this action manager has pointer triggers
  33867. * @return {boolean} whether or not it has pointer triggers
  33868. */
  33869. get: function () {
  33870. for (var index = 0; index < this.actions.length; index++) {
  33871. var action = this.actions[index];
  33872. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  33873. return true;
  33874. }
  33875. }
  33876. return false;
  33877. },
  33878. enumerable: true,
  33879. configurable: true
  33880. });
  33881. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  33882. /**
  33883. * Does this action manager has pick triggers
  33884. * @return {boolean} whether or not it has pick triggers
  33885. */
  33886. get: function () {
  33887. for (var index = 0; index < this.actions.length; index++) {
  33888. var action = this.actions[index];
  33889. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  33890. return true;
  33891. }
  33892. }
  33893. return false;
  33894. },
  33895. enumerable: true,
  33896. configurable: true
  33897. });
  33898. Object.defineProperty(ActionManager, "HasTriggers", {
  33899. /**
  33900. * Does exist one action manager with at least one trigger
  33901. * @return {boolean} whether or not it exists one action manager with one trigger
  33902. **/
  33903. get: function () {
  33904. for (var t in ActionManager.Triggers) {
  33905. if (ActionManager.Triggers.hasOwnProperty(t)) {
  33906. return true;
  33907. }
  33908. }
  33909. return false;
  33910. },
  33911. enumerable: true,
  33912. configurable: true
  33913. });
  33914. Object.defineProperty(ActionManager, "HasPickTriggers", {
  33915. /**
  33916. * Does exist one action manager with at least one pick trigger
  33917. * @return {boolean} whether or not it exists one action manager with one pick trigger
  33918. **/
  33919. get: function () {
  33920. for (var t in ActionManager.Triggers) {
  33921. if (ActionManager.Triggers.hasOwnProperty(t)) {
  33922. var t_int = parseInt(t);
  33923. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  33924. return true;
  33925. }
  33926. }
  33927. }
  33928. return false;
  33929. },
  33930. enumerable: true,
  33931. configurable: true
  33932. });
  33933. /**
  33934. * Does exist one action manager that handles actions of a given trigger
  33935. * @param {number} trigger - the trigger to be tested
  33936. * @return {boolean} whether the trigger is handeled by at least one action manager
  33937. **/
  33938. ActionManager.HasSpecificTrigger = function (trigger) {
  33939. for (var t in ActionManager.Triggers) {
  33940. if (ActionManager.Triggers.hasOwnProperty(t)) {
  33941. var t_int = parseInt(t);
  33942. if (t_int === trigger) {
  33943. return true;
  33944. }
  33945. }
  33946. }
  33947. return false;
  33948. };
  33949. /**
  33950. * Registers an action to this action manager
  33951. * @param {BABYLON.Action} action - the action to be registered
  33952. * @return {BABYLON.Action} the action amended (prepared) after registration
  33953. */
  33954. ActionManager.prototype.registerAction = function (action) {
  33955. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  33956. if (this.getScene().actionManager !== this) {
  33957. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  33958. return null;
  33959. }
  33960. }
  33961. this.actions.push(action);
  33962. if (ActionManager.Triggers[action.trigger]) {
  33963. ActionManager.Triggers[action.trigger]++;
  33964. }
  33965. else {
  33966. ActionManager.Triggers[action.trigger] = 1;
  33967. }
  33968. action._actionManager = this;
  33969. action._prepare();
  33970. return action;
  33971. };
  33972. /**
  33973. * Process a specific trigger
  33974. * @param {number} trigger - the trigger to process
  33975. * @param evt {BABYLON.ActionEvent} the event details to be processed
  33976. */
  33977. ActionManager.prototype.processTrigger = function (trigger, evt) {
  33978. for (var index = 0; index < this.actions.length; index++) {
  33979. var action = this.actions[index];
  33980. if (action.trigger === trigger) {
  33981. if (trigger === ActionManager.OnKeyUpTrigger
  33982. || trigger === ActionManager.OnKeyDownTrigger) {
  33983. var parameter = action.getTriggerParameter();
  33984. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  33985. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  33986. var actualkey = String.fromCharCode(unicode).toLowerCase();
  33987. if (actualkey !== parameter.toLowerCase()) {
  33988. continue;
  33989. }
  33990. }
  33991. }
  33992. action._executeCurrent(evt);
  33993. }
  33994. }
  33995. };
  33996. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  33997. var properties = propertyPath.split(".");
  33998. for (var index = 0; index < properties.length - 1; index++) {
  33999. target = target[properties[index]];
  34000. }
  34001. return target;
  34002. };
  34003. ActionManager.prototype._getProperty = function (propertyPath) {
  34004. var properties = propertyPath.split(".");
  34005. return properties[properties.length - 1];
  34006. };
  34007. ActionManager.prototype.serialize = function (name) {
  34008. var root = {
  34009. children: [],
  34010. name: name,
  34011. type: 3,
  34012. properties: [] // Empty for root but required
  34013. };
  34014. for (var i = 0; i < this.actions.length; i++) {
  34015. var triggerObject = {
  34016. type: 0,
  34017. children: [],
  34018. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  34019. properties: []
  34020. };
  34021. var triggerOptions = this.actions[i].triggerOptions;
  34022. if (triggerOptions && typeof triggerOptions !== "number") {
  34023. if (triggerOptions.parameter instanceof BABYLON.Node) {
  34024. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  34025. }
  34026. else {
  34027. var parameter = {};
  34028. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  34029. if (triggerOptions.parameter.mesh) {
  34030. parameter._meshId = triggerOptions.parameter.mesh.id;
  34031. }
  34032. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  34033. }
  34034. }
  34035. // Serialize child action, recursively
  34036. this.actions[i].serialize(triggerObject);
  34037. // Add serialized trigger
  34038. root.children.push(triggerObject);
  34039. }
  34040. return root;
  34041. };
  34042. ActionManager.Parse = function (parsedActions, object, scene) {
  34043. var actionManager = new BABYLON.ActionManager(scene);
  34044. if (object === null)
  34045. scene.actionManager = actionManager;
  34046. else
  34047. object.actionManager = actionManager;
  34048. // instanciate a new object
  34049. var instanciate = function (name, params) {
  34050. var newInstance = Object.create(BABYLON[name].prototype);
  34051. newInstance.constructor.apply(newInstance, params);
  34052. return newInstance;
  34053. };
  34054. var parseParameter = function (name, value, target, propertyPath) {
  34055. if (propertyPath === null) {
  34056. // String, boolean or float
  34057. var floatValue = parseFloat(value);
  34058. if (value === "true" || value === "false")
  34059. return value === "true";
  34060. else
  34061. return isNaN(floatValue) ? value : floatValue;
  34062. }
  34063. var effectiveTarget = propertyPath.split(".");
  34064. var values = value.split(",");
  34065. // Get effective Target
  34066. for (var i = 0; i < effectiveTarget.length; i++) {
  34067. target = target[effectiveTarget[i]];
  34068. }
  34069. // Return appropriate value with its type
  34070. if (typeof (target) === "boolean")
  34071. return values[0] === "true";
  34072. if (typeof (target) === "string")
  34073. return values[0];
  34074. // Parameters with multiple values such as Vector3 etc.
  34075. var split = new Array();
  34076. for (var i = 0; i < values.length; i++)
  34077. split.push(parseFloat(values[i]));
  34078. if (target instanceof BABYLON.Vector3)
  34079. return BABYLON.Vector3.FromArray(split);
  34080. if (target instanceof BABYLON.Vector4)
  34081. return BABYLON.Vector4.FromArray(split);
  34082. if (target instanceof BABYLON.Color3)
  34083. return BABYLON.Color3.FromArray(split);
  34084. if (target instanceof BABYLON.Color4)
  34085. return BABYLON.Color4.FromArray(split);
  34086. return parseFloat(values[0]);
  34087. };
  34088. // traverse graph per trigger
  34089. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  34090. if (combineArray === void 0) { combineArray = null; }
  34091. if (parsedAction.detached)
  34092. return;
  34093. var parameters = new Array();
  34094. var target = null;
  34095. var propertyPath = null;
  34096. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  34097. // Parameters
  34098. if (parsedAction.type === 2)
  34099. parameters.push(actionManager);
  34100. else
  34101. parameters.push(trigger);
  34102. if (combine) {
  34103. var actions = new Array();
  34104. for (var j = 0; j < parsedAction.combine.length; j++) {
  34105. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  34106. }
  34107. parameters.push(actions);
  34108. }
  34109. else {
  34110. for (var i = 0; i < parsedAction.properties.length; i++) {
  34111. var value = parsedAction.properties[i].value;
  34112. var name = parsedAction.properties[i].name;
  34113. var targetType = parsedAction.properties[i].targetType;
  34114. if (name === "target")
  34115. if (targetType !== null && targetType === "SceneProperties")
  34116. value = target = scene;
  34117. else
  34118. value = target = scene.getNodeByName(value);
  34119. else if (name === "parent")
  34120. value = scene.getNodeByName(value);
  34121. else if (name === "sound")
  34122. value = scene.getSoundByName(value);
  34123. else if (name !== "propertyPath") {
  34124. if (parsedAction.type === 2 && name === "operator")
  34125. value = BABYLON.ValueCondition[value];
  34126. else
  34127. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  34128. }
  34129. else {
  34130. propertyPath = value;
  34131. }
  34132. parameters.push(value);
  34133. }
  34134. }
  34135. if (combineArray === null) {
  34136. parameters.push(condition);
  34137. }
  34138. else {
  34139. parameters.push(null);
  34140. }
  34141. // If interpolate value action
  34142. if (parsedAction.name === "InterpolateValueAction") {
  34143. var param = parameters[parameters.length - 2];
  34144. parameters[parameters.length - 1] = param;
  34145. parameters[parameters.length - 2] = condition;
  34146. }
  34147. // Action or condition(s) and not CombineAction
  34148. var newAction = instanciate(parsedAction.name, parameters);
  34149. if (newAction instanceof BABYLON.Condition && condition !== null) {
  34150. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  34151. if (action)
  34152. action.then(nothing);
  34153. else
  34154. actionManager.registerAction(nothing);
  34155. action = nothing;
  34156. }
  34157. if (combineArray === null) {
  34158. if (newAction instanceof BABYLON.Condition) {
  34159. condition = newAction;
  34160. newAction = action;
  34161. }
  34162. else {
  34163. condition = null;
  34164. if (action)
  34165. action.then(newAction);
  34166. else
  34167. actionManager.registerAction(newAction);
  34168. }
  34169. }
  34170. else {
  34171. combineArray.push(newAction);
  34172. }
  34173. for (var i = 0; i < parsedAction.children.length; i++)
  34174. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  34175. };
  34176. // triggers
  34177. for (var i = 0; i < parsedActions.children.length; i++) {
  34178. var triggerParams;
  34179. var trigger = parsedActions.children[i];
  34180. if (trigger.properties.length > 0) {
  34181. var param = trigger.properties[0].value;
  34182. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  34183. if (value._meshId) {
  34184. value.mesh = scene.getMeshByID(value._meshId);
  34185. }
  34186. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  34187. }
  34188. else
  34189. triggerParams = BABYLON.ActionManager[trigger.name];
  34190. for (var j = 0; j < trigger.children.length; j++) {
  34191. if (!trigger.detached)
  34192. traverse(trigger.children[j], triggerParams, null, null);
  34193. }
  34194. }
  34195. };
  34196. ActionManager.GetTriggerName = function (trigger) {
  34197. switch (trigger) {
  34198. case 0: return "NothingTrigger";
  34199. case 1: return "OnPickTrigger";
  34200. case 2: return "OnLeftPickTrigger";
  34201. case 3: return "OnRightPickTrigger";
  34202. case 4: return "OnCenterPickTrigger";
  34203. case 5: return "OnPickDownTrigger";
  34204. case 6: return "OnPickUpTrigger";
  34205. case 7: return "OnLongPressTrigger";
  34206. case 8: return "OnPointerOverTrigger";
  34207. case 9: return "OnPointerOutTrigger";
  34208. case 10: return "OnEveryFrameTrigger";
  34209. case 11: return "OnIntersectionEnterTrigger";
  34210. case 12: return "OnIntersectionExitTrigger";
  34211. case 13: return "OnKeyDownTrigger";
  34212. case 14: return "OnKeyUpTrigger";
  34213. case 15: return "OnPickOutTrigger";
  34214. default: return "";
  34215. }
  34216. };
  34217. return ActionManager;
  34218. }());
  34219. // Statics
  34220. ActionManager._NothingTrigger = 0;
  34221. ActionManager._OnPickTrigger = 1;
  34222. ActionManager._OnLeftPickTrigger = 2;
  34223. ActionManager._OnRightPickTrigger = 3;
  34224. ActionManager._OnCenterPickTrigger = 4;
  34225. ActionManager._OnPickDownTrigger = 5;
  34226. ActionManager._OnDoublePickTrigger = 6;
  34227. ActionManager._OnPickUpTrigger = 7;
  34228. ActionManager._OnLongPressTrigger = 8;
  34229. ActionManager._OnPointerOverTrigger = 9;
  34230. ActionManager._OnPointerOutTrigger = 10;
  34231. ActionManager._OnEveryFrameTrigger = 11;
  34232. ActionManager._OnIntersectionEnterTrigger = 12;
  34233. ActionManager._OnIntersectionExitTrigger = 13;
  34234. ActionManager._OnKeyDownTrigger = 14;
  34235. ActionManager._OnKeyUpTrigger = 15;
  34236. ActionManager._OnPickOutTrigger = 16;
  34237. ActionManager.Triggers = {};
  34238. BABYLON.ActionManager = ActionManager;
  34239. })(BABYLON || (BABYLON = {}));
  34240. //# sourceMappingURL=babylon.actionManager.js.map
  34241. var BABYLON;
  34242. (function (BABYLON) {
  34243. var InterpolateValueAction = (function (_super) {
  34244. __extends(InterpolateValueAction, _super);
  34245. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  34246. if (duration === void 0) { duration = 1000; }
  34247. var _this = _super.call(this, triggerOptions, condition) || this;
  34248. _this.propertyPath = propertyPath;
  34249. _this.value = value;
  34250. _this.duration = duration;
  34251. _this.stopOtherAnimations = stopOtherAnimations;
  34252. _this.onInterpolationDone = onInterpolationDone;
  34253. _this._target = _this._effectiveTarget = target;
  34254. return _this;
  34255. }
  34256. InterpolateValueAction.prototype._prepare = function () {
  34257. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  34258. this._property = this._getProperty(this.propertyPath);
  34259. };
  34260. InterpolateValueAction.prototype.execute = function () {
  34261. var scene = this._actionManager.getScene();
  34262. var keys = [
  34263. {
  34264. frame: 0,
  34265. value: this._effectiveTarget[this._property]
  34266. }, {
  34267. frame: 100,
  34268. value: this.value
  34269. }
  34270. ];
  34271. var dataType;
  34272. if (typeof this.value === "number") {
  34273. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  34274. }
  34275. else if (this.value instanceof BABYLON.Color3) {
  34276. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  34277. }
  34278. else if (this.value instanceof BABYLON.Vector3) {
  34279. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  34280. }
  34281. else if (this.value instanceof BABYLON.Matrix) {
  34282. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  34283. }
  34284. else if (this.value instanceof BABYLON.Quaternion) {
  34285. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  34286. }
  34287. else {
  34288. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  34289. return;
  34290. }
  34291. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  34292. animation.setKeys(keys);
  34293. if (this.stopOtherAnimations) {
  34294. scene.stopAnimation(this._effectiveTarget);
  34295. }
  34296. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
  34297. };
  34298. InterpolateValueAction.prototype.serialize = function (parent) {
  34299. return _super.prototype._serialize.call(this, {
  34300. name: "InterpolateValueAction",
  34301. properties: [
  34302. BABYLON.Action._GetTargetProperty(this._target),
  34303. { name: "propertyPath", value: this.propertyPath },
  34304. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  34305. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  34306. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  34307. ]
  34308. }, parent);
  34309. };
  34310. return InterpolateValueAction;
  34311. }(BABYLON.Action));
  34312. BABYLON.InterpolateValueAction = InterpolateValueAction;
  34313. })(BABYLON || (BABYLON = {}));
  34314. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  34315. var BABYLON;
  34316. (function (BABYLON) {
  34317. var SwitchBooleanAction = (function (_super) {
  34318. __extends(SwitchBooleanAction, _super);
  34319. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  34320. var _this = _super.call(this, triggerOptions, condition) || this;
  34321. _this.propertyPath = propertyPath;
  34322. _this._target = _this._effectiveTarget = target;
  34323. return _this;
  34324. }
  34325. SwitchBooleanAction.prototype._prepare = function () {
  34326. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  34327. this._property = this._getProperty(this.propertyPath);
  34328. };
  34329. SwitchBooleanAction.prototype.execute = function () {
  34330. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  34331. };
  34332. SwitchBooleanAction.prototype.serialize = function (parent) {
  34333. return _super.prototype._serialize.call(this, {
  34334. name: "SwitchBooleanAction",
  34335. properties: [
  34336. BABYLON.Action._GetTargetProperty(this._target),
  34337. { name: "propertyPath", value: this.propertyPath }
  34338. ]
  34339. }, parent);
  34340. };
  34341. return SwitchBooleanAction;
  34342. }(BABYLON.Action));
  34343. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  34344. var SetStateAction = (function (_super) {
  34345. __extends(SetStateAction, _super);
  34346. function SetStateAction(triggerOptions, target, value, condition) {
  34347. var _this = _super.call(this, triggerOptions, condition) || this;
  34348. _this.value = value;
  34349. _this._target = target;
  34350. return _this;
  34351. }
  34352. SetStateAction.prototype.execute = function () {
  34353. this._target.state = this.value;
  34354. };
  34355. SetStateAction.prototype.serialize = function (parent) {
  34356. return _super.prototype._serialize.call(this, {
  34357. name: "SetStateAction",
  34358. properties: [
  34359. BABYLON.Action._GetTargetProperty(this._target),
  34360. { name: "value", value: this.value }
  34361. ]
  34362. }, parent);
  34363. };
  34364. return SetStateAction;
  34365. }(BABYLON.Action));
  34366. BABYLON.SetStateAction = SetStateAction;
  34367. var SetValueAction = (function (_super) {
  34368. __extends(SetValueAction, _super);
  34369. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  34370. var _this = _super.call(this, triggerOptions, condition) || this;
  34371. _this.propertyPath = propertyPath;
  34372. _this.value = value;
  34373. _this._target = _this._effectiveTarget = target;
  34374. return _this;
  34375. }
  34376. SetValueAction.prototype._prepare = function () {
  34377. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  34378. this._property = this._getProperty(this.propertyPath);
  34379. };
  34380. SetValueAction.prototype.execute = function () {
  34381. this._effectiveTarget[this._property] = this.value;
  34382. if (this._target.markAsDirty) {
  34383. this._target.markAsDirty(this._property);
  34384. }
  34385. };
  34386. SetValueAction.prototype.serialize = function (parent) {
  34387. return _super.prototype._serialize.call(this, {
  34388. name: "SetValueAction",
  34389. properties: [
  34390. BABYLON.Action._GetTargetProperty(this._target),
  34391. { name: "propertyPath", value: this.propertyPath },
  34392. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  34393. ]
  34394. }, parent);
  34395. };
  34396. return SetValueAction;
  34397. }(BABYLON.Action));
  34398. BABYLON.SetValueAction = SetValueAction;
  34399. var IncrementValueAction = (function (_super) {
  34400. __extends(IncrementValueAction, _super);
  34401. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  34402. var _this = _super.call(this, triggerOptions, condition) || this;
  34403. _this.propertyPath = propertyPath;
  34404. _this.value = value;
  34405. _this._target = _this._effectiveTarget = target;
  34406. return _this;
  34407. }
  34408. IncrementValueAction.prototype._prepare = function () {
  34409. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  34410. this._property = this._getProperty(this.propertyPath);
  34411. if (typeof this._effectiveTarget[this._property] !== "number") {
  34412. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  34413. }
  34414. };
  34415. IncrementValueAction.prototype.execute = function () {
  34416. this._effectiveTarget[this._property] += this.value;
  34417. if (this._target.markAsDirty) {
  34418. this._target.markAsDirty(this._property);
  34419. }
  34420. };
  34421. IncrementValueAction.prototype.serialize = function (parent) {
  34422. return _super.prototype._serialize.call(this, {
  34423. name: "IncrementValueAction",
  34424. properties: [
  34425. BABYLON.Action._GetTargetProperty(this._target),
  34426. { name: "propertyPath", value: this.propertyPath },
  34427. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  34428. ]
  34429. }, parent);
  34430. };
  34431. return IncrementValueAction;
  34432. }(BABYLON.Action));
  34433. BABYLON.IncrementValueAction = IncrementValueAction;
  34434. var PlayAnimationAction = (function (_super) {
  34435. __extends(PlayAnimationAction, _super);
  34436. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  34437. var _this = _super.call(this, triggerOptions, condition) || this;
  34438. _this.from = from;
  34439. _this.to = to;
  34440. _this.loop = loop;
  34441. _this._target = target;
  34442. return _this;
  34443. }
  34444. PlayAnimationAction.prototype._prepare = function () {
  34445. };
  34446. PlayAnimationAction.prototype.execute = function () {
  34447. var scene = this._actionManager.getScene();
  34448. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  34449. };
  34450. PlayAnimationAction.prototype.serialize = function (parent) {
  34451. return _super.prototype._serialize.call(this, {
  34452. name: "PlayAnimationAction",
  34453. properties: [
  34454. BABYLON.Action._GetTargetProperty(this._target),
  34455. { name: "from", value: String(this.from) },
  34456. { name: "to", value: String(this.to) },
  34457. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  34458. ]
  34459. }, parent);
  34460. };
  34461. return PlayAnimationAction;
  34462. }(BABYLON.Action));
  34463. BABYLON.PlayAnimationAction = PlayAnimationAction;
  34464. var StopAnimationAction = (function (_super) {
  34465. __extends(StopAnimationAction, _super);
  34466. function StopAnimationAction(triggerOptions, target, condition) {
  34467. var _this = _super.call(this, triggerOptions, condition) || this;
  34468. _this._target = target;
  34469. return _this;
  34470. }
  34471. StopAnimationAction.prototype._prepare = function () {
  34472. };
  34473. StopAnimationAction.prototype.execute = function () {
  34474. var scene = this._actionManager.getScene();
  34475. scene.stopAnimation(this._target);
  34476. };
  34477. StopAnimationAction.prototype.serialize = function (parent) {
  34478. return _super.prototype._serialize.call(this, {
  34479. name: "StopAnimationAction",
  34480. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  34481. }, parent);
  34482. };
  34483. return StopAnimationAction;
  34484. }(BABYLON.Action));
  34485. BABYLON.StopAnimationAction = StopAnimationAction;
  34486. var DoNothingAction = (function (_super) {
  34487. __extends(DoNothingAction, _super);
  34488. function DoNothingAction(triggerOptions, condition) {
  34489. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  34490. return _super.call(this, triggerOptions, condition) || this;
  34491. }
  34492. DoNothingAction.prototype.execute = function () {
  34493. };
  34494. DoNothingAction.prototype.serialize = function (parent) {
  34495. return _super.prototype._serialize.call(this, {
  34496. name: "DoNothingAction",
  34497. properties: []
  34498. }, parent);
  34499. };
  34500. return DoNothingAction;
  34501. }(BABYLON.Action));
  34502. BABYLON.DoNothingAction = DoNothingAction;
  34503. var CombineAction = (function (_super) {
  34504. __extends(CombineAction, _super);
  34505. function CombineAction(triggerOptions, children, condition) {
  34506. var _this = _super.call(this, triggerOptions, condition) || this;
  34507. _this.children = children;
  34508. return _this;
  34509. }
  34510. CombineAction.prototype._prepare = function () {
  34511. for (var index = 0; index < this.children.length; index++) {
  34512. this.children[index]._actionManager = this._actionManager;
  34513. this.children[index]._prepare();
  34514. }
  34515. };
  34516. CombineAction.prototype.execute = function (evt) {
  34517. for (var index = 0; index < this.children.length; index++) {
  34518. this.children[index].execute(evt);
  34519. }
  34520. };
  34521. CombineAction.prototype.serialize = function (parent) {
  34522. var serializationObject = _super.prototype._serialize.call(this, {
  34523. name: "CombineAction",
  34524. properties: [],
  34525. combine: []
  34526. }, parent);
  34527. for (var i = 0; i < this.children.length; i++) {
  34528. serializationObject.combine.push(this.children[i].serialize(null));
  34529. }
  34530. return serializationObject;
  34531. };
  34532. return CombineAction;
  34533. }(BABYLON.Action));
  34534. BABYLON.CombineAction = CombineAction;
  34535. var ExecuteCodeAction = (function (_super) {
  34536. __extends(ExecuteCodeAction, _super);
  34537. function ExecuteCodeAction(triggerOptions, func, condition) {
  34538. var _this = _super.call(this, triggerOptions, condition) || this;
  34539. _this.func = func;
  34540. return _this;
  34541. }
  34542. ExecuteCodeAction.prototype.execute = function (evt) {
  34543. this.func(evt);
  34544. };
  34545. return ExecuteCodeAction;
  34546. }(BABYLON.Action));
  34547. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  34548. var SetParentAction = (function (_super) {
  34549. __extends(SetParentAction, _super);
  34550. function SetParentAction(triggerOptions, target, parent, condition) {
  34551. var _this = _super.call(this, triggerOptions, condition) || this;
  34552. _this._target = target;
  34553. _this._parent = parent;
  34554. return _this;
  34555. }
  34556. SetParentAction.prototype._prepare = function () {
  34557. };
  34558. SetParentAction.prototype.execute = function () {
  34559. if (this._target.parent === this._parent) {
  34560. return;
  34561. }
  34562. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  34563. invertParentWorldMatrix.invert();
  34564. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  34565. this._target.parent = this._parent;
  34566. };
  34567. SetParentAction.prototype.serialize = function (parent) {
  34568. return _super.prototype._serialize.call(this, {
  34569. name: "SetParentAction",
  34570. properties: [
  34571. BABYLON.Action._GetTargetProperty(this._target),
  34572. BABYLON.Action._GetTargetProperty(this._parent),
  34573. ]
  34574. }, parent);
  34575. };
  34576. return SetParentAction;
  34577. }(BABYLON.Action));
  34578. BABYLON.SetParentAction = SetParentAction;
  34579. var PlaySoundAction = (function (_super) {
  34580. __extends(PlaySoundAction, _super);
  34581. function PlaySoundAction(triggerOptions, sound, condition) {
  34582. var _this = _super.call(this, triggerOptions, condition) || this;
  34583. _this._sound = sound;
  34584. return _this;
  34585. }
  34586. PlaySoundAction.prototype._prepare = function () {
  34587. };
  34588. PlaySoundAction.prototype.execute = function () {
  34589. if (this._sound !== undefined)
  34590. this._sound.play();
  34591. };
  34592. PlaySoundAction.prototype.serialize = function (parent) {
  34593. return _super.prototype._serialize.call(this, {
  34594. name: "PlaySoundAction",
  34595. properties: [{ name: "sound", value: this._sound.name }]
  34596. }, parent);
  34597. };
  34598. return PlaySoundAction;
  34599. }(BABYLON.Action));
  34600. BABYLON.PlaySoundAction = PlaySoundAction;
  34601. var StopSoundAction = (function (_super) {
  34602. __extends(StopSoundAction, _super);
  34603. function StopSoundAction(triggerOptions, sound, condition) {
  34604. var _this = _super.call(this, triggerOptions, condition) || this;
  34605. _this._sound = sound;
  34606. return _this;
  34607. }
  34608. StopSoundAction.prototype._prepare = function () {
  34609. };
  34610. StopSoundAction.prototype.execute = function () {
  34611. if (this._sound !== undefined)
  34612. this._sound.stop();
  34613. };
  34614. StopSoundAction.prototype.serialize = function (parent) {
  34615. return _super.prototype._serialize.call(this, {
  34616. name: "StopSoundAction",
  34617. properties: [{ name: "sound", value: this._sound.name }]
  34618. }, parent);
  34619. };
  34620. return StopSoundAction;
  34621. }(BABYLON.Action));
  34622. BABYLON.StopSoundAction = StopSoundAction;
  34623. })(BABYLON || (BABYLON = {}));
  34624. //# sourceMappingURL=babylon.directActions.js.map
  34625. var BABYLON;
  34626. (function (BABYLON) {
  34627. var SpriteManager = (function () {
  34628. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  34629. if (epsilon === void 0) { epsilon = 0.01; }
  34630. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  34631. this.name = name;
  34632. this.sprites = new Array();
  34633. this.renderingGroupId = 0;
  34634. this.layerMask = 0x0FFFFFFF;
  34635. this.fogEnabled = true;
  34636. this.isPickable = false;
  34637. /**
  34638. * An event triggered when the manager is disposed.
  34639. * @type {BABYLON.Observable}
  34640. */
  34641. this.onDisposeObservable = new BABYLON.Observable();
  34642. this._vertexBuffers = {};
  34643. this._capacity = capacity;
  34644. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  34645. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34646. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34647. if (cellSize.width && cellSize.height) {
  34648. this.cellWidth = cellSize.width;
  34649. this.cellHeight = cellSize.height;
  34650. }
  34651. else if (cellSize !== undefined) {
  34652. this.cellWidth = cellSize;
  34653. this.cellHeight = cellSize;
  34654. }
  34655. else {
  34656. return;
  34657. }
  34658. this._epsilon = epsilon;
  34659. this._scene = scene;
  34660. this._scene.spriteManagers.push(this);
  34661. var indices = [];
  34662. var index = 0;
  34663. for (var count = 0; count < capacity; count++) {
  34664. indices.push(index);
  34665. indices.push(index + 1);
  34666. indices.push(index + 2);
  34667. indices.push(index);
  34668. indices.push(index + 2);
  34669. indices.push(index + 3);
  34670. index += 4;
  34671. }
  34672. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  34673. // VBO
  34674. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  34675. this._vertexData = new Float32Array(capacity * 16 * 4);
  34676. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  34677. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  34678. var options = this._buffer.createVertexBuffer("options", 4, 4);
  34679. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  34680. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  34681. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  34682. this._vertexBuffers["options"] = options;
  34683. this._vertexBuffers["cellInfo"] = cellInfo;
  34684. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  34685. // Effects
  34686. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  34687. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  34688. }
  34689. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  34690. set: function (callback) {
  34691. if (this._onDisposeObserver) {
  34692. this.onDisposeObservable.remove(this._onDisposeObserver);
  34693. }
  34694. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  34695. },
  34696. enumerable: true,
  34697. configurable: true
  34698. });
  34699. Object.defineProperty(SpriteManager.prototype, "texture", {
  34700. get: function () {
  34701. return this._spriteTexture;
  34702. },
  34703. set: function (value) {
  34704. this._spriteTexture = value;
  34705. },
  34706. enumerable: true,
  34707. configurable: true
  34708. });
  34709. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  34710. var arrayOffset = index * 16;
  34711. if (offsetX === 0)
  34712. offsetX = this._epsilon;
  34713. else if (offsetX === 1)
  34714. offsetX = 1 - this._epsilon;
  34715. if (offsetY === 0)
  34716. offsetY = this._epsilon;
  34717. else if (offsetY === 1)
  34718. offsetY = 1 - this._epsilon;
  34719. this._vertexData[arrayOffset] = sprite.position.x;
  34720. this._vertexData[arrayOffset + 1] = sprite.position.y;
  34721. this._vertexData[arrayOffset + 2] = sprite.position.z;
  34722. this._vertexData[arrayOffset + 3] = sprite.angle;
  34723. this._vertexData[arrayOffset + 4] = sprite.width;
  34724. this._vertexData[arrayOffset + 5] = sprite.height;
  34725. this._vertexData[arrayOffset + 6] = offsetX;
  34726. this._vertexData[arrayOffset + 7] = offsetY;
  34727. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  34728. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  34729. var offset = (sprite.cellIndex / rowSize) >> 0;
  34730. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  34731. this._vertexData[arrayOffset + 11] = offset;
  34732. // Color
  34733. this._vertexData[arrayOffset + 12] = sprite.color.r;
  34734. this._vertexData[arrayOffset + 13] = sprite.color.g;
  34735. this._vertexData[arrayOffset + 14] = sprite.color.b;
  34736. this._vertexData[arrayOffset + 15] = sprite.color.a;
  34737. };
  34738. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  34739. var count = Math.min(this._capacity, this.sprites.length);
  34740. var min = BABYLON.Vector3.Zero();
  34741. var max = BABYLON.Vector3.Zero();
  34742. var distance = Number.MAX_VALUE;
  34743. var currentSprite;
  34744. var cameraSpacePosition = BABYLON.Vector3.Zero();
  34745. var cameraView = camera.getViewMatrix();
  34746. for (var index = 0; index < count; index++) {
  34747. var sprite = this.sprites[index];
  34748. if (!sprite) {
  34749. continue;
  34750. }
  34751. if (predicate) {
  34752. if (!predicate(sprite)) {
  34753. continue;
  34754. }
  34755. }
  34756. else if (!sprite.isPickable) {
  34757. continue;
  34758. }
  34759. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  34760. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  34761. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  34762. if (ray.intersectsBoxMinMax(min, max)) {
  34763. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  34764. if (distance > currentDistance) {
  34765. distance = currentDistance;
  34766. currentSprite = sprite;
  34767. if (fastCheck) {
  34768. break;
  34769. }
  34770. }
  34771. }
  34772. }
  34773. if (currentSprite) {
  34774. var result = new BABYLON.PickingInfo();
  34775. result.hit = true;
  34776. result.pickedSprite = currentSprite;
  34777. result.distance = distance;
  34778. return result;
  34779. }
  34780. return null;
  34781. };
  34782. SpriteManager.prototype.render = function () {
  34783. // Check
  34784. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  34785. return;
  34786. var engine = this._scene.getEngine();
  34787. var baseSize = this._spriteTexture.getBaseSize();
  34788. // Sprites
  34789. var deltaTime = engine.getDeltaTime();
  34790. var max = Math.min(this._capacity, this.sprites.length);
  34791. var rowSize = baseSize.width / this.cellWidth;
  34792. var offset = 0;
  34793. for (var index = 0; index < max; index++) {
  34794. var sprite = this.sprites[index];
  34795. if (!sprite) {
  34796. continue;
  34797. }
  34798. sprite._animate(deltaTime);
  34799. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  34800. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  34801. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  34802. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  34803. }
  34804. this._buffer.update(this._vertexData);
  34805. // Render
  34806. var effect = this._effectBase;
  34807. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  34808. effect = this._effectFog;
  34809. }
  34810. engine.enableEffect(effect);
  34811. var viewMatrix = this._scene.getViewMatrix();
  34812. effect.setTexture("diffuseSampler", this._spriteTexture);
  34813. effect.setMatrix("view", viewMatrix);
  34814. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  34815. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  34816. // Fog
  34817. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  34818. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  34819. effect.setColor3("vFogColor", this._scene.fogColor);
  34820. }
  34821. // VBOs
  34822. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  34823. // Draw order
  34824. engine.setDepthFunctionToLessOrEqual();
  34825. effect.setBool("alphaTest", true);
  34826. engine.setColorWrite(false);
  34827. engine.draw(true, 0, max * 6);
  34828. engine.setColorWrite(true);
  34829. effect.setBool("alphaTest", false);
  34830. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  34831. engine.draw(true, 0, max * 6);
  34832. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  34833. };
  34834. SpriteManager.prototype.dispose = function () {
  34835. if (this._buffer) {
  34836. this._buffer.dispose();
  34837. this._buffer = null;
  34838. }
  34839. if (this._indexBuffer) {
  34840. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  34841. this._indexBuffer = null;
  34842. }
  34843. if (this._spriteTexture) {
  34844. this._spriteTexture.dispose();
  34845. this._spriteTexture = null;
  34846. }
  34847. // Remove from scene
  34848. var index = this._scene.spriteManagers.indexOf(this);
  34849. this._scene.spriteManagers.splice(index, 1);
  34850. // Callback
  34851. this.onDisposeObservable.notifyObservers(this);
  34852. this.onDisposeObservable.clear();
  34853. };
  34854. return SpriteManager;
  34855. }());
  34856. BABYLON.SpriteManager = SpriteManager;
  34857. })(BABYLON || (BABYLON = {}));
  34858. //# sourceMappingURL=babylon.spriteManager.js.map
  34859. var BABYLON;
  34860. (function (BABYLON) {
  34861. var Sprite = (function () {
  34862. function Sprite(name, manager) {
  34863. this.name = name;
  34864. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  34865. this.width = 1.0;
  34866. this.height = 1.0;
  34867. this.angle = 0;
  34868. this.cellIndex = 0;
  34869. this.invertU = 0;
  34870. this.invertV = 0;
  34871. this.animations = new Array();
  34872. this.isPickable = false;
  34873. this._animationStarted = false;
  34874. this._loopAnimation = false;
  34875. this._fromIndex = 0;
  34876. this._toIndex = 0;
  34877. this._delay = 0;
  34878. this._direction = 1;
  34879. this._frameCount = 0;
  34880. this._time = 0;
  34881. this._manager = manager;
  34882. this._manager.sprites.push(this);
  34883. this.position = BABYLON.Vector3.Zero();
  34884. }
  34885. Object.defineProperty(Sprite.prototype, "size", {
  34886. get: function () {
  34887. return this.width;
  34888. },
  34889. set: function (value) {
  34890. this.width = value;
  34891. this.height = value;
  34892. },
  34893. enumerable: true,
  34894. configurable: true
  34895. });
  34896. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  34897. this._fromIndex = from;
  34898. this._toIndex = to;
  34899. this._loopAnimation = loop;
  34900. this._delay = delay;
  34901. this._animationStarted = true;
  34902. this._direction = from < to ? 1 : -1;
  34903. this.cellIndex = from;
  34904. this._time = 0;
  34905. this._onAnimationEnd = onAnimationEnd;
  34906. };
  34907. Sprite.prototype.stopAnimation = function () {
  34908. this._animationStarted = false;
  34909. };
  34910. Sprite.prototype._animate = function (deltaTime) {
  34911. if (!this._animationStarted)
  34912. return;
  34913. this._time += deltaTime;
  34914. if (this._time > this._delay) {
  34915. this._time = this._time % this._delay;
  34916. this.cellIndex += this._direction;
  34917. if (this.cellIndex === this._toIndex) {
  34918. if (this._loopAnimation) {
  34919. this.cellIndex = this._fromIndex;
  34920. }
  34921. else {
  34922. this._animationStarted = false;
  34923. if (this._onAnimationEnd) {
  34924. this._onAnimationEnd();
  34925. }
  34926. if (this.disposeWhenFinishedAnimating) {
  34927. this.dispose();
  34928. }
  34929. }
  34930. }
  34931. }
  34932. };
  34933. Sprite.prototype.dispose = function () {
  34934. for (var i = 0; i < this._manager.sprites.length; i++) {
  34935. if (this._manager.sprites[i] == this) {
  34936. this._manager.sprites.splice(i, 1);
  34937. }
  34938. }
  34939. };
  34940. return Sprite;
  34941. }());
  34942. BABYLON.Sprite = Sprite;
  34943. })(BABYLON || (BABYLON = {}));
  34944. //# sourceMappingURL=babylon.sprite.js.map
  34945. var BABYLON;
  34946. (function (BABYLON) {
  34947. var IntersectionInfo = (function () {
  34948. function IntersectionInfo(bu, bv, distance) {
  34949. this.bu = bu;
  34950. this.bv = bv;
  34951. this.distance = distance;
  34952. this.faceId = 0;
  34953. this.subMeshId = 0;
  34954. }
  34955. return IntersectionInfo;
  34956. }());
  34957. BABYLON.IntersectionInfo = IntersectionInfo;
  34958. var PickingInfo = (function () {
  34959. function PickingInfo() {
  34960. this.hit = false;
  34961. this.distance = 0;
  34962. this.pickedPoint = null;
  34963. this.pickedMesh = null;
  34964. this.bu = 0;
  34965. this.bv = 0;
  34966. this.faceId = -1;
  34967. this.subMeshId = 0;
  34968. this.pickedSprite = null;
  34969. }
  34970. // Methods
  34971. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  34972. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  34973. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  34974. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  34975. return null;
  34976. }
  34977. var indices = this.pickedMesh.getIndices();
  34978. var result;
  34979. if (useVerticesNormals) {
  34980. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34981. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  34982. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  34983. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  34984. normal0 = normal0.scale(this.bu);
  34985. normal1 = normal1.scale(this.bv);
  34986. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  34987. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  34988. }
  34989. else {
  34990. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34991. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  34992. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  34993. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  34994. var p1p2 = vertex1.subtract(vertex2);
  34995. var p3p2 = vertex3.subtract(vertex2);
  34996. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  34997. }
  34998. if (useWorldCoordinates) {
  34999. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  35000. }
  35001. return BABYLON.Vector3.Normalize(result);
  35002. };
  35003. PickingInfo.prototype.getTextureCoordinates = function () {
  35004. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  35005. return null;
  35006. }
  35007. var indices = this.pickedMesh.getIndices();
  35008. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  35009. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  35010. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  35011. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  35012. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  35013. uv1 = uv1.scale(this.bu);
  35014. uv2 = uv2.scale(this.bv);
  35015. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  35016. };
  35017. return PickingInfo;
  35018. }());
  35019. BABYLON.PickingInfo = PickingInfo;
  35020. })(BABYLON || (BABYLON = {}));
  35021. //# sourceMappingURL=babylon.pickingInfo.js.map
  35022. var BABYLON;
  35023. (function (BABYLON) {
  35024. var Ray = (function () {
  35025. function Ray(origin, direction, length) {
  35026. if (length === void 0) { length = Number.MAX_VALUE; }
  35027. this.origin = origin;
  35028. this.direction = direction;
  35029. this.length = length;
  35030. }
  35031. // Methods
  35032. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  35033. var d = 0.0;
  35034. var maxValue = Number.MAX_VALUE;
  35035. var inv;
  35036. var min;
  35037. var max;
  35038. var temp;
  35039. if (Math.abs(this.direction.x) < 0.0000001) {
  35040. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  35041. return false;
  35042. }
  35043. }
  35044. else {
  35045. inv = 1.0 / this.direction.x;
  35046. min = (minimum.x - this.origin.x) * inv;
  35047. max = (maximum.x - this.origin.x) * inv;
  35048. if (max === -Infinity) {
  35049. max = Infinity;
  35050. }
  35051. if (min > max) {
  35052. temp = min;
  35053. min = max;
  35054. max = temp;
  35055. }
  35056. d = Math.max(min, d);
  35057. maxValue = Math.min(max, maxValue);
  35058. if (d > maxValue) {
  35059. return false;
  35060. }
  35061. }
  35062. if (Math.abs(this.direction.y) < 0.0000001) {
  35063. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  35064. return false;
  35065. }
  35066. }
  35067. else {
  35068. inv = 1.0 / this.direction.y;
  35069. min = (minimum.y - this.origin.y) * inv;
  35070. max = (maximum.y - this.origin.y) * inv;
  35071. if (max === -Infinity) {
  35072. max = Infinity;
  35073. }
  35074. if (min > max) {
  35075. temp = min;
  35076. min = max;
  35077. max = temp;
  35078. }
  35079. d = Math.max(min, d);
  35080. maxValue = Math.min(max, maxValue);
  35081. if (d > maxValue) {
  35082. return false;
  35083. }
  35084. }
  35085. if (Math.abs(this.direction.z) < 0.0000001) {
  35086. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  35087. return false;
  35088. }
  35089. }
  35090. else {
  35091. inv = 1.0 / this.direction.z;
  35092. min = (minimum.z - this.origin.z) * inv;
  35093. max = (maximum.z - this.origin.z) * inv;
  35094. if (max === -Infinity) {
  35095. max = Infinity;
  35096. }
  35097. if (min > max) {
  35098. temp = min;
  35099. min = max;
  35100. max = temp;
  35101. }
  35102. d = Math.max(min, d);
  35103. maxValue = Math.min(max, maxValue);
  35104. if (d > maxValue) {
  35105. return false;
  35106. }
  35107. }
  35108. return true;
  35109. };
  35110. Ray.prototype.intersectsBox = function (box) {
  35111. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  35112. };
  35113. Ray.prototype.intersectsSphere = function (sphere) {
  35114. var x = sphere.center.x - this.origin.x;
  35115. var y = sphere.center.y - this.origin.y;
  35116. var z = sphere.center.z - this.origin.z;
  35117. var pyth = (x * x) + (y * y) + (z * z);
  35118. var rr = sphere.radius * sphere.radius;
  35119. if (pyth <= rr) {
  35120. return true;
  35121. }
  35122. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  35123. if (dot < 0.0) {
  35124. return false;
  35125. }
  35126. var temp = pyth - (dot * dot);
  35127. return temp <= rr;
  35128. };
  35129. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  35130. if (!this._edge1) {
  35131. this._edge1 = BABYLON.Vector3.Zero();
  35132. this._edge2 = BABYLON.Vector3.Zero();
  35133. this._pvec = BABYLON.Vector3.Zero();
  35134. this._tvec = BABYLON.Vector3.Zero();
  35135. this._qvec = BABYLON.Vector3.Zero();
  35136. }
  35137. vertex1.subtractToRef(vertex0, this._edge1);
  35138. vertex2.subtractToRef(vertex0, this._edge2);
  35139. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  35140. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  35141. if (det === 0) {
  35142. return null;
  35143. }
  35144. var invdet = 1 / det;
  35145. this.origin.subtractToRef(vertex0, this._tvec);
  35146. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  35147. if (bu < 0 || bu > 1.0) {
  35148. return null;
  35149. }
  35150. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  35151. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  35152. if (bv < 0 || bu + bv > 1.0) {
  35153. return null;
  35154. }
  35155. //check if the distance is longer than the predefined length.
  35156. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  35157. if (distance > this.length) {
  35158. return null;
  35159. }
  35160. return new BABYLON.IntersectionInfo(bu, bv, distance);
  35161. };
  35162. Ray.prototype.intersectsPlane = function (plane) {
  35163. var distance;
  35164. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  35165. if (Math.abs(result1) < 9.99999997475243E-07) {
  35166. return null;
  35167. }
  35168. else {
  35169. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  35170. distance = (-plane.d - result2) / result1;
  35171. if (distance < 0.0) {
  35172. if (distance < -9.99999997475243E-07) {
  35173. return null;
  35174. }
  35175. else {
  35176. return 0;
  35177. }
  35178. }
  35179. return distance;
  35180. }
  35181. };
  35182. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  35183. var tm = BABYLON.Tmp.Matrix[0];
  35184. mesh.getWorldMatrix().invertToRef(tm);
  35185. if (this._tmpRay) {
  35186. Ray.TransformToRef(this, tm, this._tmpRay);
  35187. }
  35188. else {
  35189. this._tmpRay = Ray.Transform(this, tm);
  35190. }
  35191. return mesh.intersects(this._tmpRay, fastCheck);
  35192. };
  35193. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  35194. if (results) {
  35195. results.length = 0;
  35196. }
  35197. else {
  35198. results = [];
  35199. }
  35200. for (var i = 0; i < meshes.length; i++) {
  35201. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  35202. if (pickInfo.hit) {
  35203. results.push(pickInfo);
  35204. }
  35205. }
  35206. results.sort(this._comparePickingInfo);
  35207. return results;
  35208. };
  35209. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  35210. if (pickingInfoA.distance < pickingInfoB.distance) {
  35211. return -1;
  35212. }
  35213. else if (pickingInfoA.distance > pickingInfoB.distance) {
  35214. return 1;
  35215. }
  35216. else {
  35217. return 0;
  35218. }
  35219. };
  35220. /**
  35221. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  35222. * @param sega the first point of the segment to test the intersection against
  35223. * @param segb the second point of the segment to test the intersection against
  35224. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  35225. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  35226. */
  35227. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  35228. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  35229. var u = segb.subtract(sega);
  35230. var v = rsegb.subtract(this.origin);
  35231. var w = sega.subtract(this.origin);
  35232. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  35233. var b = BABYLON.Vector3.Dot(u, v);
  35234. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  35235. var d = BABYLON.Vector3.Dot(u, w);
  35236. var e = BABYLON.Vector3.Dot(v, w);
  35237. var D = a * c - b * b; // always >= 0
  35238. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  35239. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  35240. // compute the line parameters of the two closest points
  35241. if (D < Ray.smallnum) {
  35242. sN = 0.0; // force using point P0 on segment S1
  35243. sD = 1.0; // to prevent possible division by 0.0 later
  35244. tN = e;
  35245. tD = c;
  35246. }
  35247. else {
  35248. sN = (b * e - c * d);
  35249. tN = (a * e - b * d);
  35250. if (sN < 0.0) {
  35251. sN = 0.0;
  35252. tN = e;
  35253. tD = c;
  35254. }
  35255. else if (sN > sD) {
  35256. sN = sD;
  35257. tN = e + b;
  35258. tD = c;
  35259. }
  35260. }
  35261. if (tN < 0.0) {
  35262. tN = 0.0;
  35263. // recompute sc for this edge
  35264. if (-d < 0.0) {
  35265. sN = 0.0;
  35266. }
  35267. else if (-d > a)
  35268. sN = sD;
  35269. else {
  35270. sN = -d;
  35271. sD = a;
  35272. }
  35273. }
  35274. else if (tN > tD) {
  35275. tN = tD;
  35276. // recompute sc for this edge
  35277. if ((-d + b) < 0.0) {
  35278. sN = 0;
  35279. }
  35280. else if ((-d + b) > a) {
  35281. sN = sD;
  35282. }
  35283. else {
  35284. sN = (-d + b);
  35285. sD = a;
  35286. }
  35287. }
  35288. // finally do the division to get sc and tc
  35289. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  35290. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  35291. // get the difference of the two closest points
  35292. var qtc = v.multiplyByFloats(tc, tc, tc);
  35293. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  35294. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  35295. if (isIntersected) {
  35296. return qtc.length();
  35297. }
  35298. return -1;
  35299. };
  35300. // Statics
  35301. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  35302. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  35303. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  35304. var direction = end.subtract(start);
  35305. direction.normalize();
  35306. return new Ray(start, direction);
  35307. };
  35308. /**
  35309. * 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
  35310. * transformed to the given world matrix.
  35311. * @param origin The origin point
  35312. * @param end The end point
  35313. * @param world a matrix to transform the ray to. Default is the identity matrix.
  35314. */
  35315. Ray.CreateNewFromTo = function (origin, end, world) {
  35316. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  35317. var direction = end.subtract(origin);
  35318. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  35319. direction.normalize();
  35320. return Ray.Transform(new Ray(origin, direction, length), world);
  35321. };
  35322. Ray.Transform = function (ray, matrix) {
  35323. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  35324. Ray.TransformToRef(ray, matrix, result);
  35325. return result;
  35326. };
  35327. Ray.TransformToRef = function (ray, matrix, result) {
  35328. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  35329. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  35330. result.length = ray.length;
  35331. var dir = result.direction;
  35332. var len = dir.length();
  35333. if (!(len === 0 || len === 1)) {
  35334. var num = 1.0 / len;
  35335. dir.x *= num;
  35336. dir.y *= num;
  35337. dir.z *= num;
  35338. result.length *= len;
  35339. }
  35340. };
  35341. return Ray;
  35342. }());
  35343. Ray.smallnum = 0.00000001;
  35344. Ray.rayl = 10e8;
  35345. BABYLON.Ray = Ray;
  35346. })(BABYLON || (BABYLON = {}));
  35347. //# sourceMappingURL=babylon.ray.js.map
  35348. var BABYLON;
  35349. (function (BABYLON) {
  35350. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  35351. if (boxMin.x > sphereCenter.x + sphereRadius)
  35352. return false;
  35353. if (sphereCenter.x - sphereRadius > boxMax.x)
  35354. return false;
  35355. if (boxMin.y > sphereCenter.y + sphereRadius)
  35356. return false;
  35357. if (sphereCenter.y - sphereRadius > boxMax.y)
  35358. return false;
  35359. if (boxMin.z > sphereCenter.z + sphereRadius)
  35360. return false;
  35361. if (sphereCenter.z - sphereRadius > boxMax.z)
  35362. return false;
  35363. return true;
  35364. };
  35365. var getLowestRoot = (function () {
  35366. var result = { root: 0, found: false };
  35367. return function (a, b, c, maxR) {
  35368. result.root = 0;
  35369. result.found = false;
  35370. var determinant = b * b - 4.0 * a * c;
  35371. if (determinant < 0)
  35372. return result;
  35373. var sqrtD = Math.sqrt(determinant);
  35374. var r1 = (-b - sqrtD) / (2.0 * a);
  35375. var r2 = (-b + sqrtD) / (2.0 * a);
  35376. if (r1 > r2) {
  35377. var temp = r2;
  35378. r2 = r1;
  35379. r1 = temp;
  35380. }
  35381. if (r1 > 0 && r1 < maxR) {
  35382. result.root = r1;
  35383. result.found = true;
  35384. return result;
  35385. }
  35386. if (r2 > 0 && r2 < maxR) {
  35387. result.root = r2;
  35388. result.found = true;
  35389. return result;
  35390. }
  35391. return result;
  35392. };
  35393. })();
  35394. var Collider = (function () {
  35395. function Collider() {
  35396. this.radius = new BABYLON.Vector3(1, 1, 1);
  35397. this.retry = 0;
  35398. this.basePointWorld = BABYLON.Vector3.Zero();
  35399. this.velocityWorld = BABYLON.Vector3.Zero();
  35400. this.normalizedVelocity = BABYLON.Vector3.Zero();
  35401. this._collisionPoint = BABYLON.Vector3.Zero();
  35402. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  35403. this._tempVector = BABYLON.Vector3.Zero();
  35404. this._tempVector2 = BABYLON.Vector3.Zero();
  35405. this._tempVector3 = BABYLON.Vector3.Zero();
  35406. this._tempVector4 = BABYLON.Vector3.Zero();
  35407. this._edge = BABYLON.Vector3.Zero();
  35408. this._baseToVertex = BABYLON.Vector3.Zero();
  35409. this._destinationPoint = BABYLON.Vector3.Zero();
  35410. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  35411. this._displacementVector = BABYLON.Vector3.Zero();
  35412. this._collisionMask = -1;
  35413. }
  35414. Object.defineProperty(Collider.prototype, "collisionMask", {
  35415. get: function () {
  35416. return this._collisionMask;
  35417. },
  35418. set: function (mask) {
  35419. this._collisionMask = !isNaN(mask) ? mask : -1;
  35420. },
  35421. enumerable: true,
  35422. configurable: true
  35423. });
  35424. // Methods
  35425. Collider.prototype._initialize = function (source, dir, e) {
  35426. this.velocity = dir;
  35427. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  35428. this.basePoint = source;
  35429. source.multiplyToRef(this.radius, this.basePointWorld);
  35430. dir.multiplyToRef(this.radius, this.velocityWorld);
  35431. this.velocityWorldLength = this.velocityWorld.length();
  35432. this.epsilon = e;
  35433. this.collisionFound = false;
  35434. };
  35435. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  35436. pa.subtractToRef(point, this._tempVector);
  35437. pb.subtractToRef(point, this._tempVector2);
  35438. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  35439. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  35440. if (d < 0)
  35441. return false;
  35442. pc.subtractToRef(point, this._tempVector3);
  35443. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  35444. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  35445. if (d < 0)
  35446. return false;
  35447. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  35448. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  35449. return d >= 0;
  35450. };
  35451. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  35452. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  35453. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  35454. if (distance > this.velocityWorldLength + max + sphereRadius) {
  35455. return false;
  35456. }
  35457. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  35458. return false;
  35459. return true;
  35460. };
  35461. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  35462. var t0;
  35463. var embeddedInPlane = false;
  35464. //defensive programming, actually not needed.
  35465. if (!trianglePlaneArray) {
  35466. trianglePlaneArray = [];
  35467. }
  35468. if (!trianglePlaneArray[faceIndex]) {
  35469. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  35470. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  35471. }
  35472. var trianglePlane = trianglePlaneArray[faceIndex];
  35473. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  35474. return;
  35475. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  35476. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  35477. if (normalDotVelocity == 0) {
  35478. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  35479. return;
  35480. embeddedInPlane = true;
  35481. t0 = 0;
  35482. }
  35483. else {
  35484. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  35485. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  35486. if (t0 > t1) {
  35487. var temp = t1;
  35488. t1 = t0;
  35489. t0 = temp;
  35490. }
  35491. if (t0 > 1.0 || t1 < 0.0)
  35492. return;
  35493. if (t0 < 0)
  35494. t0 = 0;
  35495. if (t0 > 1.0)
  35496. t0 = 1.0;
  35497. }
  35498. this._collisionPoint.copyFromFloats(0, 0, 0);
  35499. var found = false;
  35500. var t = 1.0;
  35501. if (!embeddedInPlane) {
  35502. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  35503. this.velocity.scaleToRef(t0, this._tempVector);
  35504. this._planeIntersectionPoint.addInPlace(this._tempVector);
  35505. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  35506. found = true;
  35507. t = t0;
  35508. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  35509. }
  35510. }
  35511. if (!found) {
  35512. var velocitySquaredLength = this.velocity.lengthSquared();
  35513. var a = velocitySquaredLength;
  35514. this.basePoint.subtractToRef(p1, this._tempVector);
  35515. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  35516. var c = this._tempVector.lengthSquared() - 1.0;
  35517. var lowestRoot = getLowestRoot(a, b, c, t);
  35518. if (lowestRoot.found) {
  35519. t = lowestRoot.root;
  35520. found = true;
  35521. this._collisionPoint.copyFrom(p1);
  35522. }
  35523. this.basePoint.subtractToRef(p2, this._tempVector);
  35524. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  35525. c = this._tempVector.lengthSquared() - 1.0;
  35526. lowestRoot = getLowestRoot(a, b, c, t);
  35527. if (lowestRoot.found) {
  35528. t = lowestRoot.root;
  35529. found = true;
  35530. this._collisionPoint.copyFrom(p2);
  35531. }
  35532. this.basePoint.subtractToRef(p3, this._tempVector);
  35533. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  35534. c = this._tempVector.lengthSquared() - 1.0;
  35535. lowestRoot = getLowestRoot(a, b, c, t);
  35536. if (lowestRoot.found) {
  35537. t = lowestRoot.root;
  35538. found = true;
  35539. this._collisionPoint.copyFrom(p3);
  35540. }
  35541. p2.subtractToRef(p1, this._edge);
  35542. p1.subtractToRef(this.basePoint, this._baseToVertex);
  35543. var edgeSquaredLength = this._edge.lengthSquared();
  35544. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  35545. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  35546. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  35547. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  35548. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  35549. lowestRoot = getLowestRoot(a, b, c, t);
  35550. if (lowestRoot.found) {
  35551. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  35552. if (f >= 0.0 && f <= 1.0) {
  35553. t = lowestRoot.root;
  35554. found = true;
  35555. this._edge.scaleInPlace(f);
  35556. p1.addToRef(this._edge, this._collisionPoint);
  35557. }
  35558. }
  35559. p3.subtractToRef(p2, this._edge);
  35560. p2.subtractToRef(this.basePoint, this._baseToVertex);
  35561. edgeSquaredLength = this._edge.lengthSquared();
  35562. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  35563. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  35564. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  35565. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  35566. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  35567. lowestRoot = getLowestRoot(a, b, c, t);
  35568. if (lowestRoot.found) {
  35569. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  35570. if (f >= 0.0 && f <= 1.0) {
  35571. t = lowestRoot.root;
  35572. found = true;
  35573. this._edge.scaleInPlace(f);
  35574. p2.addToRef(this._edge, this._collisionPoint);
  35575. }
  35576. }
  35577. p1.subtractToRef(p3, this._edge);
  35578. p3.subtractToRef(this.basePoint, this._baseToVertex);
  35579. edgeSquaredLength = this._edge.lengthSquared();
  35580. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  35581. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  35582. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  35583. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  35584. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  35585. lowestRoot = getLowestRoot(a, b, c, t);
  35586. if (lowestRoot.found) {
  35587. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  35588. if (f >= 0.0 && f <= 1.0) {
  35589. t = lowestRoot.root;
  35590. found = true;
  35591. this._edge.scaleInPlace(f);
  35592. p3.addToRef(this._edge, this._collisionPoint);
  35593. }
  35594. }
  35595. }
  35596. if (found) {
  35597. var distToCollision = t * this.velocity.length();
  35598. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  35599. if (!this.intersectionPoint) {
  35600. this.intersectionPoint = this._collisionPoint.clone();
  35601. }
  35602. else {
  35603. this.intersectionPoint.copyFrom(this._collisionPoint);
  35604. }
  35605. this.nearestDistance = distToCollision;
  35606. this.collisionFound = true;
  35607. }
  35608. }
  35609. };
  35610. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  35611. for (var i = indexStart; i < indexEnd; i += 3) {
  35612. var p1 = pts[indices[i] - decal];
  35613. var p2 = pts[indices[i + 1] - decal];
  35614. var p3 = pts[indices[i + 2] - decal];
  35615. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  35616. }
  35617. };
  35618. Collider.prototype._getResponse = function (pos, vel) {
  35619. pos.addToRef(vel, this._destinationPoint);
  35620. vel.scaleInPlace((this.nearestDistance / vel.length()));
  35621. this.basePoint.addToRef(vel, pos);
  35622. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  35623. this._slidePlaneNormal.normalize();
  35624. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  35625. pos.addInPlace(this._displacementVector);
  35626. this.intersectionPoint.addInPlace(this._displacementVector);
  35627. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  35628. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  35629. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  35630. };
  35631. return Collider;
  35632. }());
  35633. BABYLON.Collider = Collider;
  35634. })(BABYLON || (BABYLON = {}));
  35635. //# sourceMappingURL=babylon.collider.js.map
  35636. var BABYLON;
  35637. (function (BABYLON) {
  35638. //WebWorker code will be inserted to this variable.
  35639. BABYLON.CollisionWorker = "";
  35640. var WorkerTaskType;
  35641. (function (WorkerTaskType) {
  35642. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  35643. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  35644. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  35645. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  35646. var WorkerReplyType;
  35647. (function (WorkerReplyType) {
  35648. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  35649. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  35650. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  35651. var CollisionCoordinatorWorker = (function () {
  35652. function CollisionCoordinatorWorker() {
  35653. var _this = this;
  35654. this._scaledPosition = BABYLON.Vector3.Zero();
  35655. this._scaledVelocity = BABYLON.Vector3.Zero();
  35656. this.onMeshUpdated = function (mesh) {
  35657. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  35658. };
  35659. this.onGeometryUpdated = function (geometry) {
  35660. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  35661. };
  35662. this._afterRender = function () {
  35663. if (!_this._init)
  35664. return;
  35665. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  35666. return;
  35667. }
  35668. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  35669. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  35670. if (_this._runningUpdated > 4) {
  35671. return;
  35672. }
  35673. ++_this._runningUpdated;
  35674. var payload = {
  35675. updatedMeshes: _this._addUpdateMeshesList,
  35676. updatedGeometries: _this._addUpdateGeometriesList,
  35677. removedGeometries: _this._toRemoveGeometryArray,
  35678. removedMeshes: _this._toRemoveMeshesArray
  35679. };
  35680. var message = {
  35681. payload: payload,
  35682. taskType: WorkerTaskType.UPDATE
  35683. };
  35684. var serializable = [];
  35685. for (var id in payload.updatedGeometries) {
  35686. if (payload.updatedGeometries.hasOwnProperty(id)) {
  35687. //prepare transferables
  35688. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  35689. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  35690. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  35691. }
  35692. }
  35693. _this._worker.postMessage(message, serializable);
  35694. _this._addUpdateMeshesList = {};
  35695. _this._addUpdateGeometriesList = {};
  35696. _this._toRemoveGeometryArray = [];
  35697. _this._toRemoveMeshesArray = [];
  35698. };
  35699. this._onMessageFromWorker = function (e) {
  35700. var returnData = e.data;
  35701. if (returnData.error != WorkerReplyType.SUCCESS) {
  35702. //TODO what errors can be returned from the worker?
  35703. BABYLON.Tools.Warn("error returned from worker!");
  35704. return;
  35705. }
  35706. switch (returnData.taskType) {
  35707. case WorkerTaskType.INIT:
  35708. _this._init = true;
  35709. //Update the worked with ALL of the scene's current state
  35710. _this._scene.meshes.forEach(function (mesh) {
  35711. _this.onMeshAdded(mesh);
  35712. });
  35713. _this._scene.getGeometries().forEach(function (geometry) {
  35714. _this.onGeometryAdded(geometry);
  35715. });
  35716. break;
  35717. case WorkerTaskType.UPDATE:
  35718. _this._runningUpdated--;
  35719. break;
  35720. case WorkerTaskType.COLLIDE:
  35721. _this._runningCollisionTask = false;
  35722. var returnPayload = returnData.payload;
  35723. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  35724. return;
  35725. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  35726. //cleanup
  35727. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  35728. break;
  35729. }
  35730. };
  35731. this._collisionsCallbackArray = [];
  35732. this._init = false;
  35733. this._runningUpdated = 0;
  35734. this._runningCollisionTask = false;
  35735. this._addUpdateMeshesList = {};
  35736. this._addUpdateGeometriesList = {};
  35737. this._toRemoveGeometryArray = [];
  35738. this._toRemoveMeshesArray = [];
  35739. }
  35740. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  35741. if (!this._init)
  35742. return;
  35743. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  35744. return;
  35745. position.divideToRef(collider.radius, this._scaledPosition);
  35746. velocity.divideToRef(collider.radius, this._scaledVelocity);
  35747. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  35748. var payload = {
  35749. collider: {
  35750. position: this._scaledPosition.asArray(),
  35751. velocity: this._scaledVelocity.asArray(),
  35752. radius: collider.radius.asArray()
  35753. },
  35754. collisionId: collisionIndex,
  35755. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  35756. maximumRetry: maximumRetry
  35757. };
  35758. var message = {
  35759. payload: payload,
  35760. taskType: WorkerTaskType.COLLIDE
  35761. };
  35762. this._worker.postMessage(message);
  35763. };
  35764. CollisionCoordinatorWorker.prototype.init = function (scene) {
  35765. this._scene = scene;
  35766. this._scene.registerAfterRender(this._afterRender);
  35767. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  35768. this._worker = new Worker(workerUrl);
  35769. this._worker.onmessage = this._onMessageFromWorker;
  35770. var message = {
  35771. payload: {},
  35772. taskType: WorkerTaskType.INIT
  35773. };
  35774. this._worker.postMessage(message);
  35775. };
  35776. CollisionCoordinatorWorker.prototype.destroy = function () {
  35777. this._scene.unregisterAfterRender(this._afterRender);
  35778. this._worker.terminate();
  35779. };
  35780. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  35781. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  35782. this.onMeshUpdated(mesh);
  35783. };
  35784. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  35785. this._toRemoveMeshesArray.push(mesh.uniqueId);
  35786. };
  35787. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  35788. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  35789. geometry.onGeometryUpdated = this.onGeometryUpdated;
  35790. this.onGeometryUpdated(geometry);
  35791. };
  35792. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  35793. this._toRemoveGeometryArray.push(geometry.id);
  35794. };
  35795. return CollisionCoordinatorWorker;
  35796. }());
  35797. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  35798. var submeshes = [];
  35799. if (mesh.subMeshes) {
  35800. submeshes = mesh.subMeshes.map(function (sm, idx) {
  35801. return {
  35802. position: idx,
  35803. verticesStart: sm.verticesStart,
  35804. verticesCount: sm.verticesCount,
  35805. indexStart: sm.indexStart,
  35806. indexCount: sm.indexCount,
  35807. hasMaterial: !!sm.getMaterial(),
  35808. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  35809. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  35810. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  35811. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  35812. };
  35813. });
  35814. }
  35815. var geometryId = null;
  35816. if (mesh instanceof BABYLON.Mesh) {
  35817. geometryId = mesh.geometry ? mesh.geometry.id : null;
  35818. }
  35819. else if (mesh instanceof BABYLON.InstancedMesh) {
  35820. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  35821. }
  35822. return {
  35823. uniqueId: mesh.uniqueId,
  35824. id: mesh.id,
  35825. name: mesh.name,
  35826. geometryId: geometryId,
  35827. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  35828. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  35829. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  35830. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  35831. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  35832. subMeshes: submeshes,
  35833. checkCollisions: mesh.checkCollisions
  35834. };
  35835. };
  35836. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  35837. return {
  35838. id: geometry.id,
  35839. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  35840. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  35841. indices: new Uint32Array(geometry.getIndices() || []),
  35842. };
  35843. };
  35844. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  35845. var CollisionCoordinatorLegacy = (function () {
  35846. function CollisionCoordinatorLegacy() {
  35847. this._scaledPosition = BABYLON.Vector3.Zero();
  35848. this._scaledVelocity = BABYLON.Vector3.Zero();
  35849. this._finalPosition = BABYLON.Vector3.Zero();
  35850. }
  35851. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  35852. position.divideToRef(collider.radius, this._scaledPosition);
  35853. velocity.divideToRef(collider.radius, this._scaledVelocity);
  35854. collider.collidedMesh = null;
  35855. collider.retry = 0;
  35856. collider.initialVelocity = this._scaledVelocity;
  35857. collider.initialPosition = this._scaledPosition;
  35858. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  35859. this._finalPosition.multiplyInPlace(collider.radius);
  35860. //run the callback
  35861. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  35862. };
  35863. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  35864. this._scene = scene;
  35865. };
  35866. CollisionCoordinatorLegacy.prototype.destroy = function () {
  35867. //Legacy need no destruction method.
  35868. };
  35869. //No update in legacy mode
  35870. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  35871. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  35872. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  35873. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  35874. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  35875. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  35876. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  35877. if (excludedMesh === void 0) { excludedMesh = null; }
  35878. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  35879. if (collider.retry >= maximumRetry) {
  35880. finalPosition.copyFrom(position);
  35881. return;
  35882. }
  35883. // Check if this is a mesh else camera or -1
  35884. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  35885. collider._initialize(position, velocity, closeDistance);
  35886. // Check all meshes
  35887. for (var index = 0; index < this._scene.meshes.length; index++) {
  35888. var mesh = this._scene.meshes[index];
  35889. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  35890. mesh._checkCollision(collider);
  35891. }
  35892. }
  35893. if (!collider.collisionFound) {
  35894. position.addToRef(velocity, finalPosition);
  35895. return;
  35896. }
  35897. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  35898. collider._getResponse(position, velocity);
  35899. }
  35900. if (velocity.length() <= closeDistance) {
  35901. finalPosition.copyFrom(position);
  35902. return;
  35903. }
  35904. collider.retry++;
  35905. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  35906. };
  35907. return CollisionCoordinatorLegacy;
  35908. }());
  35909. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  35910. })(BABYLON || (BABYLON = {}));
  35911. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  35912. var BABYLON;
  35913. (function (BABYLON) {
  35914. var Particle = (function () {
  35915. function Particle() {
  35916. this.position = BABYLON.Vector3.Zero();
  35917. this.direction = BABYLON.Vector3.Zero();
  35918. this.color = new BABYLON.Color4(0, 0, 0, 0);
  35919. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  35920. this.lifeTime = 1.0;
  35921. this.age = 0;
  35922. this.size = 0;
  35923. this.angle = 0;
  35924. this.angularSpeed = 0;
  35925. }
  35926. Particle.prototype.copyTo = function (other) {
  35927. other.position.copyFrom(this.position);
  35928. other.direction.copyFrom(this.direction);
  35929. other.color.copyFrom(this.color);
  35930. other.colorStep.copyFrom(this.colorStep);
  35931. other.lifeTime = this.lifeTime;
  35932. other.age = this.age;
  35933. other.size = this.size;
  35934. other.angle = this.angle;
  35935. other.angularSpeed = this.angularSpeed;
  35936. };
  35937. return Particle;
  35938. }());
  35939. BABYLON.Particle = Particle;
  35940. })(BABYLON || (BABYLON = {}));
  35941. //# sourceMappingURL=babylon.particle.js.map
  35942. var BABYLON;
  35943. (function (BABYLON) {
  35944. var randomNumber = function (min, max) {
  35945. if (min === max) {
  35946. return (min);
  35947. }
  35948. var random = Math.random();
  35949. return ((random * (max - min)) + min);
  35950. };
  35951. var ParticleSystem = (function () {
  35952. function ParticleSystem(name, capacity, scene, customEffect) {
  35953. var _this = this;
  35954. this.name = name;
  35955. // Members
  35956. this.animations = [];
  35957. this.renderingGroupId = 0;
  35958. this.emitter = null;
  35959. this.emitRate = 10;
  35960. this.manualEmitCount = -1;
  35961. this.updateSpeed = 0.01;
  35962. this.targetStopDuration = 0;
  35963. this.disposeOnStop = false;
  35964. this.minEmitPower = 1;
  35965. this.maxEmitPower = 1;
  35966. this.minLifeTime = 1;
  35967. this.maxLifeTime = 1;
  35968. this.minSize = 1;
  35969. this.maxSize = 1;
  35970. this.minAngularSpeed = 0;
  35971. this.maxAngularSpeed = 0;
  35972. this.layerMask = 0x0FFFFFFF;
  35973. this.customShader = null;
  35974. this.preventAutoStart = false;
  35975. /**
  35976. * An event triggered when the system is disposed.
  35977. * @type {BABYLON.Observable}
  35978. */
  35979. this.onDisposeObservable = new BABYLON.Observable();
  35980. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  35981. this.forceDepthWrite = false;
  35982. this.gravity = BABYLON.Vector3.Zero();
  35983. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  35984. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  35985. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  35986. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  35987. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  35988. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  35989. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  35990. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  35991. this.particles = new Array();
  35992. this._stockParticles = new Array();
  35993. this._newPartsExcess = 0;
  35994. this._vertexBuffers = {};
  35995. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  35996. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  35997. this._scaledDirection = BABYLON.Vector3.Zero();
  35998. this._scaledGravity = BABYLON.Vector3.Zero();
  35999. this._currentRenderId = -1;
  36000. this._started = false;
  36001. this._stopped = false;
  36002. this._actualFrame = 0;
  36003. this.id = name;
  36004. this._capacity = capacity;
  36005. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  36006. this._customEffect = customEffect;
  36007. scene.particleSystems.push(this);
  36008. var indices = [];
  36009. var index = 0;
  36010. for (var count = 0; count < capacity; count++) {
  36011. indices.push(index);
  36012. indices.push(index + 1);
  36013. indices.push(index + 2);
  36014. indices.push(index);
  36015. indices.push(index + 2);
  36016. indices.push(index + 3);
  36017. index += 4;
  36018. }
  36019. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  36020. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  36021. this._vertexData = new Float32Array(capacity * 11 * 4);
  36022. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 11);
  36023. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  36024. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  36025. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  36026. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  36027. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  36028. this._vertexBuffers["options"] = options;
  36029. // Default behaviors
  36030. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  36031. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  36032. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  36033. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  36034. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  36035. };
  36036. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  36037. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  36038. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  36039. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  36040. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  36041. };
  36042. this.updateFunction = function (particles) {
  36043. for (var index = 0; index < particles.length; index++) {
  36044. var particle = particles[index];
  36045. particle.age += _this._scaledUpdateSpeed;
  36046. if (particle.age >= particle.lifeTime) {
  36047. _this.recycleParticle(particle);
  36048. index--;
  36049. continue;
  36050. }
  36051. else {
  36052. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  36053. particle.color.addInPlace(_this._scaledColorStep);
  36054. if (particle.color.a < 0)
  36055. particle.color.a = 0;
  36056. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  36057. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  36058. particle.position.addInPlace(_this._scaledDirection);
  36059. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  36060. particle.direction.addInPlace(_this._scaledGravity);
  36061. }
  36062. }
  36063. };
  36064. }
  36065. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  36066. set: function (callback) {
  36067. if (this._onDisposeObserver) {
  36068. this.onDisposeObservable.remove(this._onDisposeObserver);
  36069. }
  36070. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  36071. },
  36072. enumerable: true,
  36073. configurable: true
  36074. });
  36075. ParticleSystem.prototype.recycleParticle = function (particle) {
  36076. var lastParticle = this.particles.pop();
  36077. if (lastParticle !== particle) {
  36078. lastParticle.copyTo(particle);
  36079. this._stockParticles.push(lastParticle);
  36080. }
  36081. };
  36082. ParticleSystem.prototype.getCapacity = function () {
  36083. return this._capacity;
  36084. };
  36085. ParticleSystem.prototype.isAlive = function () {
  36086. return this._alive;
  36087. };
  36088. ParticleSystem.prototype.isStarted = function () {
  36089. return this._started;
  36090. };
  36091. ParticleSystem.prototype.start = function () {
  36092. this._started = true;
  36093. this._stopped = false;
  36094. this._actualFrame = 0;
  36095. };
  36096. ParticleSystem.prototype.stop = function () {
  36097. this._stopped = true;
  36098. };
  36099. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  36100. var offset = index * 11;
  36101. this._vertexData[offset] = particle.position.x;
  36102. this._vertexData[offset + 1] = particle.position.y;
  36103. this._vertexData[offset + 2] = particle.position.z;
  36104. this._vertexData[offset + 3] = particle.color.r;
  36105. this._vertexData[offset + 4] = particle.color.g;
  36106. this._vertexData[offset + 5] = particle.color.b;
  36107. this._vertexData[offset + 6] = particle.color.a;
  36108. this._vertexData[offset + 7] = particle.angle;
  36109. this._vertexData[offset + 8] = particle.size;
  36110. this._vertexData[offset + 9] = offsetX;
  36111. this._vertexData[offset + 10] = offsetY;
  36112. };
  36113. ParticleSystem.prototype._update = function (newParticles) {
  36114. // Update current
  36115. this._alive = this.particles.length > 0;
  36116. this.updateFunction(this.particles);
  36117. // Add new ones
  36118. var worldMatrix;
  36119. if (this.emitter.position) {
  36120. worldMatrix = this.emitter.getWorldMatrix();
  36121. }
  36122. else {
  36123. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  36124. }
  36125. var particle;
  36126. for (var index = 0; index < newParticles; index++) {
  36127. if (this.particles.length === this._capacity) {
  36128. break;
  36129. }
  36130. if (this._stockParticles.length !== 0) {
  36131. particle = this._stockParticles.pop();
  36132. particle.age = 0;
  36133. }
  36134. else {
  36135. particle = new BABYLON.Particle();
  36136. }
  36137. this.particles.push(particle);
  36138. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  36139. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  36140. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  36141. particle.size = randomNumber(this.minSize, this.maxSize);
  36142. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  36143. this.startPositionFunction(worldMatrix, particle.position, particle);
  36144. var step = randomNumber(0, 1.0);
  36145. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  36146. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  36147. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  36148. }
  36149. };
  36150. ParticleSystem.prototype._getEffect = function () {
  36151. if (this._customEffect) {
  36152. return this._customEffect;
  36153. }
  36154. ;
  36155. var defines = [];
  36156. if (this._scene.clipPlane) {
  36157. defines.push("#define CLIPPLANE");
  36158. }
  36159. // Effect
  36160. var join = defines.join("\n");
  36161. if (this._cachedDefines !== join) {
  36162. this._cachedDefines = join;
  36163. this._effect = this._scene.getEngine().createEffect("particles", [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  36164. }
  36165. return this._effect;
  36166. };
  36167. ParticleSystem.prototype.animate = function () {
  36168. if (!this._started)
  36169. return;
  36170. var effect = this._getEffect();
  36171. // Check
  36172. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  36173. return;
  36174. if (this._currentRenderId === this._scene.getRenderId()) {
  36175. return;
  36176. }
  36177. this._currentRenderId = this._scene.getRenderId();
  36178. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  36179. // determine the number of particles we need to create
  36180. var newParticles;
  36181. if (this.manualEmitCount > -1) {
  36182. newParticles = this.manualEmitCount;
  36183. this._newPartsExcess = 0;
  36184. this.manualEmitCount = 0;
  36185. }
  36186. else {
  36187. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  36188. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  36189. }
  36190. if (this._newPartsExcess > 1.0) {
  36191. newParticles += this._newPartsExcess >> 0;
  36192. this._newPartsExcess -= this._newPartsExcess >> 0;
  36193. }
  36194. this._alive = false;
  36195. if (!this._stopped) {
  36196. this._actualFrame += this._scaledUpdateSpeed;
  36197. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  36198. this.stop();
  36199. }
  36200. else {
  36201. newParticles = 0;
  36202. }
  36203. this._update(newParticles);
  36204. // Stopped?
  36205. if (this._stopped) {
  36206. if (!this._alive) {
  36207. this._started = false;
  36208. if (this.disposeOnStop) {
  36209. this._scene._toBeDisposed.push(this);
  36210. }
  36211. }
  36212. }
  36213. // Update VBO
  36214. var offset = 0;
  36215. for (var index = 0; index < this.particles.length; index++) {
  36216. var particle = this.particles[index];
  36217. this._appendParticleVertex(offset++, particle, 0, 0);
  36218. this._appendParticleVertex(offset++, particle, 1, 0);
  36219. this._appendParticleVertex(offset++, particle, 1, 1);
  36220. this._appendParticleVertex(offset++, particle, 0, 1);
  36221. }
  36222. this._vertexBuffer.update(this._vertexData);
  36223. };
  36224. ParticleSystem.prototype.render = function () {
  36225. var effect = this._getEffect();
  36226. // Check
  36227. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  36228. return 0;
  36229. var engine = this._scene.getEngine();
  36230. // Render
  36231. engine.enableEffect(effect);
  36232. engine.setState(false);
  36233. var viewMatrix = this._scene.getViewMatrix();
  36234. effect.setTexture("diffuseSampler", this.particleTexture);
  36235. effect.setMatrix("view", viewMatrix);
  36236. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  36237. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  36238. if (this._scene.clipPlane) {
  36239. var clipPlane = this._scene.clipPlane;
  36240. var invView = viewMatrix.clone();
  36241. invView.invert();
  36242. effect.setMatrix("invView", invView);
  36243. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  36244. }
  36245. // VBOs
  36246. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  36247. // Draw order
  36248. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  36249. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  36250. }
  36251. else {
  36252. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  36253. }
  36254. if (this.forceDepthWrite) {
  36255. engine.setDepthWrite(true);
  36256. }
  36257. engine.draw(true, 0, this.particles.length * 6);
  36258. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  36259. return this.particles.length;
  36260. };
  36261. ParticleSystem.prototype.dispose = function () {
  36262. if (this._vertexBuffer) {
  36263. this._vertexBuffer.dispose();
  36264. this._vertexBuffer = null;
  36265. }
  36266. if (this._indexBuffer) {
  36267. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  36268. this._indexBuffer = null;
  36269. }
  36270. if (this.particleTexture) {
  36271. this.particleTexture.dispose();
  36272. this.particleTexture = null;
  36273. }
  36274. // Remove from scene
  36275. var index = this._scene.particleSystems.indexOf(this);
  36276. this._scene.particleSystems.splice(index, 1);
  36277. // Callback
  36278. this.onDisposeObservable.notifyObservers(this);
  36279. this.onDisposeObservable.clear();
  36280. };
  36281. // Clone
  36282. ParticleSystem.prototype.clone = function (name, newEmitter) {
  36283. var custom = null;
  36284. var program = null;
  36285. if (this.customShader != null) {
  36286. program = this.customShader;
  36287. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  36288. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  36289. }
  36290. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  36291. result.customShader = program;
  36292. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  36293. if (newEmitter === undefined) {
  36294. newEmitter = this.emitter;
  36295. }
  36296. result.emitter = newEmitter;
  36297. if (this.particleTexture) {
  36298. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  36299. }
  36300. if (!this.preventAutoStart) {
  36301. result.start();
  36302. }
  36303. return result;
  36304. };
  36305. ParticleSystem.prototype.serialize = function () {
  36306. var serializationObject = {};
  36307. serializationObject.name = this.name;
  36308. serializationObject.id = this.id;
  36309. // Emitter
  36310. if (this.emitter.position) {
  36311. serializationObject.emitterId = this.emitter.id;
  36312. }
  36313. else {
  36314. serializationObject.emitter = this.emitter.asArray();
  36315. }
  36316. serializationObject.capacity = this.getCapacity();
  36317. if (this.particleTexture) {
  36318. serializationObject.textureName = this.particleTexture.name;
  36319. }
  36320. // Animations
  36321. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  36322. // Particle system
  36323. serializationObject.minAngularSpeed = this.minAngularSpeed;
  36324. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  36325. serializationObject.minSize = this.minSize;
  36326. serializationObject.maxSize = this.maxSize;
  36327. serializationObject.minEmitPower = this.minEmitPower;
  36328. serializationObject.maxEmitPower = this.maxEmitPower;
  36329. serializationObject.minLifeTime = this.minLifeTime;
  36330. serializationObject.maxLifeTime = this.maxLifeTime;
  36331. serializationObject.emitRate = this.emitRate;
  36332. serializationObject.minEmitBox = this.minEmitBox.asArray();
  36333. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  36334. serializationObject.gravity = this.gravity.asArray();
  36335. serializationObject.direction1 = this.direction1.asArray();
  36336. serializationObject.direction2 = this.direction2.asArray();
  36337. serializationObject.color1 = this.color1.asArray();
  36338. serializationObject.color2 = this.color2.asArray();
  36339. serializationObject.colorDead = this.colorDead.asArray();
  36340. serializationObject.updateSpeed = this.updateSpeed;
  36341. serializationObject.targetStopDuration = this.targetStopDuration;
  36342. serializationObject.textureMask = this.textureMask.asArray();
  36343. serializationObject.blendMode = this.blendMode;
  36344. serializationObject.customShader = this.customShader;
  36345. serializationObject.preventAutoStart = this.preventAutoStart;
  36346. return serializationObject;
  36347. };
  36348. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  36349. var name = parsedParticleSystem.name;
  36350. var custom = null;
  36351. var program = null;
  36352. if (parsedParticleSystem.customShader) {
  36353. program = parsedParticleSystem.customShader;
  36354. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  36355. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  36356. }
  36357. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom);
  36358. particleSystem.customShader = program;
  36359. if (parsedParticleSystem.id) {
  36360. particleSystem.id = parsedParticleSystem.id;
  36361. }
  36362. // Auto start
  36363. if (parsedParticleSystem.preventAutoStart) {
  36364. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  36365. }
  36366. // Texture
  36367. if (parsedParticleSystem.textureName) {
  36368. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  36369. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  36370. }
  36371. // Emitter
  36372. if (parsedParticleSystem.emitterId) {
  36373. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  36374. }
  36375. else {
  36376. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  36377. }
  36378. // Animations
  36379. if (parsedParticleSystem.animations) {
  36380. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  36381. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  36382. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  36383. }
  36384. }
  36385. if (parsedParticleSystem.autoAnimate) {
  36386. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  36387. }
  36388. // Particle system
  36389. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  36390. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  36391. particleSystem.minSize = parsedParticleSystem.minSize;
  36392. particleSystem.maxSize = parsedParticleSystem.maxSize;
  36393. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  36394. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  36395. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  36396. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  36397. particleSystem.emitRate = parsedParticleSystem.emitRate;
  36398. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  36399. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  36400. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  36401. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  36402. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  36403. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  36404. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  36405. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  36406. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  36407. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  36408. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  36409. particleSystem.blendMode = parsedParticleSystem.blendMode;
  36410. if (!particleSystem.preventAutoStart) {
  36411. particleSystem.start();
  36412. }
  36413. return particleSystem;
  36414. };
  36415. return ParticleSystem;
  36416. }());
  36417. // Statics
  36418. ParticleSystem.BLENDMODE_ONEONE = 0;
  36419. ParticleSystem.BLENDMODE_STANDARD = 1;
  36420. BABYLON.ParticleSystem = ParticleSystem;
  36421. })(BABYLON || (BABYLON = {}));
  36422. //# sourceMappingURL=babylon.particleSystem.js.map
  36423. var BABYLON;
  36424. (function (BABYLON) {
  36425. var SolidParticle = (function () {
  36426. /**
  36427. * Creates a Solid Particle object.
  36428. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  36429. * `particleIndex` (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  36430. * `positionIndex` (integer) is the starting index of the particle vertices in the SPS "positions" array.
  36431. * `model` (ModelShape) is a reference to the model shape on what the particle is designed.
  36432. * `shapeId` (integer) is the model shape identifier in the SPS.
  36433. * `idxInShape` (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  36434. * `modelBoundingInfo` is the reference to the model BoundingInfo used for intersection computations.
  36435. */
  36436. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  36437. this.idx = 0; // particle global index
  36438. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); // color
  36439. this.position = BABYLON.Vector3.Zero(); // position
  36440. this.rotation = BABYLON.Vector3.Zero(); // rotation
  36441. this.scaling = new BABYLON.Vector3(1.0, 1.0, 1.0); // scaling
  36442. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0); // uvs
  36443. this.velocity = BABYLON.Vector3.Zero(); // velocity
  36444. this.alive = true; // alive
  36445. this.isVisible = true; // visibility
  36446. this._pos = 0; // index of this particle in the global "positions" array
  36447. this.shapeId = 0; // model shape id
  36448. this.idxInShape = 0; // index of the particle in its shape id
  36449. this.idx = particleIndex;
  36450. this._pos = positionIndex;
  36451. this._model = model;
  36452. this.shapeId = shapeId;
  36453. this.idxInShape = idxInShape;
  36454. this._sps = sps;
  36455. if (modelBoundingInfo) {
  36456. this._modelBoundingInfo = modelBoundingInfo;
  36457. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  36458. }
  36459. }
  36460. Object.defineProperty(SolidParticle.prototype, "scale", {
  36461. /**
  36462. * legacy support, changed scale to scaling
  36463. */
  36464. get: function () {
  36465. return this.scaling;
  36466. },
  36467. set: function (scale) {
  36468. this.scaling = scale;
  36469. },
  36470. enumerable: true,
  36471. configurable: true
  36472. });
  36473. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  36474. /**
  36475. * legacy support, changed quaternion to rotationQuaternion
  36476. */
  36477. get: function () {
  36478. return this.rotationQuaternion;
  36479. },
  36480. set: function (q) {
  36481. this.rotationQuaternion = q;
  36482. },
  36483. enumerable: true,
  36484. configurable: true
  36485. });
  36486. /**
  36487. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  36488. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  36489. * `target` is the object (solid particle or mesh) what the intersection is computed against.
  36490. */
  36491. SolidParticle.prototype.intersectsMesh = function (target) {
  36492. if (!this._boundingInfo || !target._boundingInfo) {
  36493. return false;
  36494. }
  36495. if (this._sps._bSphereOnly) {
  36496. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  36497. }
  36498. return this._boundingInfo.intersects(target._boundingInfo, false);
  36499. };
  36500. return SolidParticle;
  36501. }());
  36502. BABYLON.SolidParticle = SolidParticle;
  36503. var ModelShape = (function () {
  36504. /**
  36505. * 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.
  36506. * SPS internal tool, don't use it manually.
  36507. */
  36508. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  36509. this.shapeID = id;
  36510. this._shape = shape;
  36511. this._shapeUV = shapeUV;
  36512. this._positionFunction = posFunction;
  36513. this._vertexFunction = vtxFunction;
  36514. }
  36515. return ModelShape;
  36516. }());
  36517. BABYLON.ModelShape = ModelShape;
  36518. })(BABYLON || (BABYLON = {}));
  36519. //# sourceMappingURL=babylon.solidParticle.js.map
  36520. var BABYLON;
  36521. (function (BABYLON) {
  36522. /**
  36523. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  36524. */
  36525. var SolidParticleSystem = (function () {
  36526. /**
  36527. * Creates a SPS (Solid Particle System) object.
  36528. * `name` (String) is the SPS name, this will be the underlying mesh name.
  36529. * `scene` (Scene) is the scene in which the SPS is added.
  36530. * `updatable` (optional boolean, default true) : if the SPS must be updatable or immutable.
  36531. * `isPickable` (optional boolean, default false) : if the solid particles must be pickable.
  36532. * `particleIntersection` (optional boolean, default false) : if the solid particle intersections must be computed.
  36533. * `boundingSphereOnly` (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  36534. * `bSphereRadiusFactor` (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  36535. * Example : bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  36536. */
  36537. function SolidParticleSystem(name, scene, options) {
  36538. // public members
  36539. /**
  36540. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  36541. * Example : var p = SPS.particles[i];
  36542. */
  36543. this.particles = new Array();
  36544. /**
  36545. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  36546. */
  36547. this.nbParticles = 0;
  36548. /**
  36549. * If the particles must ever face the camera (default false). Useful for planar particles.
  36550. */
  36551. this.billboard = false;
  36552. /**
  36553. * Recompute normals when adding a shape
  36554. */
  36555. this.recomputeNormals = true;
  36556. /**
  36557. * This a counter ofr your own usage. It's not set by any SPS functions.
  36558. */
  36559. this.counter = 0;
  36560. /**
  36561. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  36562. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  36563. */
  36564. this.vars = {};
  36565. this._positions = new Array();
  36566. this._indices = new Array();
  36567. this._normals = new Array();
  36568. this._colors = new Array();
  36569. this._uvs = new Array();
  36570. this._index = 0; // indices index
  36571. this._updatable = true;
  36572. this._pickable = false;
  36573. this._isVisibilityBoxLocked = false;
  36574. this._alwaysVisible = false;
  36575. this._shapeCounter = 0;
  36576. this._copy = new BABYLON.SolidParticle(null, null, null, null, null, null);
  36577. this._color = new BABYLON.Color4(0, 0, 0, 0);
  36578. this._computeParticleColor = true;
  36579. this._computeParticleTexture = true;
  36580. this._computeParticleRotation = true;
  36581. this._computeParticleVertex = false;
  36582. this._computeBoundingBox = false;
  36583. this._cam_axisZ = BABYLON.Vector3.Zero();
  36584. this._cam_axisY = BABYLON.Vector3.Zero();
  36585. this._cam_axisX = BABYLON.Vector3.Zero();
  36586. this._axisX = BABYLON.Axis.X;
  36587. this._axisY = BABYLON.Axis.Y;
  36588. this._axisZ = BABYLON.Axis.Z;
  36589. this._camDir = BABYLON.Vector3.Zero();
  36590. this._rotMatrix = new BABYLON.Matrix();
  36591. this._invertMatrix = new BABYLON.Matrix();
  36592. this._rotated = BABYLON.Vector3.Zero();
  36593. this._quaternion = new BABYLON.Quaternion();
  36594. this._vertex = BABYLON.Vector3.Zero();
  36595. this._normal = BABYLON.Vector3.Zero();
  36596. this._yaw = 0.0;
  36597. this._pitch = 0.0;
  36598. this._roll = 0.0;
  36599. this._halfroll = 0.0;
  36600. this._halfpitch = 0.0;
  36601. this._halfyaw = 0.0;
  36602. this._sinRoll = 0.0;
  36603. this._cosRoll = 0.0;
  36604. this._sinPitch = 0.0;
  36605. this._cosPitch = 0.0;
  36606. this._sinYaw = 0.0;
  36607. this._cosYaw = 0.0;
  36608. this._w = 0.0;
  36609. this._mustUnrotateFixedNormals = false;
  36610. this._minimum = BABYLON.Tmp.Vector3[0];
  36611. this._maximum = BABYLON.Tmp.Vector3[1];
  36612. this._scale = BABYLON.Tmp.Vector3[2];
  36613. this._translation = BABYLON.Tmp.Vector3[3];
  36614. this._minBbox = BABYLON.Tmp.Vector3[4];
  36615. this._maxBbox = BABYLON.Tmp.Vector3[5];
  36616. this._particlesIntersect = false;
  36617. this._bSphereOnly = false;
  36618. this._bSphereRadiusFactor = 1.0;
  36619. this.name = name;
  36620. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  36621. this._camera = scene.activeCamera;
  36622. this._pickable = options ? options.isPickable : false;
  36623. this._particlesIntersect = options ? options.particleIntersection : false;
  36624. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  36625. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  36626. if (options && options.updatable) {
  36627. this._updatable = options.updatable;
  36628. }
  36629. else {
  36630. this._updatable = true;
  36631. }
  36632. if (this._pickable) {
  36633. this.pickedParticles = [];
  36634. }
  36635. }
  36636. /**
  36637. * Builds the SPS underlying mesh. Returns a standard Mesh.
  36638. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  36639. */
  36640. SolidParticleSystem.prototype.buildMesh = function () {
  36641. if (this.nbParticles === 0) {
  36642. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  36643. this.addShape(triangle, 1);
  36644. triangle.dispose();
  36645. }
  36646. this._positions32 = new Float32Array(this._positions);
  36647. this._uvs32 = new Float32Array(this._uvs);
  36648. this._colors32 = new Float32Array(this._colors);
  36649. if (this.recomputeNormals) {
  36650. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  36651. }
  36652. this._normals32 = new Float32Array(this._normals);
  36653. this._fixedNormal32 = new Float32Array(this._normals);
  36654. if (this._mustUnrotateFixedNormals) {
  36655. this._unrotateFixedNormals();
  36656. }
  36657. var vertexData = new BABYLON.VertexData();
  36658. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  36659. vertexData.indices = this._indices;
  36660. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  36661. if (this._uvs32) {
  36662. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  36663. ;
  36664. }
  36665. if (this._colors32) {
  36666. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  36667. }
  36668. var mesh = new BABYLON.Mesh(this.name, this._scene);
  36669. vertexData.applyToMesh(mesh, this._updatable);
  36670. this.mesh = mesh;
  36671. this.mesh.isPickable = this._pickable;
  36672. // free memory
  36673. this._positions = null;
  36674. this._normals = null;
  36675. this._uvs = null;
  36676. this._colors = null;
  36677. if (!this._updatable) {
  36678. this.particles.length = 0;
  36679. }
  36680. return mesh;
  36681. };
  36682. /**
  36683. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  36684. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  36685. * Thus the particles generated from `digest()` have their property `position` set yet.
  36686. * `mesh` ( Mesh ) is the mesh to be digested
  36687. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  36688. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  36689. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  36690. */
  36691. SolidParticleSystem.prototype.digest = function (mesh, options) {
  36692. var size = (options && options.facetNb) || 1;
  36693. var number = (options && options.number);
  36694. var delta = (options && options.delta) || 0;
  36695. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  36696. var meshInd = mesh.getIndices();
  36697. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  36698. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  36699. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  36700. var f = 0; // facet counter
  36701. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  36702. // compute size from number
  36703. if (number) {
  36704. number = (number > totalFacets) ? totalFacets : number;
  36705. size = Math.round(totalFacets / number);
  36706. delta = 0;
  36707. }
  36708. else {
  36709. size = (size > totalFacets) ? totalFacets : size;
  36710. }
  36711. var facetPos = []; // submesh positions
  36712. var facetInd = []; // submesh indices
  36713. var facetUV = []; // submesh UV
  36714. var facetCol = []; // submesh colors
  36715. var barycenter = BABYLON.Tmp.Vector3[0];
  36716. var rand;
  36717. var sizeO = size;
  36718. while (f < totalFacets) {
  36719. size = sizeO + Math.floor((1 + delta) * Math.random());
  36720. if (f > totalFacets - size) {
  36721. size = totalFacets - f;
  36722. }
  36723. // reset temp arrays
  36724. facetPos.length = 0;
  36725. facetInd.length = 0;
  36726. facetUV.length = 0;
  36727. facetCol.length = 0;
  36728. // iterate over "size" facets
  36729. var fi = 0;
  36730. for (var j = f * 3; j < (f + size) * 3; j++) {
  36731. facetInd.push(fi);
  36732. var i = meshInd[j];
  36733. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  36734. if (meshUV) {
  36735. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  36736. }
  36737. if (meshCol) {
  36738. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  36739. }
  36740. fi++;
  36741. }
  36742. // create a model shape for each single particle
  36743. var idx = this.nbParticles;
  36744. var shape = this._posToShape(facetPos);
  36745. var shapeUV = this._uvsToShapeUV(facetUV);
  36746. // compute the barycenter of the shape
  36747. var v;
  36748. for (v = 0; v < shape.length; v++) {
  36749. barycenter.addInPlace(shape[v]);
  36750. }
  36751. barycenter.scaleInPlace(1 / shape.length);
  36752. // shift the shape from its barycenter to the origin
  36753. for (v = 0; v < shape.length; v++) {
  36754. shape[v].subtractInPlace(barycenter);
  36755. }
  36756. var bInfo;
  36757. if (this._particlesIntersect) {
  36758. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  36759. }
  36760. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  36761. // add the particle in the SPS
  36762. var currentPos = this._positions.length;
  36763. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  36764. this._addParticle(idx, currentPos, modelShape, this._shapeCounter, 0, bInfo);
  36765. // initialize the particle position
  36766. this.particles[this.nbParticles].position.addInPlace(barycenter);
  36767. this._index += shape.length;
  36768. idx++;
  36769. this.nbParticles++;
  36770. this._shapeCounter++;
  36771. f += size;
  36772. }
  36773. return this;
  36774. };
  36775. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  36776. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  36777. var index = 0;
  36778. var idx = 0;
  36779. for (var p = 0; p < this.particles.length; p++) {
  36780. this._particle = this.particles[p];
  36781. this._shape = this._particle._model._shape;
  36782. if (this._particle.rotationQuaternion) {
  36783. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  36784. }
  36785. else {
  36786. this._yaw = this._particle.rotation.y;
  36787. this._pitch = this._particle.rotation.x;
  36788. this._roll = this._particle.rotation.z;
  36789. this._quaternionRotationYPR();
  36790. }
  36791. this._quaternionToRotationMatrix();
  36792. this._rotMatrix.invertToRef(this._invertMatrix);
  36793. for (var pt = 0; pt < this._shape.length; pt++) {
  36794. idx = index + pt * 3;
  36795. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  36796. this._fixedNormal32[idx] = this._normal.x;
  36797. this._fixedNormal32[idx + 1] = this._normal.y;
  36798. this._fixedNormal32[idx + 2] = this._normal.z;
  36799. }
  36800. index = idx + 3;
  36801. }
  36802. };
  36803. //reset copy
  36804. SolidParticleSystem.prototype._resetCopy = function () {
  36805. this._copy.position.x = 0;
  36806. this._copy.position.y = 0;
  36807. this._copy.position.z = 0;
  36808. this._copy.rotation.x = 0;
  36809. this._copy.rotation.y = 0;
  36810. this._copy.rotation.z = 0;
  36811. this._copy.rotationQuaternion = null;
  36812. this._copy.scaling.x = 1;
  36813. this._copy.scaling.y = 1;
  36814. this._copy.scaling.z = 1;
  36815. this._copy.uvs.x = 0;
  36816. this._copy.uvs.y = 0;
  36817. this._copy.uvs.z = 1;
  36818. this._copy.uvs.w = 1;
  36819. this._copy.color = null;
  36820. };
  36821. // _meshBuilder : inserts the shape model in the global SPS mesh
  36822. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  36823. var i;
  36824. var u = 0;
  36825. var c = 0;
  36826. var n = 0;
  36827. this._resetCopy();
  36828. if (options && options.positionFunction) {
  36829. options.positionFunction(this._copy, idx, idxInShape);
  36830. this._mustUnrotateFixedNormals = true;
  36831. }
  36832. if (this._copy.rotationQuaternion) {
  36833. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  36834. }
  36835. else {
  36836. this._yaw = this._copy.rotation.y;
  36837. this._pitch = this._copy.rotation.x;
  36838. this._roll = this._copy.rotation.z;
  36839. this._quaternionRotationYPR();
  36840. }
  36841. this._quaternionToRotationMatrix();
  36842. for (i = 0; i < shape.length; i++) {
  36843. this._vertex.x = shape[i].x;
  36844. this._vertex.y = shape[i].y;
  36845. this._vertex.z = shape[i].z;
  36846. if (options && options.vertexFunction) {
  36847. options.vertexFunction(this._copy, this._vertex, i);
  36848. }
  36849. this._vertex.x *= this._copy.scaling.x;
  36850. this._vertex.y *= this._copy.scaling.y;
  36851. this._vertex.z *= this._copy.scaling.z;
  36852. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  36853. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  36854. if (meshUV) {
  36855. 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);
  36856. u += 2;
  36857. }
  36858. if (this._copy.color) {
  36859. this._color = this._copy.color;
  36860. }
  36861. else if (meshCol && meshCol[c] !== undefined) {
  36862. this._color.r = meshCol[c];
  36863. this._color.g = meshCol[c + 1];
  36864. this._color.b = meshCol[c + 2];
  36865. this._color.a = meshCol[c + 3];
  36866. }
  36867. else {
  36868. this._color.r = 1;
  36869. this._color.g = 1;
  36870. this._color.b = 1;
  36871. this._color.a = 1;
  36872. }
  36873. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  36874. c += 4;
  36875. if (!this.recomputeNormals && meshNor) {
  36876. this._normal.x = meshNor[n];
  36877. this._normal.y = meshNor[n + 1];
  36878. this._normal.z = meshNor[n + 2];
  36879. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  36880. normals.push(this._normal.x, this._normal.y, this._normal.z);
  36881. n += 3;
  36882. }
  36883. }
  36884. for (i = 0; i < meshInd.length; i++) {
  36885. indices.push(p + meshInd[i]);
  36886. }
  36887. if (this._pickable) {
  36888. var nbfaces = meshInd.length / 3;
  36889. for (i = 0; i < nbfaces; i++) {
  36890. this.pickedParticles.push({ idx: idx, faceId: i });
  36891. }
  36892. }
  36893. return this._copy;
  36894. };
  36895. // returns a shape array from positions array
  36896. SolidParticleSystem.prototype._posToShape = function (positions) {
  36897. var shape = [];
  36898. for (var i = 0; i < positions.length; i += 3) {
  36899. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  36900. }
  36901. return shape;
  36902. };
  36903. // returns a shapeUV array from a Vector4 uvs
  36904. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  36905. var shapeUV = [];
  36906. if (uvs) {
  36907. for (var i = 0; i < uvs.length; i++)
  36908. shapeUV.push(uvs[i]);
  36909. }
  36910. return shapeUV;
  36911. };
  36912. // adds a new particle object in the particles array
  36913. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape, bInfo) {
  36914. var sp = new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape, this, bInfo);
  36915. this.particles.push(sp);
  36916. return sp;
  36917. };
  36918. /**
  36919. * Adds some particles to the SPS from the model shape. Returns the shape id.
  36920. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  36921. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  36922. * `nb` (positive integer) the number of particles to be created from this model
  36923. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  36924. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  36925. */
  36926. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  36927. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  36928. var meshInd = mesh.getIndices();
  36929. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  36930. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  36931. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  36932. var bbInfo;
  36933. if (this._particlesIntersect) {
  36934. bbInfo = mesh.getBoundingInfo();
  36935. }
  36936. var shape = this._posToShape(meshPos);
  36937. var shapeUV = this._uvsToShapeUV(meshUV);
  36938. var posfunc = options ? options.positionFunction : null;
  36939. var vtxfunc = options ? options.vertexFunction : null;
  36940. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  36941. // particles
  36942. var sp;
  36943. var currentCopy;
  36944. var idx = this.nbParticles;
  36945. for (var i = 0; i < nb; i++) {
  36946. var currentPos = this._positions.length;
  36947. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  36948. if (this._updatable) {
  36949. sp = this._addParticle(idx, currentPos, modelShape, this._shapeCounter, i, bbInfo);
  36950. sp.position.copyFrom(currentCopy.position);
  36951. sp.rotation.copyFrom(currentCopy.rotation);
  36952. if (currentCopy.rotationQuaternion) {
  36953. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  36954. }
  36955. if (currentCopy.color) {
  36956. sp.color.copyFrom(currentCopy.color);
  36957. }
  36958. sp.scaling.copyFrom(currentCopy.scaling);
  36959. sp.uvs.copyFrom(currentCopy.uvs);
  36960. }
  36961. this._index += shape.length;
  36962. idx++;
  36963. }
  36964. this.nbParticles += nb;
  36965. this._shapeCounter++;
  36966. return this._shapeCounter - 1;
  36967. };
  36968. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  36969. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  36970. this._resetCopy();
  36971. if (particle._model._positionFunction) {
  36972. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  36973. }
  36974. if (this._copy.rotationQuaternion) {
  36975. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  36976. }
  36977. else {
  36978. this._yaw = this._copy.rotation.y;
  36979. this._pitch = this._copy.rotation.x;
  36980. this._roll = this._copy.rotation.z;
  36981. this._quaternionRotationYPR();
  36982. }
  36983. this._quaternionToRotationMatrix();
  36984. this._shape = particle._model._shape;
  36985. for (var pt = 0; pt < this._shape.length; pt++) {
  36986. this._vertex.x = this._shape[pt].x;
  36987. this._vertex.y = this._shape[pt].y;
  36988. this._vertex.z = this._shape[pt].z;
  36989. if (particle._model._vertexFunction) {
  36990. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  36991. }
  36992. this._vertex.x *= this._copy.scaling.x;
  36993. this._vertex.y *= this._copy.scaling.y;
  36994. this._vertex.z *= this._copy.scaling.z;
  36995. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  36996. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  36997. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  36998. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  36999. }
  37000. particle.position.x = 0.0;
  37001. particle.position.y = 0.0;
  37002. particle.position.z = 0.0;
  37003. particle.rotation.x = 0.0;
  37004. particle.rotation.y = 0.0;
  37005. particle.rotation.z = 0.0;
  37006. particle.rotationQuaternion = null;
  37007. particle.scaling.x = 1.0;
  37008. particle.scaling.y = 1.0;
  37009. particle.scaling.z = 1.0;
  37010. };
  37011. /**
  37012. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  37013. * Returns the SPS.
  37014. */
  37015. SolidParticleSystem.prototype.rebuildMesh = function () {
  37016. for (var p = 0; p < this.particles.length; p++) {
  37017. this._rebuildParticle(this.particles[p]);
  37018. }
  37019. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  37020. return this;
  37021. };
  37022. /**
  37023. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  37024. * This method calls `updateParticle()` for each particle of the SPS.
  37025. * For an animated SPS, it is usually called within the render loop.
  37026. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  37027. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  37028. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  37029. * Returns the SPS.
  37030. */
  37031. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  37032. if (start === void 0) { start = 0; }
  37033. if (end === void 0) { end = this.nbParticles - 1; }
  37034. if (update === void 0) { update = true; }
  37035. if (!this._updatable) {
  37036. return;
  37037. }
  37038. // custom beforeUpdate
  37039. this.beforeUpdateParticles(start, end, update);
  37040. this._cam_axisX.x = 1.0;
  37041. this._cam_axisX.y = 0.0;
  37042. this._cam_axisX.z = 0.0;
  37043. this._cam_axisY.x = 0.0;
  37044. this._cam_axisY.y = 1.0;
  37045. this._cam_axisY.z = 0.0;
  37046. this._cam_axisZ.x = 0.0;
  37047. this._cam_axisZ.y = 0.0;
  37048. this._cam_axisZ.z = 1.0;
  37049. // if the particles will always face the camera
  37050. if (this.billboard) {
  37051. this.mesh.computeWorldMatrix(true);
  37052. // compute the camera position and un-rotate it by the current mesh rotation
  37053. if (this.mesh._worldMatrix.decompose(this._scale, this._quaternion, this._translation)) {
  37054. this._quaternionToRotationMatrix();
  37055. this._rotMatrix.invertToRef(this._invertMatrix);
  37056. this._camera._currentTarget.subtractToRef(this._camera.globalPosition, this._camDir);
  37057. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  37058. this._cam_axisZ.normalize();
  37059. // same for camera up vector extracted from the cam view matrix
  37060. var view = this._camera.getViewMatrix(true);
  37061. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  37062. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  37063. this._cam_axisY.normalize();
  37064. this._cam_axisX.normalize();
  37065. }
  37066. }
  37067. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  37068. var idx = 0; // current position index in the global array positions32
  37069. var index = 0; // position start index in the global array positions32 of the current particle
  37070. var colidx = 0; // current color index in the global array colors32
  37071. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  37072. var uvidx = 0; // current uv index in the global array uvs32
  37073. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  37074. var pt = 0; // current index in the particle model shape
  37075. if (this.mesh.isFacetDataEnabled) {
  37076. this._computeBoundingBox = true;
  37077. }
  37078. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  37079. if (this._computeBoundingBox) {
  37080. if (start == 0 && end == this.nbParticles - 1) {
  37081. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  37082. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  37083. }
  37084. else {
  37085. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  37086. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  37087. }
  37088. }
  37089. // particle loop
  37090. index = this.particles[start]._pos;
  37091. var vpos = (index / 3) | 0;
  37092. colorIndex = vpos * 4;
  37093. uvIndex = vpos * 2;
  37094. for (var p = start; p <= end; p++) {
  37095. this._particle = this.particles[p];
  37096. this._shape = this._particle._model._shape;
  37097. this._shapeUV = this._particle._model._shapeUV;
  37098. // call to custom user function to update the particle properties
  37099. this.updateParticle(this._particle);
  37100. if (this._particle.isVisible) {
  37101. // particle rotation matrix
  37102. if (this.billboard) {
  37103. this._particle.rotation.x = 0.0;
  37104. this._particle.rotation.y = 0.0;
  37105. }
  37106. if (this._computeParticleRotation || this.billboard) {
  37107. if (this._particle.rotationQuaternion) {
  37108. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  37109. }
  37110. else {
  37111. this._yaw = this._particle.rotation.y;
  37112. this._pitch = this._particle.rotation.x;
  37113. this._roll = this._particle.rotation.z;
  37114. this._quaternionRotationYPR();
  37115. }
  37116. this._quaternionToRotationMatrix();
  37117. }
  37118. // particle vertex loop
  37119. for (pt = 0; pt < this._shape.length; pt++) {
  37120. idx = index + pt * 3;
  37121. colidx = colorIndex + pt * 4;
  37122. uvidx = uvIndex + pt * 2;
  37123. this._vertex.x = this._shape[pt].x;
  37124. this._vertex.y = this._shape[pt].y;
  37125. this._vertex.z = this._shape[pt].z;
  37126. if (this._computeParticleVertex) {
  37127. this.updateParticleVertex(this._particle, this._vertex, pt);
  37128. }
  37129. // positions
  37130. this._vertex.x *= this._particle.scaling.x;
  37131. this._vertex.y *= this._particle.scaling.y;
  37132. this._vertex.z *= this._particle.scaling.z;
  37133. 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];
  37134. 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;
  37135. 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;
  37136. 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;
  37137. 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;
  37138. 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;
  37139. 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;
  37140. if (this._computeBoundingBox) {
  37141. if (this._positions32[idx] < this._minimum.x) {
  37142. this._minimum.x = this._positions32[idx];
  37143. }
  37144. if (this._positions32[idx] > this._maximum.x) {
  37145. this._maximum.x = this._positions32[idx];
  37146. }
  37147. if (this._positions32[idx + 1] < this._minimum.y) {
  37148. this._minimum.y = this._positions32[idx + 1];
  37149. }
  37150. if (this._positions32[idx + 1] > this._maximum.y) {
  37151. this._maximum.y = this._positions32[idx + 1];
  37152. }
  37153. if (this._positions32[idx + 2] < this._minimum.z) {
  37154. this._minimum.z = this._positions32[idx + 2];
  37155. }
  37156. if (this._positions32[idx + 2] > this._maximum.z) {
  37157. this._maximum.z = this._positions32[idx + 2];
  37158. }
  37159. }
  37160. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  37161. if (!this._computeParticleVertex) {
  37162. this._normal.x = this._fixedNormal32[idx];
  37163. this._normal.y = this._fixedNormal32[idx + 1];
  37164. this._normal.z = this._fixedNormal32[idx + 2];
  37165. 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]);
  37166. 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]);
  37167. 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]);
  37168. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  37169. 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;
  37170. 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;
  37171. }
  37172. if (this._computeParticleColor) {
  37173. this._colors32[colidx] = this._particle.color.r;
  37174. this._colors32[colidx + 1] = this._particle.color.g;
  37175. this._colors32[colidx + 2] = this._particle.color.b;
  37176. this._colors32[colidx + 3] = this._particle.color.a;
  37177. }
  37178. if (this._computeParticleTexture) {
  37179. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  37180. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  37181. }
  37182. }
  37183. }
  37184. else {
  37185. for (pt = 0; pt < this._shape.length; pt++) {
  37186. idx = index + pt * 3;
  37187. colidx = colorIndex + pt * 4;
  37188. uvidx = uvIndex + pt * 2;
  37189. this._positions32[idx] = this._camera.position.x;
  37190. this._positions32[idx + 1] = this._camera.position.y;
  37191. this._positions32[idx + 2] = this._camera.position.z;
  37192. this._normals32[idx] = 0.0;
  37193. this._normals32[idx + 1] = 0.0;
  37194. this._normals32[idx + 2] = 0.0;
  37195. if (this._computeParticleColor) {
  37196. this._colors32[colidx] = this._particle.color.r;
  37197. this._colors32[colidx + 1] = this._particle.color.g;
  37198. this._colors32[colidx + 2] = this._particle.color.b;
  37199. this._colors32[colidx + 3] = this._particle.color.a;
  37200. }
  37201. if (this._computeParticleTexture) {
  37202. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  37203. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  37204. }
  37205. }
  37206. }
  37207. // if the particle intersections must be computed : update the bbInfo
  37208. if (this._particlesIntersect) {
  37209. var bInfo = this._particle._boundingInfo;
  37210. var bBox = bInfo.boundingBox;
  37211. var bSphere = bInfo.boundingSphere;
  37212. if (!this._bSphereOnly) {
  37213. // place, scale and rotate the particle bbox within the SPS local system, then update it
  37214. for (var b = 0; b < bBox.vectors.length; b++) {
  37215. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  37216. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  37217. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  37218. 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];
  37219. 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;
  37220. 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;
  37221. 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;
  37222. 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;
  37223. 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;
  37224. 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;
  37225. }
  37226. bBox._update(this.mesh._worldMatrix);
  37227. }
  37228. // place and scale the particle bouding sphere in the SPS local system, then update it
  37229. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  37230. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  37231. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  37232. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  37233. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  37234. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  37235. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  37236. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  37237. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  37238. 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));
  37239. bSphere._update(this.mesh._worldMatrix);
  37240. }
  37241. // increment indexes for the next particle
  37242. index = idx + 3;
  37243. colorIndex = colidx + 4;
  37244. uvIndex = uvidx + 2;
  37245. }
  37246. // if the VBO must be updated
  37247. if (update) {
  37248. if (this._computeParticleColor) {
  37249. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  37250. }
  37251. if (this._computeParticleTexture) {
  37252. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  37253. }
  37254. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  37255. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  37256. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  37257. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  37258. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  37259. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32, params);
  37260. for (var i = 0; i < this._normals32.length; i++) {
  37261. this._fixedNormal32[i] = this._normals32[i];
  37262. }
  37263. }
  37264. if (!this.mesh.areNormalsFrozen) {
  37265. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  37266. }
  37267. }
  37268. }
  37269. if (this._computeBoundingBox) {
  37270. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  37271. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  37272. }
  37273. this.afterUpdateParticles(start, end, update);
  37274. return this;
  37275. };
  37276. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  37277. this._halfroll = this._roll * 0.5;
  37278. this._halfpitch = this._pitch * 0.5;
  37279. this._halfyaw = this._yaw * 0.5;
  37280. this._sinRoll = Math.sin(this._halfroll);
  37281. this._cosRoll = Math.cos(this._halfroll);
  37282. this._sinPitch = Math.sin(this._halfpitch);
  37283. this._cosPitch = Math.cos(this._halfpitch);
  37284. this._sinYaw = Math.sin(this._halfyaw);
  37285. this._cosYaw = Math.cos(this._halfyaw);
  37286. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  37287. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  37288. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  37289. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  37290. };
  37291. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  37292. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  37293. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  37294. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  37295. this._rotMatrix.m[3] = 0;
  37296. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  37297. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  37298. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  37299. this._rotMatrix.m[7] = 0;
  37300. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  37301. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  37302. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  37303. this._rotMatrix.m[11] = 0;
  37304. this._rotMatrix.m[12] = 0;
  37305. this._rotMatrix.m[13] = 0;
  37306. this._rotMatrix.m[14] = 0;
  37307. this._rotMatrix.m[15] = 1.0;
  37308. };
  37309. /**
  37310. * Disposes the SPS.
  37311. * Returns nothing.
  37312. */
  37313. SolidParticleSystem.prototype.dispose = function () {
  37314. this.mesh.dispose();
  37315. this.vars = null;
  37316. // drop references to internal big arrays for the GC
  37317. this._positions = null;
  37318. this._indices = null;
  37319. this._normals = null;
  37320. this._uvs = null;
  37321. this._colors = null;
  37322. this._positions32 = null;
  37323. this._normals32 = null;
  37324. this._fixedNormal32 = null;
  37325. this._uvs32 = null;
  37326. this._colors32 = null;
  37327. this.pickedParticles = null;
  37328. };
  37329. /**
  37330. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  37331. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  37332. * Returns the SPS.
  37333. */
  37334. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  37335. if (!this._isVisibilityBoxLocked) {
  37336. this.mesh.refreshBoundingInfo();
  37337. }
  37338. return this;
  37339. };
  37340. /**
  37341. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  37342. * @param size the size (float) of the visibility box
  37343. * note : this doesn't lock the SPS mesh bounding box.
  37344. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  37345. */
  37346. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  37347. var vis = size / 2;
  37348. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  37349. };
  37350. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  37351. // getter and setter
  37352. get: function () {
  37353. return this._alwaysVisible;
  37354. },
  37355. /**
  37356. * Sets the SPS as always visible or not
  37357. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  37358. */
  37359. set: function (val) {
  37360. this._alwaysVisible = val;
  37361. this.mesh.alwaysSelectAsActiveMesh = val;
  37362. },
  37363. enumerable: true,
  37364. configurable: true
  37365. });
  37366. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  37367. get: function () {
  37368. return this._isVisibilityBoxLocked;
  37369. },
  37370. /**
  37371. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  37372. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  37373. */
  37374. set: function (val) {
  37375. this._isVisibilityBoxLocked = val;
  37376. this.mesh.getBoundingInfo().isLocked = val;
  37377. },
  37378. enumerable: true,
  37379. configurable: true
  37380. });
  37381. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  37382. // getters
  37383. get: function () {
  37384. return this._computeParticleRotation;
  37385. },
  37386. // Optimizer setters
  37387. /**
  37388. * Tells to `setParticles()` to compute the particle rotations or not.
  37389. * Default value : true. The SPS is faster when it's set to false.
  37390. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  37391. */
  37392. set: function (val) {
  37393. this._computeParticleRotation = val;
  37394. },
  37395. enumerable: true,
  37396. configurable: true
  37397. });
  37398. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  37399. get: function () {
  37400. return this._computeParticleColor;
  37401. },
  37402. /**
  37403. * Tells to `setParticles()` to compute the particle colors or not.
  37404. * Default value : true. The SPS is faster when it's set to false.
  37405. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  37406. */
  37407. set: function (val) {
  37408. this._computeParticleColor = val;
  37409. },
  37410. enumerable: true,
  37411. configurable: true
  37412. });
  37413. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  37414. get: function () {
  37415. return this._computeParticleTexture;
  37416. },
  37417. /**
  37418. * Tells to `setParticles()` to compute the particle textures or not.
  37419. * Default value : true. The SPS is faster when it's set to false.
  37420. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  37421. */
  37422. set: function (val) {
  37423. this._computeParticleTexture = val;
  37424. },
  37425. enumerable: true,
  37426. configurable: true
  37427. });
  37428. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  37429. get: function () {
  37430. return this._computeParticleVertex;
  37431. },
  37432. /**
  37433. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  37434. * Default value : false. The SPS is faster when it's set to false.
  37435. * Note : the particle custom vertex positions aren't stored values.
  37436. */
  37437. set: function (val) {
  37438. this._computeParticleVertex = val;
  37439. },
  37440. enumerable: true,
  37441. configurable: true
  37442. });
  37443. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  37444. get: function () {
  37445. return this._computeBoundingBox;
  37446. },
  37447. /**
  37448. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  37449. */
  37450. set: function (val) {
  37451. this._computeBoundingBox = val;
  37452. },
  37453. enumerable: true,
  37454. configurable: true
  37455. });
  37456. // =======================================================================
  37457. // Particle behavior logic
  37458. // these following methods may be overwritten by the user to fit his needs
  37459. /**
  37460. * This function does nothing. It may be overwritten to set all the particle first values.
  37461. * The SPS doesn't call this function, you may have to call it by your own.
  37462. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  37463. */
  37464. SolidParticleSystem.prototype.initParticles = function () {
  37465. };
  37466. /**
  37467. * This function does nothing. It may be overwritten to recycle a particle.
  37468. * The SPS doesn't call this function, you may have to call it by your own.
  37469. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  37470. */
  37471. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  37472. return particle;
  37473. };
  37474. /**
  37475. * Updates a particle : this function should be overwritten by the user.
  37476. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  37477. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  37478. * ex : just set a particle position or velocity and recycle conditions
  37479. */
  37480. SolidParticleSystem.prototype.updateParticle = function (particle) {
  37481. return particle;
  37482. };
  37483. /**
  37484. * Updates a vertex of a particle : it can be overwritten by the user.
  37485. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  37486. * @param particle the current particle
  37487. * @param vertex the current index of the current particle
  37488. * @param pt the index of the current vertex in the particle shape
  37489. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  37490. * ex : just set a vertex particle position
  37491. */
  37492. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  37493. return vertex;
  37494. };
  37495. /**
  37496. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  37497. * This does nothing and may be overwritten by the user.
  37498. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  37499. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  37500. * @param update the boolean update value actually passed to setParticles()
  37501. */
  37502. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  37503. };
  37504. /**
  37505. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  37506. * This will be passed three parameters.
  37507. * This does nothing and may be overwritten by the user.
  37508. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  37509. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  37510. * @param update the boolean update value actually passed to setParticles()
  37511. */
  37512. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  37513. };
  37514. return SolidParticleSystem;
  37515. }());
  37516. BABYLON.SolidParticleSystem = SolidParticleSystem;
  37517. })(BABYLON || (BABYLON = {}));
  37518. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  37519. /// <reference path="babylon.mesh.ts" />
  37520. var BABYLON;
  37521. (function (BABYLON) {
  37522. var GroundMesh = (function (_super) {
  37523. __extends(GroundMesh, _super);
  37524. function GroundMesh(name, scene) {
  37525. var _this = _super.call(this, name, scene) || this;
  37526. _this.generateOctree = false;
  37527. _this._worldInverse = new BABYLON.Matrix();
  37528. return _this;
  37529. }
  37530. GroundMesh.prototype.getClassName = function () {
  37531. return "GroundMesh";
  37532. };
  37533. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  37534. get: function () {
  37535. return Math.min(this._subdivisionsX, this._subdivisionsY);
  37536. },
  37537. enumerable: true,
  37538. configurable: true
  37539. });
  37540. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  37541. get: function () {
  37542. return this._subdivisionsX;
  37543. },
  37544. enumerable: true,
  37545. configurable: true
  37546. });
  37547. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  37548. get: function () {
  37549. return this._subdivisionsY;
  37550. },
  37551. enumerable: true,
  37552. configurable: true
  37553. });
  37554. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  37555. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  37556. this._subdivisionsX = chunksCount;
  37557. this._subdivisionsY = chunksCount;
  37558. this.subdivide(chunksCount);
  37559. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  37560. };
  37561. /**
  37562. * Returns a height (y) value in the Worl system :
  37563. * the ground altitude at the coordinates (x, z) expressed in the World system.
  37564. * Returns the ground y position if (x, z) are outside the ground surface.
  37565. */
  37566. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  37567. var world = this.getWorldMatrix();
  37568. var invMat = BABYLON.Tmp.Matrix[5];
  37569. world.invertToRef(invMat);
  37570. var tmpVect = BABYLON.Tmp.Vector3[8];
  37571. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  37572. x = tmpVect.x;
  37573. z = tmpVect.z;
  37574. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  37575. return this.position.y;
  37576. }
  37577. if (!this._heightQuads || this._heightQuads.length == 0) {
  37578. this._initHeightQuads();
  37579. this._computeHeightQuads();
  37580. }
  37581. var facet = this._getFacetAt(x, z);
  37582. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  37583. // return y in the World system
  37584. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  37585. return tmpVect.y;
  37586. };
  37587. /**
  37588. * Returns a normalized vector (Vector3) orthogonal to the ground
  37589. * at the ground coordinates (x, z) expressed in the World system.
  37590. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  37591. */
  37592. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  37593. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  37594. this.getNormalAtCoordinatesToRef(x, z, normal);
  37595. return normal;
  37596. };
  37597. /**
  37598. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  37599. * at the ground coordinates (x, z) expressed in the World system.
  37600. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  37601. * Returns the GroundMesh.
  37602. */
  37603. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  37604. var world = this.getWorldMatrix();
  37605. var tmpMat = BABYLON.Tmp.Matrix[5];
  37606. world.invertToRef(tmpMat);
  37607. var tmpVect = BABYLON.Tmp.Vector3[8];
  37608. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  37609. x = tmpVect.x;
  37610. z = tmpVect.z;
  37611. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  37612. return this;
  37613. }
  37614. if (!this._heightQuads || this._heightQuads.length == 0) {
  37615. this._initHeightQuads();
  37616. this._computeHeightQuads();
  37617. }
  37618. var facet = this._getFacetAt(x, z);
  37619. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  37620. return this;
  37621. };
  37622. /**
  37623. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  37624. * if the ground has been updated.
  37625. * This can be used in the render loop.
  37626. * Returns the GroundMesh.
  37627. */
  37628. GroundMesh.prototype.updateCoordinateHeights = function () {
  37629. if (!this._heightQuads || this._heightQuads.length == 0) {
  37630. this._initHeightQuads();
  37631. }
  37632. this._computeHeightQuads();
  37633. return this;
  37634. };
  37635. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  37636. GroundMesh.prototype._getFacetAt = function (x, z) {
  37637. // retrieve col and row from x, z coordinates in the ground local system
  37638. var subdivisionsX = this._subdivisionsX;
  37639. var subdivisionsY = this._subdivisionsY;
  37640. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  37641. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  37642. var quad = this._heightQuads[row * this._subdivisionsX + col];
  37643. var facet;
  37644. if (z < quad.slope.x * x + quad.slope.y) {
  37645. facet = quad.facet1;
  37646. }
  37647. else {
  37648. facet = quad.facet2;
  37649. }
  37650. return facet;
  37651. };
  37652. // Creates and populates the heightMap array with "facet" elements :
  37653. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  37654. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  37655. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  37656. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  37657. // Returns the GroundMesh.
  37658. GroundMesh.prototype._initHeightQuads = function () {
  37659. var subdivisionsX = this._subdivisionsX;
  37660. var subdivisionsY = this._subdivisionsY;
  37661. this._heightQuads = new Array();
  37662. for (var row = 0; row < subdivisionsY; row++) {
  37663. for (var col = 0; col < subdivisionsX; col++) {
  37664. 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) };
  37665. this._heightQuads[row * subdivisionsX + col] = quad;
  37666. }
  37667. }
  37668. return this;
  37669. };
  37670. // Compute each quad element values and update the the heightMap array :
  37671. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  37672. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  37673. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  37674. // Returns the GroundMesh.
  37675. GroundMesh.prototype._computeHeightQuads = function () {
  37676. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37677. var v1 = BABYLON.Tmp.Vector3[3];
  37678. var v2 = BABYLON.Tmp.Vector3[2];
  37679. var v3 = BABYLON.Tmp.Vector3[1];
  37680. var v4 = BABYLON.Tmp.Vector3[0];
  37681. var v1v2 = BABYLON.Tmp.Vector3[4];
  37682. var v1v3 = BABYLON.Tmp.Vector3[5];
  37683. var v1v4 = BABYLON.Tmp.Vector3[6];
  37684. var norm1 = BABYLON.Tmp.Vector3[7];
  37685. var norm2 = BABYLON.Tmp.Vector3[8];
  37686. var i = 0;
  37687. var j = 0;
  37688. var k = 0;
  37689. var cd = 0; // 2D slope coefficient : z = cd * x + h
  37690. var h = 0;
  37691. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  37692. var d2 = 0;
  37693. var subdivisionsX = this._subdivisionsX;
  37694. var subdivisionsY = this._subdivisionsY;
  37695. for (var row = 0; row < subdivisionsY; row++) {
  37696. for (var col = 0; col < subdivisionsX; col++) {
  37697. i = col * 3;
  37698. j = row * (subdivisionsX + 1) * 3;
  37699. k = (row + 1) * (subdivisionsX + 1) * 3;
  37700. v1.x = positions[j + i];
  37701. v1.y = positions[j + i + 1];
  37702. v1.z = positions[j + i + 2];
  37703. v2.x = positions[j + i + 3];
  37704. v2.y = positions[j + i + 4];
  37705. v2.z = positions[j + i + 5];
  37706. v3.x = positions[k + i];
  37707. v3.y = positions[k + i + 1];
  37708. v3.z = positions[k + i + 2];
  37709. v4.x = positions[k + i + 3];
  37710. v4.y = positions[k + i + 4];
  37711. v4.z = positions[k + i + 5];
  37712. // 2D slope V1V4
  37713. cd = (v4.z - v1.z) / (v4.x - v1.x);
  37714. h = v1.z - cd * v1.x; // v1 belongs to the slope
  37715. // facet equations :
  37716. // we compute each facet normal vector
  37717. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  37718. // we compute the value d by applying the equation to v1 which belongs to the plane
  37719. // then we store the facet equation in a Vector4
  37720. v2.subtractToRef(v1, v1v2);
  37721. v3.subtractToRef(v1, v1v3);
  37722. v4.subtractToRef(v1, v1v4);
  37723. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  37724. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  37725. norm1.normalize();
  37726. norm2.normalize();
  37727. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  37728. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  37729. var quad = this._heightQuads[row * subdivisionsX + col];
  37730. quad.slope.copyFromFloats(cd, h);
  37731. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  37732. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  37733. }
  37734. }
  37735. return this;
  37736. };
  37737. GroundMesh.prototype.serialize = function (serializationObject) {
  37738. _super.prototype.serialize.call(this, serializationObject);
  37739. serializationObject.subdivisionsX = this._subdivisionsX;
  37740. serializationObject.subdivisionsY = this._subdivisionsY;
  37741. serializationObject.minX = this._minX;
  37742. serializationObject.maxX = this._maxX;
  37743. serializationObject.minZ = this._minZ;
  37744. serializationObject.maxZ = this._maxZ;
  37745. serializationObject.width = this._width;
  37746. serializationObject.height = this._height;
  37747. };
  37748. GroundMesh.Parse = function (parsedMesh, scene) {
  37749. var result = new GroundMesh(parsedMesh.name, scene);
  37750. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  37751. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  37752. result._minX = parsedMesh.minX;
  37753. result._maxX = parsedMesh.maxX;
  37754. result._minZ = parsedMesh.minZ;
  37755. result._maxZ = parsedMesh.maxZ;
  37756. result._width = parsedMesh.width;
  37757. result._height = parsedMesh.height;
  37758. return result;
  37759. };
  37760. return GroundMesh;
  37761. }(BABYLON.Mesh));
  37762. BABYLON.GroundMesh = GroundMesh;
  37763. })(BABYLON || (BABYLON = {}));
  37764. //# sourceMappingURL=babylon.groundMesh.js.map
  37765. var BABYLON;
  37766. (function (BABYLON) {
  37767. /**
  37768. * Creates an instance based on a source mesh.
  37769. */
  37770. var InstancedMesh = (function (_super) {
  37771. __extends(InstancedMesh, _super);
  37772. function InstancedMesh(name, source) {
  37773. var _this = _super.call(this, name, source.getScene()) || this;
  37774. source.instances.push(_this);
  37775. _this._sourceMesh = source;
  37776. _this.position.copyFrom(source.position);
  37777. _this.rotation.copyFrom(source.rotation);
  37778. _this.scaling.copyFrom(source.scaling);
  37779. if (source.rotationQuaternion) {
  37780. _this.rotationQuaternion = source.rotationQuaternion.clone();
  37781. }
  37782. _this.infiniteDistance = source.infiniteDistance;
  37783. _this.setPivotMatrix(source.getPivotMatrix());
  37784. _this.refreshBoundingInfo();
  37785. _this._syncSubMeshes();
  37786. return _this;
  37787. }
  37788. /**
  37789. * Returns the string "InstancedMesh".
  37790. */
  37791. InstancedMesh.prototype.getClassName = function () {
  37792. return "InstancedMesh";
  37793. };
  37794. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  37795. // Methods
  37796. get: function () {
  37797. return this._sourceMesh.receiveShadows;
  37798. },
  37799. enumerable: true,
  37800. configurable: true
  37801. });
  37802. Object.defineProperty(InstancedMesh.prototype, "material", {
  37803. get: function () {
  37804. return this._sourceMesh.material;
  37805. },
  37806. enumerable: true,
  37807. configurable: true
  37808. });
  37809. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  37810. get: function () {
  37811. return this._sourceMesh.visibility;
  37812. },
  37813. enumerable: true,
  37814. configurable: true
  37815. });
  37816. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  37817. get: function () {
  37818. return this._sourceMesh.skeleton;
  37819. },
  37820. enumerable: true,
  37821. configurable: true
  37822. });
  37823. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  37824. get: function () {
  37825. return this._sourceMesh.renderingGroupId;
  37826. },
  37827. enumerable: true,
  37828. configurable: true
  37829. });
  37830. /**
  37831. * Returns the total number of vertices (integer).
  37832. */
  37833. InstancedMesh.prototype.getTotalVertices = function () {
  37834. return this._sourceMesh.getTotalVertices();
  37835. };
  37836. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  37837. get: function () {
  37838. return this._sourceMesh;
  37839. },
  37840. enumerable: true,
  37841. configurable: true
  37842. });
  37843. /**
  37844. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  37845. */
  37846. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  37847. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  37848. };
  37849. /**
  37850. * Sets the vertex data of the mesh geometry for the requested `kind`.
  37851. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  37852. * The `data` are either a numeric array either a Float32Array.
  37853. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  37854. * 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).
  37855. * Note that a new underlying VertexBuffer object is created each call.
  37856. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  37857. *
  37858. * Possible `kind` values :
  37859. * - BABYLON.VertexBuffer.PositionKind
  37860. * - BABYLON.VertexBuffer.UVKind
  37861. * - BABYLON.VertexBuffer.UV2Kind
  37862. * - BABYLON.VertexBuffer.UV3Kind
  37863. * - BABYLON.VertexBuffer.UV4Kind
  37864. * - BABYLON.VertexBuffer.UV5Kind
  37865. * - BABYLON.VertexBuffer.UV6Kind
  37866. * - BABYLON.VertexBuffer.ColorKind
  37867. * - BABYLON.VertexBuffer.MatricesIndicesKind
  37868. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  37869. * - BABYLON.VertexBuffer.MatricesWeightsKind
  37870. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  37871. *
  37872. * Returns the Mesh.
  37873. */
  37874. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  37875. if (this.sourceMesh) {
  37876. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  37877. }
  37878. return this.sourceMesh;
  37879. };
  37880. /**
  37881. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  37882. * If the mesh has no geometry, it is simply returned as it is.
  37883. * The `data` are either a numeric array either a Float32Array.
  37884. * No new underlying VertexBuffer object is created.
  37885. * 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.
  37886. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  37887. *
  37888. * Possible `kind` values :
  37889. * - BABYLON.VertexBuffer.PositionKind
  37890. * - BABYLON.VertexBuffer.UVKind
  37891. * - BABYLON.VertexBuffer.UV2Kind
  37892. * - BABYLON.VertexBuffer.UV3Kind
  37893. * - BABYLON.VertexBuffer.UV4Kind
  37894. * - BABYLON.VertexBuffer.UV5Kind
  37895. * - BABYLON.VertexBuffer.UV6Kind
  37896. * - BABYLON.VertexBuffer.ColorKind
  37897. * - BABYLON.VertexBuffer.MatricesIndicesKind
  37898. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  37899. * - BABYLON.VertexBuffer.MatricesWeightsKind
  37900. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  37901. *
  37902. * Returns the Mesh.
  37903. */
  37904. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  37905. if (this.sourceMesh) {
  37906. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  37907. }
  37908. return this.sourceMesh;
  37909. };
  37910. /**
  37911. * Sets the mesh indices.
  37912. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  37913. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  37914. * This method creates a new index buffer each call.
  37915. * Returns the Mesh.
  37916. */
  37917. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  37918. if (this.sourceMesh) {
  37919. this.sourceMesh.setIndices(indices, totalVertices);
  37920. }
  37921. return this.sourceMesh;
  37922. };
  37923. /**
  37924. * Boolean : True if the mesh owns the requested kind of data.
  37925. */
  37926. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  37927. return this._sourceMesh.isVerticesDataPresent(kind);
  37928. };
  37929. /**
  37930. * Returns an array of indices (IndicesArray).
  37931. */
  37932. InstancedMesh.prototype.getIndices = function () {
  37933. return this._sourceMesh.getIndices();
  37934. };
  37935. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  37936. get: function () {
  37937. return this._sourceMesh._positions;
  37938. },
  37939. enumerable: true,
  37940. configurable: true
  37941. });
  37942. /**
  37943. * Sets a new updated BoundingInfo to the mesh.
  37944. * Returns the mesh.
  37945. */
  37946. InstancedMesh.prototype.refreshBoundingInfo = function () {
  37947. var meshBB = this._sourceMesh.getBoundingInfo();
  37948. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  37949. this._updateBoundingInfo();
  37950. return this;
  37951. };
  37952. InstancedMesh.prototype._preActivate = function () {
  37953. if (this._currentLOD) {
  37954. this._currentLOD._preActivate();
  37955. }
  37956. return this;
  37957. };
  37958. InstancedMesh.prototype._activate = function (renderId) {
  37959. if (this._currentLOD) {
  37960. this._currentLOD._registerInstanceForRenderId(this, renderId);
  37961. }
  37962. return this;
  37963. };
  37964. /**
  37965. * Returns the current associated LOD AbstractMesh.
  37966. */
  37967. InstancedMesh.prototype.getLOD = function (camera) {
  37968. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  37969. if (this._currentLOD === this.sourceMesh) {
  37970. return this;
  37971. }
  37972. return this._currentLOD;
  37973. };
  37974. InstancedMesh.prototype._syncSubMeshes = function () {
  37975. this.releaseSubMeshes();
  37976. if (this._sourceMesh.subMeshes) {
  37977. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  37978. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  37979. }
  37980. }
  37981. return this;
  37982. };
  37983. InstancedMesh.prototype._generatePointsArray = function () {
  37984. return this._sourceMesh._generatePointsArray();
  37985. };
  37986. /**
  37987. * Creates a new InstancedMesh from the current mesh.
  37988. * - name (string) : the cloned mesh name
  37989. * - newParent (optional Node) : the optional Node to parent the clone to.
  37990. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  37991. *
  37992. * Returns the clone.
  37993. */
  37994. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  37995. var result = this._sourceMesh.createInstance(name);
  37996. // Deep copy
  37997. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  37998. // Bounding info
  37999. this.refreshBoundingInfo();
  38000. // Parent
  38001. if (newParent) {
  38002. result.parent = newParent;
  38003. }
  38004. if (!doNotCloneChildren) {
  38005. // Children
  38006. for (var index = 0; index < this.getScene().meshes.length; index++) {
  38007. var mesh = this.getScene().meshes[index];
  38008. if (mesh.parent === this) {
  38009. mesh.clone(mesh.name, result);
  38010. }
  38011. }
  38012. }
  38013. result.computeWorldMatrix(true);
  38014. return result;
  38015. };
  38016. /**
  38017. * Disposes the InstancedMesh.
  38018. * Returns nothing.
  38019. */
  38020. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  38021. // Remove from mesh
  38022. var index = this._sourceMesh.instances.indexOf(this);
  38023. this._sourceMesh.instances.splice(index, 1);
  38024. _super.prototype.dispose.call(this, doNotRecurse);
  38025. };
  38026. return InstancedMesh;
  38027. }(BABYLON.AbstractMesh));
  38028. BABYLON.InstancedMesh = InstancedMesh;
  38029. })(BABYLON || (BABYLON = {}));
  38030. //# sourceMappingURL=babylon.instancedMesh.js.map
  38031. /// <reference path="babylon.mesh.ts" />
  38032. var BABYLON;
  38033. (function (BABYLON) {
  38034. var LinesMesh = (function (_super) {
  38035. __extends(LinesMesh, _super);
  38036. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor) {
  38037. if (parent === void 0) { parent = null; }
  38038. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  38039. _this.useVertexColor = useVertexColor;
  38040. _this.color = new BABYLON.Color3(1, 1, 1);
  38041. _this.alpha = 1;
  38042. if (source) {
  38043. _this.color = source.color.clone();
  38044. _this.alpha = source.alpha;
  38045. _this.useVertexColor = source.useVertexColor;
  38046. }
  38047. _this._intersectionThreshold = 0.1;
  38048. var options = {
  38049. attributes: [BABYLON.VertexBuffer.PositionKind],
  38050. uniforms: ["world", "viewProjection"],
  38051. needAlphaBlending: false,
  38052. };
  38053. if (!useVertexColor) {
  38054. options.uniforms.push("color");
  38055. options.needAlphaBlending = true;
  38056. }
  38057. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", options);
  38058. return _this;
  38059. }
  38060. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  38061. /**
  38062. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  38063. * This margin is expressed in world space coordinates, so its value may vary.
  38064. * Default value is 0.1
  38065. * @returns the intersection Threshold value.
  38066. */
  38067. get: function () {
  38068. return this._intersectionThreshold;
  38069. },
  38070. /**
  38071. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  38072. * This margin is expressed in world space coordinates, so its value may vary.
  38073. * @param value the new threshold to apply
  38074. */
  38075. set: function (value) {
  38076. if (this._intersectionThreshold === value) {
  38077. return;
  38078. }
  38079. this._intersectionThreshold = value;
  38080. if (this.geometry) {
  38081. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  38082. }
  38083. },
  38084. enumerable: true,
  38085. configurable: true
  38086. });
  38087. /**
  38088. * Returns the string "LineMesh"
  38089. */
  38090. LinesMesh.prototype.getClassName = function () {
  38091. return "LinesMesh";
  38092. };
  38093. Object.defineProperty(LinesMesh.prototype, "material", {
  38094. get: function () {
  38095. return this._colorShader;
  38096. },
  38097. enumerable: true,
  38098. configurable: true
  38099. });
  38100. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  38101. get: function () {
  38102. return false;
  38103. },
  38104. enumerable: true,
  38105. configurable: true
  38106. });
  38107. LinesMesh.prototype.createInstance = function (name) {
  38108. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  38109. return null;
  38110. };
  38111. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  38112. // VBOs
  38113. this._geometry._bind(this._colorShader.getEffect());
  38114. // Color
  38115. if (!this.useVertexColor) {
  38116. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  38117. }
  38118. return this;
  38119. };
  38120. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  38121. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  38122. return this;
  38123. }
  38124. var engine = this.getScene().getEngine();
  38125. // Draw order
  38126. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  38127. return this;
  38128. };
  38129. LinesMesh.prototype.dispose = function (doNotRecurse) {
  38130. this._colorShader.dispose();
  38131. _super.prototype.dispose.call(this, doNotRecurse);
  38132. };
  38133. /**
  38134. * Returns a new LineMesh object cloned from the current one.
  38135. */
  38136. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  38137. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  38138. };
  38139. return LinesMesh;
  38140. }(BABYLON.Mesh));
  38141. BABYLON.LinesMesh = LinesMesh;
  38142. })(BABYLON || (BABYLON = {}));
  38143. //# sourceMappingURL=babylon.linesMesh.js.map
  38144. var BABYLON;
  38145. (function (BABYLON) {
  38146. var ShaderMaterial = (function (_super) {
  38147. __extends(ShaderMaterial, _super);
  38148. function ShaderMaterial(name, scene, shaderPath, options) {
  38149. var _this = _super.call(this, name, scene) || this;
  38150. _this._textures = {};
  38151. _this._textureArrays = {};
  38152. _this._floats = {};
  38153. _this._floatsArrays = {};
  38154. _this._colors3 = {};
  38155. _this._colors4 = {};
  38156. _this._vectors2 = {};
  38157. _this._vectors3 = {};
  38158. _this._vectors4 = {};
  38159. _this._matrices = {};
  38160. _this._matrices3x3 = {};
  38161. _this._matrices2x2 = {};
  38162. _this._vectors3Arrays = {};
  38163. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  38164. _this._shaderPath = shaderPath;
  38165. options.needAlphaBlending = options.needAlphaBlending || false;
  38166. options.needAlphaTesting = options.needAlphaTesting || false;
  38167. options.attributes = options.attributes || ["position", "normal", "uv"];
  38168. options.uniforms = options.uniforms || ["worldViewProjection"];
  38169. options.uniformBuffers = options.uniformBuffers || [];
  38170. options.samplers = options.samplers || [];
  38171. options.defines = options.defines || [];
  38172. _this._options = options;
  38173. return _this;
  38174. }
  38175. ShaderMaterial.prototype.getClassName = function () {
  38176. return "ShaderMaterial";
  38177. };
  38178. ShaderMaterial.prototype.needAlphaBlending = function () {
  38179. return this._options.needAlphaBlending;
  38180. };
  38181. ShaderMaterial.prototype.needAlphaTesting = function () {
  38182. return this._options.needAlphaTesting;
  38183. };
  38184. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  38185. if (this._options.uniforms.indexOf(uniformName) === -1) {
  38186. this._options.uniforms.push(uniformName);
  38187. }
  38188. };
  38189. ShaderMaterial.prototype.setTexture = function (name, texture) {
  38190. if (this._options.samplers.indexOf(name) === -1) {
  38191. this._options.samplers.push(name);
  38192. }
  38193. this._textures[name] = texture;
  38194. return this;
  38195. };
  38196. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  38197. if (this._options.samplers.indexOf(name) === -1) {
  38198. this._options.samplers.push(name);
  38199. }
  38200. this._checkUniform(name);
  38201. this._textureArrays[name] = textures;
  38202. return this;
  38203. };
  38204. ShaderMaterial.prototype.setFloat = function (name, value) {
  38205. this._checkUniform(name);
  38206. this._floats[name] = value;
  38207. return this;
  38208. };
  38209. ShaderMaterial.prototype.setFloats = function (name, value) {
  38210. this._checkUniform(name);
  38211. this._floatsArrays[name] = value;
  38212. return this;
  38213. };
  38214. ShaderMaterial.prototype.setColor3 = function (name, value) {
  38215. this._checkUniform(name);
  38216. this._colors3[name] = value;
  38217. return this;
  38218. };
  38219. ShaderMaterial.prototype.setColor4 = function (name, value) {
  38220. this._checkUniform(name);
  38221. this._colors4[name] = value;
  38222. return this;
  38223. };
  38224. ShaderMaterial.prototype.setVector2 = function (name, value) {
  38225. this._checkUniform(name);
  38226. this._vectors2[name] = value;
  38227. return this;
  38228. };
  38229. ShaderMaterial.prototype.setVector3 = function (name, value) {
  38230. this._checkUniform(name);
  38231. this._vectors3[name] = value;
  38232. return this;
  38233. };
  38234. ShaderMaterial.prototype.setVector4 = function (name, value) {
  38235. this._checkUniform(name);
  38236. this._vectors4[name] = value;
  38237. return this;
  38238. };
  38239. ShaderMaterial.prototype.setMatrix = function (name, value) {
  38240. this._checkUniform(name);
  38241. this._matrices[name] = value;
  38242. return this;
  38243. };
  38244. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  38245. this._checkUniform(name);
  38246. this._matrices3x3[name] = value;
  38247. return this;
  38248. };
  38249. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  38250. this._checkUniform(name);
  38251. this._matrices2x2[name] = value;
  38252. return this;
  38253. };
  38254. ShaderMaterial.prototype.setArray3 = function (name, value) {
  38255. this._checkUniform(name);
  38256. this._vectors3Arrays[name] = value;
  38257. return this;
  38258. };
  38259. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  38260. if (!mesh) {
  38261. return true;
  38262. }
  38263. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  38264. return false;
  38265. }
  38266. return false;
  38267. };
  38268. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  38269. var scene = this.getScene();
  38270. var engine = scene.getEngine();
  38271. if (!this.checkReadyOnEveryCall) {
  38272. if (this._renderId === scene.getRenderId()) {
  38273. if (this._checkCache(scene, mesh, useInstances)) {
  38274. return true;
  38275. }
  38276. }
  38277. }
  38278. // Instances
  38279. var defines = [];
  38280. var attribs = [];
  38281. var fallbacks = new BABYLON.EffectFallbacks();
  38282. if (useInstances) {
  38283. defines.push("#define INSTANCES");
  38284. }
  38285. for (var index = 0; index < this._options.defines.length; index++) {
  38286. defines.push(this._options.defines[index]);
  38287. }
  38288. for (var index = 0; index < this._options.attributes.length; index++) {
  38289. attribs.push(this._options.attributes[index]);
  38290. }
  38291. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  38292. attribs.push(BABYLON.VertexBuffer.ColorKind);
  38293. defines.push("#define VERTEXCOLOR");
  38294. }
  38295. // Bones
  38296. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  38297. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  38298. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  38299. if (mesh.numBoneInfluencers > 4) {
  38300. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  38301. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  38302. }
  38303. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  38304. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  38305. fallbacks.addCPUSkinningFallback(0, mesh);
  38306. }
  38307. else {
  38308. defines.push("#define NUM_BONE_INFLUENCERS 0");
  38309. }
  38310. // Textures
  38311. for (var name in this._textures) {
  38312. if (!this._textures[name].isReady()) {
  38313. return false;
  38314. }
  38315. }
  38316. // Alpha test
  38317. if (engine.getAlphaTesting()) {
  38318. defines.push("#define ALPHATEST");
  38319. }
  38320. var previousEffect = this._effect;
  38321. var join = defines.join("\n");
  38322. this._effect = engine.createEffect(this._shaderPath, {
  38323. attributes: attribs,
  38324. uniformsNames: this._options.uniforms,
  38325. uniformBuffersNames: this._options.uniformBuffers,
  38326. samplers: this._options.samplers,
  38327. defines: join,
  38328. fallbacks: fallbacks,
  38329. onCompiled: this.onCompiled,
  38330. onError: this.onError
  38331. }, engine);
  38332. if (!this._effect.isReady()) {
  38333. return false;
  38334. }
  38335. if (previousEffect !== this._effect) {
  38336. scene.resetCachedMaterial();
  38337. }
  38338. this._renderId = scene.getRenderId();
  38339. return true;
  38340. };
  38341. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  38342. var scene = this.getScene();
  38343. if (this._options.uniforms.indexOf("world") !== -1) {
  38344. this._effect.setMatrix("world", world);
  38345. }
  38346. if (this._options.uniforms.indexOf("worldView") !== -1) {
  38347. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  38348. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  38349. }
  38350. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  38351. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  38352. }
  38353. };
  38354. ShaderMaterial.prototype.bind = function (world, mesh) {
  38355. // Std values
  38356. this.bindOnlyWorldMatrix(world);
  38357. if (this.getScene().getCachedMaterial() !== this) {
  38358. if (this._options.uniforms.indexOf("view") !== -1) {
  38359. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  38360. }
  38361. if (this._options.uniforms.indexOf("projection") !== -1) {
  38362. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  38363. }
  38364. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  38365. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  38366. }
  38367. // Bones
  38368. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  38369. var name;
  38370. // Texture
  38371. for (name in this._textures) {
  38372. this._effect.setTexture(name, this._textures[name]);
  38373. }
  38374. // Texture arrays
  38375. for (name in this._textureArrays) {
  38376. this._effect.setTextureArray(name, this._textureArrays[name]);
  38377. }
  38378. // Float
  38379. for (name in this._floats) {
  38380. this._effect.setFloat(name, this._floats[name]);
  38381. }
  38382. // Float s
  38383. for (name in this._floatsArrays) {
  38384. this._effect.setArray(name, this._floatsArrays[name]);
  38385. }
  38386. // Color3
  38387. for (name in this._colors3) {
  38388. this._effect.setColor3(name, this._colors3[name]);
  38389. }
  38390. // Color4
  38391. for (name in this._colors4) {
  38392. var color = this._colors4[name];
  38393. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  38394. }
  38395. // Vector2
  38396. for (name in this._vectors2) {
  38397. this._effect.setVector2(name, this._vectors2[name]);
  38398. }
  38399. // Vector3
  38400. for (name in this._vectors3) {
  38401. this._effect.setVector3(name, this._vectors3[name]);
  38402. }
  38403. // Vector4
  38404. for (name in this._vectors4) {
  38405. this._effect.setVector4(name, this._vectors4[name]);
  38406. }
  38407. // Matrix
  38408. for (name in this._matrices) {
  38409. this._effect.setMatrix(name, this._matrices[name]);
  38410. }
  38411. // Matrix 3x3
  38412. for (name in this._matrices3x3) {
  38413. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  38414. }
  38415. // Matrix 2x2
  38416. for (name in this._matrices2x2) {
  38417. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  38418. }
  38419. // Vector3Array
  38420. for (name in this._vectors3Arrays) {
  38421. this._effect.setArray3(name, this._vectors3Arrays[name]);
  38422. }
  38423. }
  38424. this._afterBind(mesh);
  38425. };
  38426. ShaderMaterial.prototype.clone = function (name) {
  38427. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  38428. return newShaderMaterial;
  38429. };
  38430. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  38431. if (forceDisposeTextures) {
  38432. var name;
  38433. for (name in this._textures) {
  38434. this._textures[name].dispose();
  38435. }
  38436. for (name in this._textureArrays) {
  38437. var array = this._textureArrays[name];
  38438. for (var index = 0; index < array.length; index++) {
  38439. array[index].dispose();
  38440. }
  38441. }
  38442. }
  38443. this._textures = {};
  38444. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  38445. };
  38446. ShaderMaterial.prototype.serialize = function () {
  38447. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  38448. serializationObject.customType = "BABYLON.ShaderMaterial";
  38449. serializationObject.options = this._options;
  38450. serializationObject.shaderPath = this._shaderPath;
  38451. var name;
  38452. // Texture
  38453. serializationObject.textures = {};
  38454. for (name in this._textures) {
  38455. serializationObject.textures[name] = this._textures[name].serialize();
  38456. }
  38457. // Texture arrays
  38458. serializationObject.textureArrays = {};
  38459. for (name in this._textureArrays) {
  38460. serializationObject.textureArrays[name] = [];
  38461. var array = this._textureArrays[name];
  38462. for (var index = 0; index < array.length; index++) {
  38463. serializationObject.textureArrays[name].push(array[index].serialize());
  38464. }
  38465. }
  38466. // Float
  38467. serializationObject.floats = {};
  38468. for (name in this._floats) {
  38469. serializationObject.floats[name] = this._floats[name];
  38470. }
  38471. // Float s
  38472. serializationObject.floatArrays = {};
  38473. for (name in this._floatsArrays) {
  38474. serializationObject.floatArrays[name] = this._floatsArrays[name];
  38475. }
  38476. // Color3
  38477. serializationObject.colors3 = {};
  38478. for (name in this._colors3) {
  38479. serializationObject.colors3[name] = this._colors3[name].asArray();
  38480. }
  38481. // Color4
  38482. serializationObject.colors4 = {};
  38483. for (name in this._colors4) {
  38484. serializationObject.colors4[name] = this._colors4[name].asArray();
  38485. }
  38486. // Vector2
  38487. serializationObject.vectors2 = {};
  38488. for (name in this._vectors2) {
  38489. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  38490. }
  38491. // Vector3
  38492. serializationObject.vectors3 = {};
  38493. for (name in this._vectors3) {
  38494. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  38495. }
  38496. // Vector4
  38497. serializationObject.vectors4 = {};
  38498. for (name in this._vectors4) {
  38499. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  38500. }
  38501. // Matrix
  38502. serializationObject.matrices = {};
  38503. for (name in this._matrices) {
  38504. serializationObject.matrices[name] = this._matrices[name].asArray();
  38505. }
  38506. // Matrix 3x3
  38507. serializationObject.matrices3x3 = {};
  38508. for (name in this._matrices3x3) {
  38509. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  38510. }
  38511. // Matrix 2x2
  38512. serializationObject.matrices2x2 = {};
  38513. for (name in this._matrices2x2) {
  38514. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  38515. }
  38516. // Vector3Array
  38517. serializationObject.vectors3Arrays = {};
  38518. for (name in this._vectors3Arrays) {
  38519. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  38520. }
  38521. return serializationObject;
  38522. };
  38523. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  38524. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  38525. var name;
  38526. // Texture
  38527. for (name in source.textures) {
  38528. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  38529. }
  38530. // Texture arrays
  38531. for (name in source.textureArrays) {
  38532. var array = source.textureArrays[name];
  38533. var textureArray = new Array();
  38534. for (var index = 0; index < array.length; index++) {
  38535. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  38536. }
  38537. material.setTextureArray(name, textureArray);
  38538. }
  38539. // Float
  38540. for (name in source.floats) {
  38541. material.setFloat(name, source.floats[name]);
  38542. }
  38543. // Float s
  38544. for (name in source.floatsArrays) {
  38545. material.setFloats(name, source.floatsArrays[name]);
  38546. }
  38547. // Color3
  38548. for (name in source.colors3) {
  38549. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  38550. }
  38551. // Color4
  38552. for (name in source.colors4) {
  38553. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  38554. }
  38555. // Vector2
  38556. for (name in source.vectors2) {
  38557. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  38558. }
  38559. // Vector3
  38560. for (name in source.vectors3) {
  38561. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  38562. }
  38563. // Vector4
  38564. for (name in source.vectors4) {
  38565. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  38566. }
  38567. // Matrix
  38568. for (name in source.matrices) {
  38569. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  38570. }
  38571. // Matrix 3x3
  38572. for (name in source.matrices3x3) {
  38573. material.setMatrix3x3(name, source.matrices3x3[name]);
  38574. }
  38575. // Matrix 2x2
  38576. for (name in source.matrices2x2) {
  38577. material.setMatrix2x2(name, source.matrices2x2[name]);
  38578. }
  38579. // Vector3Array
  38580. for (name in source.vectors3Arrays) {
  38581. material.setArray3(name, source.vectors3Arrays[name]);
  38582. }
  38583. return material;
  38584. };
  38585. return ShaderMaterial;
  38586. }(BABYLON.Material));
  38587. BABYLON.ShaderMaterial = ShaderMaterial;
  38588. })(BABYLON || (BABYLON = {}));
  38589. //# sourceMappingURL=babylon.shaderMaterial.js.map
  38590. var BABYLON;
  38591. (function (BABYLON) {
  38592. var MeshBuilder = (function () {
  38593. function MeshBuilder() {
  38594. }
  38595. MeshBuilder.updateSideOrientation = function (orientation, scene) {
  38596. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  38597. return BABYLON.Mesh.DOUBLESIDE;
  38598. }
  38599. if (orientation === undefined || orientation === null) {
  38600. return BABYLON.Mesh.FRONTSIDE;
  38601. }
  38602. return orientation;
  38603. };
  38604. /**
  38605. * Creates a box mesh.
  38606. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  38607. * The parameter `size` sets the size (float) of each box side (default 1).
  38608. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  38609. * 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).
  38610. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  38611. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38612. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  38613. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  38614. */
  38615. MeshBuilder.CreateBox = function (name, options, scene) {
  38616. var box = new BABYLON.Mesh(name, scene);
  38617. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  38618. box.sideOrientation = options.sideOrientation;
  38619. var vertexData = BABYLON.VertexData.CreateBox(options);
  38620. vertexData.applyToMesh(box, options.updatable);
  38621. return box;
  38622. };
  38623. /**
  38624. * Creates a sphere mesh.
  38625. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  38626. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  38627. * 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`).
  38628. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  38629. * 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
  38630. * 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).
  38631. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38632. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  38633. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  38634. */
  38635. MeshBuilder.CreateSphere = function (name, options, scene) {
  38636. var sphere = new BABYLON.Mesh(name, scene);
  38637. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  38638. sphere.sideOrientation = options.sideOrientation;
  38639. var vertexData = BABYLON.VertexData.CreateSphere(options);
  38640. vertexData.applyToMesh(sphere, options.updatable);
  38641. return sphere;
  38642. };
  38643. /**
  38644. * Creates a plane polygonal mesh. By default, this is a disc.
  38645. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  38646. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  38647. * 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.
  38648. * 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
  38649. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38650. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  38651. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  38652. */
  38653. MeshBuilder.CreateDisc = function (name, options, scene) {
  38654. var disc = new BABYLON.Mesh(name, scene);
  38655. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  38656. disc.sideOrientation = options.sideOrientation;
  38657. var vertexData = BABYLON.VertexData.CreateDisc(options);
  38658. vertexData.applyToMesh(disc, options.updatable);
  38659. return disc;
  38660. };
  38661. /**
  38662. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  38663. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  38664. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  38665. * 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`).
  38666. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  38667. * 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.
  38668. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38669. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  38670. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  38671. */
  38672. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  38673. var sphere = new BABYLON.Mesh(name, scene);
  38674. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  38675. sphere.sideOrientation = options.sideOrientation;
  38676. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  38677. vertexData.applyToMesh(sphere, options.updatable);
  38678. return sphere;
  38679. };
  38680. ;
  38681. /**
  38682. * Creates a ribbon mesh.
  38683. * 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.
  38684. *
  38685. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  38686. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  38687. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  38688. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  38689. * 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.
  38690. * 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.
  38691. * 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
  38692. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38693. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  38694. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  38695. * 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.
  38696. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  38697. * 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
  38698. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  38699. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  38700. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  38701. */
  38702. MeshBuilder.CreateRibbon = function (name, options, scene) {
  38703. var pathArray = options.pathArray;
  38704. var closeArray = options.closeArray;
  38705. var closePath = options.closePath;
  38706. var offset = options.offset;
  38707. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  38708. var instance = options.instance;
  38709. var updatable = options.updatable;
  38710. if (instance) {
  38711. // positionFunction : ribbon case
  38712. // only pathArray and sideOrientation parameters are taken into account for positions update
  38713. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  38714. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  38715. var positionFunction = function (positions) {
  38716. var minlg = pathArray[0].length;
  38717. var i = 0;
  38718. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  38719. for (var si = 1; si <= ns; si++) {
  38720. for (var p = 0; p < pathArray.length; p++) {
  38721. var path = pathArray[p];
  38722. var l = path.length;
  38723. minlg = (minlg < l) ? minlg : l;
  38724. var j = 0;
  38725. while (j < minlg) {
  38726. positions[i] = path[j].x;
  38727. positions[i + 1] = path[j].y;
  38728. positions[i + 2] = path[j].z;
  38729. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  38730. BABYLON.Tmp.Vector3[0].x = path[j].x;
  38731. }
  38732. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  38733. BABYLON.Tmp.Vector3[1].x = path[j].x;
  38734. }
  38735. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  38736. BABYLON.Tmp.Vector3[0].y = path[j].y;
  38737. }
  38738. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  38739. BABYLON.Tmp.Vector3[1].y = path[j].y;
  38740. }
  38741. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  38742. BABYLON.Tmp.Vector3[0].z = path[j].z;
  38743. }
  38744. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  38745. BABYLON.Tmp.Vector3[1].z = path[j].z;
  38746. }
  38747. j++;
  38748. i += 3;
  38749. }
  38750. if (instance._closePath) {
  38751. positions[i] = path[0].x;
  38752. positions[i + 1] = path[0].y;
  38753. positions[i + 2] = path[0].z;
  38754. i += 3;
  38755. }
  38756. }
  38757. }
  38758. };
  38759. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38760. positionFunction(positions);
  38761. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  38762. instance._boundingInfo.update(instance._worldMatrix);
  38763. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  38764. if (options.colors) {
  38765. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  38766. for (var c = 0; c < options.colors.length; c++) {
  38767. colors[c * 4] = options.colors[c].r;
  38768. colors[c * 4 + 1] = options.colors[c].g;
  38769. colors[c * 4 + 2] = options.colors[c].b;
  38770. colors[c * 4 + 3] = options.colors[c].a;
  38771. }
  38772. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  38773. }
  38774. if (options.uvs) {
  38775. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  38776. for (var i = 0; i < options.uvs.length; i++) {
  38777. uvs[i * 2] = options.uvs[i].x;
  38778. uvs[i * 2 + 1] = options.uvs[i].y;
  38779. }
  38780. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  38781. }
  38782. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  38783. var indices = instance.getIndices();
  38784. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  38785. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  38786. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  38787. if (instance._closePath) {
  38788. var indexFirst = 0;
  38789. var indexLast = 0;
  38790. for (var p = 0; p < pathArray.length; p++) {
  38791. indexFirst = instance._idx[p] * 3;
  38792. if (p + 1 < pathArray.length) {
  38793. indexLast = (instance._idx[p + 1] - 1) * 3;
  38794. }
  38795. else {
  38796. indexLast = normals.length - 3;
  38797. }
  38798. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  38799. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  38800. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  38801. normals[indexLast] = normals[indexFirst];
  38802. normals[indexLast + 1] = normals[indexFirst + 1];
  38803. normals[indexLast + 2] = normals[indexFirst + 2];
  38804. }
  38805. }
  38806. if (!(instance.areNormalsFrozen)) {
  38807. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  38808. }
  38809. }
  38810. return instance;
  38811. }
  38812. else {
  38813. var ribbon = new BABYLON.Mesh(name, scene);
  38814. ribbon.sideOrientation = sideOrientation;
  38815. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  38816. if (closePath) {
  38817. ribbon._idx = vertexData._idx;
  38818. }
  38819. ribbon._closePath = closePath;
  38820. ribbon._closeArray = closeArray;
  38821. vertexData.applyToMesh(ribbon, updatable);
  38822. return ribbon;
  38823. }
  38824. };
  38825. /**
  38826. * Creates a cylinder or a cone mesh.
  38827. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  38828. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  38829. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  38830. * 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.
  38831. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  38832. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  38833. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  38834. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  38835. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  38836. * 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).
  38837. * 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
  38838. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  38839. * 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
  38840. * 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.
  38841. * If `enclose` is false, a ring surface is one element.
  38842. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  38843. * 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
  38844. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38845. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  38846. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  38847. */
  38848. MeshBuilder.CreateCylinder = function (name, options, scene) {
  38849. var cylinder = new BABYLON.Mesh(name, scene);
  38850. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  38851. cylinder.sideOrientation = options.sideOrientation;
  38852. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  38853. vertexData.applyToMesh(cylinder, options.updatable);
  38854. return cylinder;
  38855. };
  38856. /**
  38857. * Creates a torus mesh.
  38858. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  38859. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  38860. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  38861. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  38862. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38863. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  38864. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  38865. */
  38866. MeshBuilder.CreateTorus = function (name, options, scene) {
  38867. var torus = new BABYLON.Mesh(name, scene);
  38868. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  38869. torus.sideOrientation = options.sideOrientation;
  38870. var vertexData = BABYLON.VertexData.CreateTorus(options);
  38871. vertexData.applyToMesh(torus, options.updatable);
  38872. return torus;
  38873. };
  38874. /**
  38875. * Creates a torus knot mesh.
  38876. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  38877. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  38878. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  38879. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  38880. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  38881. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38882. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  38883. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  38884. */
  38885. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  38886. var torusKnot = new BABYLON.Mesh(name, scene);
  38887. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  38888. torusKnot.sideOrientation = options.sideOrientation;
  38889. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  38890. vertexData.applyToMesh(torusKnot, options.updatable);
  38891. return torusKnot;
  38892. };
  38893. /**
  38894. * Creates a line system mesh.
  38895. * A line system is a pool of many lines gathered in a single mesh.
  38896. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  38897. * 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.
  38898. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  38899. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  38900. * 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
  38901. * 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
  38902. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  38903. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  38904. */
  38905. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  38906. var instance = options.instance;
  38907. var lines = options.lines;
  38908. if (instance) {
  38909. var positionFunction = function (positions) {
  38910. var i = 0;
  38911. for (var l = 0; l < lines.length; l++) {
  38912. var points = lines[l];
  38913. for (var p = 0; p < points.length; p++) {
  38914. positions[i] = points[p].x;
  38915. positions[i + 1] = points[p].y;
  38916. positions[i + 2] = points[p].z;
  38917. i += 3;
  38918. }
  38919. }
  38920. };
  38921. instance.updateMeshPositions(positionFunction, false);
  38922. return instance;
  38923. }
  38924. // line system creation
  38925. var lineSystem = new BABYLON.LinesMesh(name, scene);
  38926. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  38927. vertexData.applyToMesh(lineSystem, options.updatable);
  38928. return lineSystem;
  38929. };
  38930. /**
  38931. * Creates a line mesh.
  38932. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  38933. * 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.
  38934. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  38935. * The parameter `points` is an array successive Vector3.
  38936. * 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
  38937. * When updating an instance, remember that only point positions can change, not the number of points.
  38938. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  38939. */
  38940. MeshBuilder.CreateLines = function (name, options, scene) {
  38941. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  38942. return lines;
  38943. };
  38944. /**
  38945. * Creates a dashed line mesh.
  38946. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  38947. * 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.
  38948. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  38949. * The parameter `points` is an array successive Vector3.
  38950. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  38951. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  38952. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  38953. * 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
  38954. * When updating an instance, remember that only point positions can change, not the number of points.
  38955. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  38956. */
  38957. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  38958. var points = options.points;
  38959. var instance = options.instance;
  38960. var gapSize = options.gapSize;
  38961. var dashNb = options.dashNb;
  38962. var dashSize = options.dashSize;
  38963. if (instance) {
  38964. var positionFunction = function (positions) {
  38965. var curvect = BABYLON.Vector3.Zero();
  38966. var nbSeg = positions.length / 6;
  38967. var lg = 0;
  38968. var nb = 0;
  38969. var shft = 0;
  38970. var dashshft = 0;
  38971. var curshft = 0;
  38972. var p = 0;
  38973. var i = 0;
  38974. var j = 0;
  38975. for (i = 0; i < points.length - 1; i++) {
  38976. points[i + 1].subtractToRef(points[i], curvect);
  38977. lg += curvect.length();
  38978. }
  38979. shft = lg / nbSeg;
  38980. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  38981. for (i = 0; i < points.length - 1; i++) {
  38982. points[i + 1].subtractToRef(points[i], curvect);
  38983. nb = Math.floor(curvect.length() / shft);
  38984. curvect.normalize();
  38985. j = 0;
  38986. while (j < nb && p < positions.length) {
  38987. curshft = shft * j;
  38988. positions[p] = points[i].x + curshft * curvect.x;
  38989. positions[p + 1] = points[i].y + curshft * curvect.y;
  38990. positions[p + 2] = points[i].z + curshft * curvect.z;
  38991. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  38992. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  38993. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  38994. p += 6;
  38995. j++;
  38996. }
  38997. }
  38998. while (p < positions.length) {
  38999. positions[p] = points[i].x;
  39000. positions[p + 1] = points[i].y;
  39001. positions[p + 2] = points[i].z;
  39002. p += 3;
  39003. }
  39004. };
  39005. instance.updateMeshPositions(positionFunction, false);
  39006. return instance;
  39007. }
  39008. // dashed lines creation
  39009. var dashedLines = new BABYLON.LinesMesh(name, scene);
  39010. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  39011. vertexData.applyToMesh(dashedLines, options.updatable);
  39012. dashedLines.dashSize = dashSize;
  39013. dashedLines.gapSize = gapSize;
  39014. return dashedLines;
  39015. };
  39016. /**
  39017. * Creates an extruded shape mesh.
  39018. * 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.
  39019. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  39020. *
  39021. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  39022. * 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
  39023. * extruded along the Z axis.
  39024. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  39025. * 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.
  39026. * The parameter `scale` (float, default 1) is the value to scale the shape.
  39027. * 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
  39028. * 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
  39029. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  39030. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39031. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39032. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  39033. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39034. */
  39035. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  39036. var path = options.path;
  39037. var shape = options.shape;
  39038. var scale = options.scale || 1;
  39039. var rotation = options.rotation || 0;
  39040. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  39041. var updatable = options.updatable;
  39042. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39043. var instance = options.instance;
  39044. var invertUV = options.invertUV || false;
  39045. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance, invertUV);
  39046. };
  39047. /**
  39048. * Creates an custom extruded shape mesh.
  39049. * 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.
  39050. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  39051. *
  39052. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  39053. * 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
  39054. * extruded along the Z axis.
  39055. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  39056. * 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
  39057. * and the distance of this point from the begining of the path :
  39058. * ```javascript
  39059. * var rotationFunction = function(i, distance) {
  39060. * // do things
  39061. * return rotationValue; }
  39062. * ```
  39063. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  39064. * 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
  39065. * and the distance of this point from the begining of the path :
  39066. * ```javascript
  39067. * var scaleFunction = function(i, distance) {
  39068. * // do things
  39069. * return scaleValue;}
  39070. * ```
  39071. * It must returns a float value that will be the scale value applied to the shape on each path point.
  39072. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  39073. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  39074. * 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
  39075. * 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
  39076. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  39077. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39078. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39079. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  39080. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39081. */
  39082. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  39083. var path = options.path;
  39084. var shape = options.shape;
  39085. var scaleFunction = options.scaleFunction || (function () { return 1; });
  39086. var rotationFunction = options.rotationFunction || (function () { return 0; });
  39087. var ribbonCloseArray = options.ribbonCloseArray || false;
  39088. var ribbonClosePath = options.ribbonClosePath || false;
  39089. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  39090. var updatable = options.updatable;
  39091. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39092. var instance = options.instance;
  39093. var invertUV = options.invertUV || false;
  39094. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance, invertUV);
  39095. };
  39096. /**
  39097. * Creates lathe mesh.
  39098. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  39099. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  39100. *
  39101. * 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
  39102. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  39103. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  39104. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  39105. * 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.
  39106. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  39107. * 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
  39108. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39109. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39110. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  39111. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39112. */
  39113. MeshBuilder.CreateLathe = function (name, options, scene) {
  39114. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  39115. var closed = (options.closed === undefined) ? true : options.closed;
  39116. var shape = options.shape;
  39117. var radius = options.radius || 1;
  39118. var tessellation = options.tessellation || 64;
  39119. var updatable = options.updatable;
  39120. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39121. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  39122. var pi2 = Math.PI * 2;
  39123. var paths = new Array();
  39124. var invertUV = options.invertUV || false;
  39125. var i = 0;
  39126. var p = 0;
  39127. var step = pi2 / tessellation * arc;
  39128. var rotated;
  39129. var path = new Array();
  39130. ;
  39131. for (i = 0; i <= tessellation; i++) {
  39132. var path = [];
  39133. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  39134. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  39135. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  39136. }
  39137. for (p = 0; p < shape.length; p++) {
  39138. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  39139. path.push(rotated);
  39140. }
  39141. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  39142. 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));
  39143. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  39144. }
  39145. paths.push(path);
  39146. }
  39147. // lathe ribbon
  39148. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV }, scene);
  39149. return lathe;
  39150. };
  39151. /**
  39152. * Creates a plane mesh.
  39153. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  39154. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  39155. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  39156. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  39157. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39158. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39159. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39160. */
  39161. MeshBuilder.CreatePlane = function (name, options, scene) {
  39162. var plane = new BABYLON.Mesh(name, scene);
  39163. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39164. plane.sideOrientation = options.sideOrientation;
  39165. var vertexData = BABYLON.VertexData.CreatePlane(options);
  39166. vertexData.applyToMesh(plane, options.updatable);
  39167. if (options.sourcePlane) {
  39168. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  39169. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  39170. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  39171. plane.rotate(vectorProduct, product);
  39172. }
  39173. return plane;
  39174. };
  39175. /**
  39176. * Creates a ground mesh.
  39177. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  39178. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  39179. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  39180. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39181. */
  39182. MeshBuilder.CreateGround = function (name, options, scene) {
  39183. var ground = new BABYLON.GroundMesh(name, scene);
  39184. ground._setReady(false);
  39185. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  39186. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  39187. ground._width = options.width || 1;
  39188. ground._height = options.height || 1;
  39189. ground._maxX = ground._width / 2;
  39190. ground._maxZ = ground._height / 2;
  39191. ground._minX = -ground._maxX;
  39192. ground._minZ = -ground._maxZ;
  39193. var vertexData = BABYLON.VertexData.CreateGround(options);
  39194. vertexData.applyToMesh(ground, options.updatable);
  39195. ground._setReady(true);
  39196. return ground;
  39197. };
  39198. /**
  39199. * Creates a tiled ground mesh.
  39200. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  39201. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  39202. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  39203. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  39204. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  39205. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  39206. * numbers of subdivisions on the ground width and height of each tile.
  39207. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39208. */
  39209. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  39210. var tiledGround = new BABYLON.Mesh(name, scene);
  39211. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  39212. vertexData.applyToMesh(tiledGround, options.updatable);
  39213. return tiledGround;
  39214. };
  39215. /**
  39216. * Creates a ground mesh from a height map.
  39217. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  39218. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  39219. * The parameter `url` sets the URL of the height map image resource.
  39220. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  39221. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  39222. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  39223. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  39224. * 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.
  39225. * 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).
  39226. * This function is passed the newly built mesh :
  39227. * ```javascript
  39228. * function(mesh) { // do things
  39229. * return; }
  39230. * ```
  39231. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39232. */
  39233. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  39234. var width = options.width || 10.0;
  39235. var height = options.height || 10.0;
  39236. var subdivisions = options.subdivisions || 1 | 0;
  39237. var minHeight = options.minHeight || 0.0;
  39238. var maxHeight = options.maxHeight || 10.0;
  39239. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  39240. var updatable = options.updatable;
  39241. var onReady = options.onReady;
  39242. var ground = new BABYLON.GroundMesh(name, scene);
  39243. ground._subdivisionsX = subdivisions;
  39244. ground._subdivisionsY = subdivisions;
  39245. ground._width = width;
  39246. ground._height = height;
  39247. ground._maxX = ground._width / 2.0;
  39248. ground._maxZ = ground._height / 2.0;
  39249. ground._minX = -ground._maxX;
  39250. ground._minZ = -ground._maxZ;
  39251. ground._setReady(false);
  39252. var onload = function (img) {
  39253. // Getting height map data
  39254. var canvas = document.createElement("canvas");
  39255. var context = canvas.getContext("2d");
  39256. var bufferWidth = img.width;
  39257. var bufferHeight = img.height;
  39258. canvas.width = bufferWidth;
  39259. canvas.height = bufferHeight;
  39260. context.drawImage(img, 0, 0);
  39261. // Create VertexData from map data
  39262. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  39263. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  39264. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  39265. width: width, height: height,
  39266. subdivisions: subdivisions,
  39267. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  39268. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  39269. });
  39270. vertexData.applyToMesh(ground, updatable);
  39271. ground._setReady(true);
  39272. //execute ready callback, if set
  39273. if (onReady) {
  39274. onReady(ground);
  39275. }
  39276. };
  39277. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  39278. return ground;
  39279. };
  39280. /**
  39281. * Creates a tube mesh.
  39282. * 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.
  39283. *
  39284. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  39285. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  39286. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  39287. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  39288. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  39289. * 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.
  39290. * It must return a radius value (positive float) :
  39291. * ```javascript
  39292. * var radiusFunction = function(i, distance) {
  39293. * // do things
  39294. * return radius; }
  39295. * ```
  39296. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  39297. * 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
  39298. * 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
  39299. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39300. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39301. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  39302. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39303. */
  39304. MeshBuilder.CreateTube = function (name, options, scene) {
  39305. var path = options.path;
  39306. var radius = options.radius || 1.0;
  39307. var tessellation = options.tessellation || 64 | 0;
  39308. var radiusFunction = options.radiusFunction;
  39309. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  39310. var invertUV = options.invertUV || false;
  39311. var updatable = options.updatable;
  39312. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39313. var instance = options.instance;
  39314. options.arc = (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  39315. // tube geometry
  39316. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  39317. var tangents = path3D.getTangents();
  39318. var normals = path3D.getNormals();
  39319. var distances = path3D.getDistances();
  39320. var pi2 = Math.PI * 2;
  39321. var step = pi2 / tessellation * arc;
  39322. var returnRadius = function () { return radius; };
  39323. var radiusFunctionFinal = radiusFunction || returnRadius;
  39324. var circlePath;
  39325. var rad;
  39326. var normal;
  39327. var rotated;
  39328. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  39329. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  39330. for (var i = 0; i < path.length; i++) {
  39331. rad = radiusFunctionFinal(i, distances[i]); // current radius
  39332. circlePath = Array(); // current circle array
  39333. normal = normals[i]; // current normal
  39334. for (var t = 0; t < tessellation; t++) {
  39335. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  39336. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  39337. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  39338. rotated.scaleInPlace(rad).addInPlace(path[i]);
  39339. circlePath[t] = rotated;
  39340. }
  39341. circlePaths[index] = circlePath;
  39342. index++;
  39343. }
  39344. // cap
  39345. var capPath = function (nbPoints, pathIndex) {
  39346. var pointCap = Array();
  39347. for (var i = 0; i < nbPoints; i++) {
  39348. pointCap.push(path[pathIndex]);
  39349. }
  39350. return pointCap;
  39351. };
  39352. switch (cap) {
  39353. case BABYLON.Mesh.NO_CAP:
  39354. break;
  39355. case BABYLON.Mesh.CAP_START:
  39356. circlePaths[0] = capPath(tessellation, 0);
  39357. circlePaths[1] = circlePaths[2].slice(0);
  39358. break;
  39359. case BABYLON.Mesh.CAP_END:
  39360. circlePaths[index] = circlePaths[index - 1].slice(0);
  39361. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  39362. break;
  39363. case BABYLON.Mesh.CAP_ALL:
  39364. circlePaths[0] = capPath(tessellation, 0);
  39365. circlePaths[1] = circlePaths[2].slice(0);
  39366. circlePaths[index] = circlePaths[index - 1].slice(0);
  39367. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  39368. break;
  39369. default:
  39370. break;
  39371. }
  39372. return circlePaths;
  39373. };
  39374. var path3D;
  39375. var pathArray;
  39376. if (instance) {
  39377. var arc = options.arc || instance.arc;
  39378. path3D = (instance.path3D).update(path);
  39379. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  39380. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  39381. instance.path3D = path3D;
  39382. instance.pathArray = pathArray;
  39383. instance.arc = arc;
  39384. return instance;
  39385. }
  39386. // tube creation
  39387. path3D = new BABYLON.Path3D(path);
  39388. var newPathArray = new Array();
  39389. cap = (cap < 0 || cap > 3) ? 0 : cap;
  39390. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  39391. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV }, scene);
  39392. tube.pathArray = pathArray;
  39393. tube.path3D = path3D;
  39394. tube.tessellation = tessellation;
  39395. tube.cap = cap;
  39396. tube.arc = options.arc;
  39397. return tube;
  39398. };
  39399. /**
  39400. * Creates a polyhedron mesh.
  39401. *
  39402. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  39403. * 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
  39404. * to choose the wanted type.
  39405. * The parameter `size` (positive float, default 1) sets the polygon size.
  39406. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  39407. * 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`.
  39408. * 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
  39409. * 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)`).
  39410. * 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
  39411. * 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.
  39412. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39413. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39414. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39415. */
  39416. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  39417. var polyhedron = new BABYLON.Mesh(name, scene);
  39418. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39419. polyhedron.sideOrientation = options.sideOrientation;
  39420. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  39421. vertexData.applyToMesh(polyhedron, options.updatable);
  39422. return polyhedron;
  39423. };
  39424. /**
  39425. * Creates a decal mesh.
  39426. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  39427. * 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.
  39428. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  39429. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  39430. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  39431. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  39432. */
  39433. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  39434. var indices = sourceMesh.getIndices();
  39435. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39436. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  39437. var position = options.position || BABYLON.Vector3.Zero();
  39438. var normal = options.normal || BABYLON.Vector3.Up();
  39439. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  39440. var angle = options.angle || 0;
  39441. // Getting correct rotation
  39442. if (!normal) {
  39443. var target = new BABYLON.Vector3(0, 0, 1);
  39444. var camera = sourceMesh.getScene().activeCamera;
  39445. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  39446. normal = camera.globalPosition.subtract(cameraWorldTarget);
  39447. }
  39448. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  39449. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  39450. var pitch = Math.atan2(normal.y, len);
  39451. // Matrix
  39452. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  39453. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  39454. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  39455. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  39456. var vertexData = new BABYLON.VertexData();
  39457. vertexData.indices = [];
  39458. vertexData.positions = [];
  39459. vertexData.normals = [];
  39460. vertexData.uvs = [];
  39461. var currentVertexDataIndex = 0;
  39462. var extractDecalVector3 = function (indexId) {
  39463. var vertexId = indices[indexId];
  39464. var result = new BABYLON.PositionNormalVertex();
  39465. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  39466. // Send vector to decal local world
  39467. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  39468. // Get normal
  39469. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  39470. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  39471. return result;
  39472. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  39473. var clip = function (vertices, axis) {
  39474. if (vertices.length === 0) {
  39475. return vertices;
  39476. }
  39477. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  39478. var clipVertices = function (v0, v1) {
  39479. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  39480. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  39481. };
  39482. var result = new Array();
  39483. for (var index = 0; index < vertices.length; index += 3) {
  39484. var v1Out;
  39485. var v2Out;
  39486. var v3Out;
  39487. var total = 0;
  39488. var nV1, nV2, nV3, nV4;
  39489. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  39490. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  39491. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  39492. v1Out = d1 > 0;
  39493. v2Out = d2 > 0;
  39494. v3Out = d3 > 0;
  39495. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  39496. switch (total) {
  39497. case 0:
  39498. result.push(vertices[index]);
  39499. result.push(vertices[index + 1]);
  39500. result.push(vertices[index + 2]);
  39501. break;
  39502. case 1:
  39503. if (v1Out) {
  39504. nV1 = vertices[index + 1];
  39505. nV2 = vertices[index + 2];
  39506. nV3 = clipVertices(vertices[index], nV1);
  39507. nV4 = clipVertices(vertices[index], nV2);
  39508. }
  39509. if (v2Out) {
  39510. nV1 = vertices[index];
  39511. nV2 = vertices[index + 2];
  39512. nV3 = clipVertices(vertices[index + 1], nV1);
  39513. nV4 = clipVertices(vertices[index + 1], nV2);
  39514. result.push(nV3);
  39515. result.push(nV2.clone());
  39516. result.push(nV1.clone());
  39517. result.push(nV2.clone());
  39518. result.push(nV3.clone());
  39519. result.push(nV4);
  39520. break;
  39521. }
  39522. if (v3Out) {
  39523. nV1 = vertices[index];
  39524. nV2 = vertices[index + 1];
  39525. nV3 = clipVertices(vertices[index + 2], nV1);
  39526. nV4 = clipVertices(vertices[index + 2], nV2);
  39527. }
  39528. result.push(nV1.clone());
  39529. result.push(nV2.clone());
  39530. result.push(nV3);
  39531. result.push(nV4);
  39532. result.push(nV3.clone());
  39533. result.push(nV2.clone());
  39534. break;
  39535. case 2:
  39536. if (!v1Out) {
  39537. nV1 = vertices[index].clone();
  39538. nV2 = clipVertices(nV1, vertices[index + 1]);
  39539. nV3 = clipVertices(nV1, vertices[index + 2]);
  39540. result.push(nV1);
  39541. result.push(nV2);
  39542. result.push(nV3);
  39543. }
  39544. if (!v2Out) {
  39545. nV1 = vertices[index + 1].clone();
  39546. nV2 = clipVertices(nV1, vertices[index + 2]);
  39547. nV3 = clipVertices(nV1, vertices[index]);
  39548. result.push(nV1);
  39549. result.push(nV2);
  39550. result.push(nV3);
  39551. }
  39552. if (!v3Out) {
  39553. nV1 = vertices[index + 2].clone();
  39554. nV2 = clipVertices(nV1, vertices[index]);
  39555. nV3 = clipVertices(nV1, vertices[index + 1]);
  39556. result.push(nV1);
  39557. result.push(nV2);
  39558. result.push(nV3);
  39559. }
  39560. break;
  39561. case 3:
  39562. break;
  39563. }
  39564. }
  39565. return result;
  39566. };
  39567. for (var index = 0; index < indices.length; index += 3) {
  39568. var faceVertices = new Array();
  39569. faceVertices.push(extractDecalVector3(index));
  39570. faceVertices.push(extractDecalVector3(index + 1));
  39571. faceVertices.push(extractDecalVector3(index + 2));
  39572. // Clip
  39573. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  39574. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  39575. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  39576. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  39577. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  39578. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  39579. if (faceVertices.length === 0) {
  39580. continue;
  39581. }
  39582. // Add UVs and get back to world
  39583. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  39584. var vertex = faceVertices[vIndex];
  39585. //TODO check for Int32Array | Uint32Array | Uint16Array
  39586. vertexData.indices.push(currentVertexDataIndex);
  39587. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  39588. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  39589. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  39590. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  39591. currentVertexDataIndex++;
  39592. }
  39593. }
  39594. // Return mesh
  39595. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  39596. vertexData.applyToMesh(decal);
  39597. decal.position = position.clone();
  39598. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  39599. return decal;
  39600. };
  39601. // Privates
  39602. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV) {
  39603. // extrusion geometry
  39604. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  39605. var tangents = path3D.getTangents();
  39606. var normals = path3D.getNormals();
  39607. var binormals = path3D.getBinormals();
  39608. var distances = path3D.getDistances();
  39609. var angle = 0;
  39610. var returnScale = function () { return scale; };
  39611. var returnRotation = function () { return rotation; };
  39612. var rotate = custom ? rotateFunction : returnRotation;
  39613. var scl = custom ? scaleFunction : returnScale;
  39614. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  39615. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  39616. for (var i = 0; i < curve.length; i++) {
  39617. var shapePath = new Array();
  39618. var angleStep = rotate(i, distances[i]);
  39619. var scaleRatio = scl(i, distances[i]);
  39620. for (var p = 0; p < shape.length; p++) {
  39621. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  39622. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  39623. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  39624. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  39625. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  39626. shapePath[p] = rotated;
  39627. }
  39628. shapePaths[index] = shapePath;
  39629. angle += angleStep;
  39630. index++;
  39631. }
  39632. // cap
  39633. var capPath = function (shapePath) {
  39634. var pointCap = Array();
  39635. var barycenter = BABYLON.Vector3.Zero();
  39636. var i;
  39637. for (i = 0; i < shapePath.length; i++) {
  39638. barycenter.addInPlace(shapePath[i]);
  39639. }
  39640. barycenter.scaleInPlace(1.0 / shapePath.length);
  39641. for (i = 0; i < shapePath.length; i++) {
  39642. pointCap.push(barycenter);
  39643. }
  39644. return pointCap;
  39645. };
  39646. switch (cap) {
  39647. case BABYLON.Mesh.NO_CAP:
  39648. break;
  39649. case BABYLON.Mesh.CAP_START:
  39650. shapePaths[0] = capPath(shapePaths[2]);
  39651. shapePaths[1] = shapePaths[2];
  39652. break;
  39653. case BABYLON.Mesh.CAP_END:
  39654. shapePaths[index] = shapePaths[index - 1];
  39655. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  39656. break;
  39657. case BABYLON.Mesh.CAP_ALL:
  39658. shapePaths[0] = capPath(shapePaths[2]);
  39659. shapePaths[1] = shapePaths[2];
  39660. shapePaths[index] = shapePaths[index - 1];
  39661. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  39662. break;
  39663. default:
  39664. break;
  39665. }
  39666. return shapePaths;
  39667. };
  39668. var path3D;
  39669. var pathArray;
  39670. if (instance) {
  39671. path3D = (instance.path3D).update(curve);
  39672. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  39673. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, scene, null, null, instance);
  39674. return instance;
  39675. }
  39676. // extruded shape creation
  39677. path3D = new BABYLON.Path3D(curve);
  39678. var newShapePaths = new Array();
  39679. cap = (cap < 0 || cap > 3) ? 0 : cap;
  39680. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  39681. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV }, scene);
  39682. extrudedGeneric.pathArray = pathArray;
  39683. extrudedGeneric.path3D = path3D;
  39684. extrudedGeneric.cap = cap;
  39685. return extrudedGeneric;
  39686. };
  39687. return MeshBuilder;
  39688. }());
  39689. BABYLON.MeshBuilder = MeshBuilder;
  39690. })(BABYLON || (BABYLON = {}));
  39691. //# sourceMappingURL=babylon.meshBuilder.js.map
  39692. var BABYLON;
  39693. (function (BABYLON) {
  39694. var AudioEngine = (function () {
  39695. function AudioEngine() {
  39696. this._audioContext = null;
  39697. this._audioContextInitialized = false;
  39698. this.canUseWebAudio = false;
  39699. this.WarnedWebAudioUnsupported = false;
  39700. this.unlocked = false;
  39701. this.isMP3supported = false;
  39702. this.isOGGsupported = false;
  39703. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  39704. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  39705. this.canUseWebAudio = true;
  39706. }
  39707. var audioElem = document.createElement('audio');
  39708. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  39709. this.isMP3supported = true;
  39710. }
  39711. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  39712. this.isOGGsupported = true;
  39713. }
  39714. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  39715. this._unlockiOSaudio();
  39716. }
  39717. else {
  39718. this.unlocked = true;
  39719. }
  39720. }
  39721. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  39722. get: function () {
  39723. if (!this._audioContextInitialized) {
  39724. this._initializeAudioContext();
  39725. }
  39726. return this._audioContext;
  39727. },
  39728. enumerable: true,
  39729. configurable: true
  39730. });
  39731. AudioEngine.prototype._unlockiOSaudio = function () {
  39732. var _this = this;
  39733. var unlockaudio = function () {
  39734. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  39735. var source = _this.audioContext.createBufferSource();
  39736. source.buffer = buffer;
  39737. source.connect(_this.audioContext.destination);
  39738. source.start(0);
  39739. setTimeout(function () {
  39740. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  39741. _this.unlocked = true;
  39742. window.removeEventListener('touchend', unlockaudio, false);
  39743. if (_this.onAudioUnlocked) {
  39744. _this.onAudioUnlocked();
  39745. }
  39746. }
  39747. }, 0);
  39748. };
  39749. window.addEventListener('touchend', unlockaudio, false);
  39750. };
  39751. AudioEngine.prototype._initializeAudioContext = function () {
  39752. try {
  39753. if (this.canUseWebAudio) {
  39754. this._audioContext = new AudioContext();
  39755. // create a global volume gain node
  39756. this.masterGain = this._audioContext.createGain();
  39757. this.masterGain.gain.value = 1;
  39758. this.masterGain.connect(this._audioContext.destination);
  39759. this._audioContextInitialized = true;
  39760. }
  39761. }
  39762. catch (e) {
  39763. this.canUseWebAudio = false;
  39764. BABYLON.Tools.Error("Web Audio: " + e.message);
  39765. }
  39766. };
  39767. AudioEngine.prototype.dispose = function () {
  39768. if (this.canUseWebAudio && this._audioContextInitialized) {
  39769. if (this._connectedAnalyser) {
  39770. this._connectedAnalyser.stopDebugCanvas();
  39771. this._connectedAnalyser.dispose();
  39772. this.masterGain.disconnect();
  39773. this.masterGain.connect(this._audioContext.destination);
  39774. this._connectedAnalyser = null;
  39775. }
  39776. this.masterGain.gain.value = 1;
  39777. }
  39778. this.WarnedWebAudioUnsupported = false;
  39779. };
  39780. AudioEngine.prototype.getGlobalVolume = function () {
  39781. if (this.canUseWebAudio && this._audioContextInitialized) {
  39782. return this.masterGain.gain.value;
  39783. }
  39784. else {
  39785. return -1;
  39786. }
  39787. };
  39788. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  39789. if (this.canUseWebAudio && this._audioContextInitialized) {
  39790. this.masterGain.gain.value = newVolume;
  39791. }
  39792. };
  39793. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  39794. if (this._connectedAnalyser) {
  39795. this._connectedAnalyser.stopDebugCanvas();
  39796. }
  39797. if (this.canUseWebAudio && this._audioContextInitialized) {
  39798. this._connectedAnalyser = analyser;
  39799. this.masterGain.disconnect();
  39800. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  39801. }
  39802. };
  39803. return AudioEngine;
  39804. }());
  39805. BABYLON.AudioEngine = AudioEngine;
  39806. })(BABYLON || (BABYLON = {}));
  39807. //# sourceMappingURL=babylon.audioEngine.js.map
  39808. var BABYLON;
  39809. (function (BABYLON) {
  39810. var Sound = (function () {
  39811. /**
  39812. * Create a sound and attach it to a scene
  39813. * @param name Name of your sound
  39814. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  39815. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  39816. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  39817. */
  39818. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  39819. var _this = this;
  39820. this.autoplay = false;
  39821. this.loop = false;
  39822. this.useCustomAttenuation = false;
  39823. this.spatialSound = false;
  39824. this.refDistance = 1;
  39825. this.rolloffFactor = 1;
  39826. this.maxDistance = 100;
  39827. this.distanceModel = "linear";
  39828. this._panningModel = "equalpower";
  39829. this._playbackRate = 1;
  39830. this._streaming = false;
  39831. this._startTime = 0;
  39832. this._startOffset = 0;
  39833. this._position = BABYLON.Vector3.Zero();
  39834. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  39835. this._volume = 1;
  39836. this._isLoaded = false;
  39837. this._isReadyToPlay = false;
  39838. this.isPlaying = false;
  39839. this.isPaused = false;
  39840. this._isDirectional = false;
  39841. // Used if you'd like to create a directional sound.
  39842. // If not set, the sound will be omnidirectional
  39843. this._coneInnerAngle = 360;
  39844. this._coneOuterAngle = 360;
  39845. this._coneOuterGain = 0;
  39846. this._isOutputConnected = false;
  39847. this._urlType = "Unknown";
  39848. this.name = name;
  39849. this._scene = scene;
  39850. this._readyToPlayCallback = readyToPlayCallback;
  39851. // Default custom attenuation function is a linear attenuation
  39852. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  39853. if (currentDistance < maxDistance) {
  39854. return currentVolume * (1 - currentDistance / maxDistance);
  39855. }
  39856. else {
  39857. return 0;
  39858. }
  39859. };
  39860. if (options) {
  39861. this.autoplay = options.autoplay || false;
  39862. this.loop = options.loop || false;
  39863. // if volume === 0, we need another way to check this option
  39864. if (options.volume !== undefined) {
  39865. this._volume = options.volume;
  39866. }
  39867. this.spatialSound = options.spatialSound || false;
  39868. this.maxDistance = options.maxDistance || 100;
  39869. this.useCustomAttenuation = options.useCustomAttenuation || false;
  39870. this.rolloffFactor = options.rolloffFactor || 1;
  39871. this.refDistance = options.refDistance || 1;
  39872. this.distanceModel = options.distanceModel || "linear";
  39873. this._playbackRate = options.playbackRate || 1;
  39874. this._streaming = options.streaming || false;
  39875. }
  39876. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  39877. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  39878. this._soundGain.gain.value = this._volume;
  39879. this._inputAudioNode = this._soundGain;
  39880. this._ouputAudioNode = this._soundGain;
  39881. if (this.spatialSound) {
  39882. this._createSpatialParameters();
  39883. }
  39884. this._scene.mainSoundTrack.AddSound(this);
  39885. var validParameter = true;
  39886. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  39887. if (urlOrArrayBuffer) {
  39888. if (typeof (urlOrArrayBuffer) === "string")
  39889. this._urlType = "String";
  39890. if (Array.isArray(urlOrArrayBuffer))
  39891. this._urlType = "Array";
  39892. if (urlOrArrayBuffer instanceof ArrayBuffer)
  39893. this._urlType = "ArrayBuffer";
  39894. var urls = [];
  39895. var codecSupportedFound = false;
  39896. switch (this._urlType) {
  39897. case "ArrayBuffer":
  39898. if (urlOrArrayBuffer.byteLength > 0) {
  39899. codecSupportedFound = true;
  39900. this._soundLoaded(urlOrArrayBuffer);
  39901. }
  39902. break;
  39903. case "String":
  39904. urls.push(urlOrArrayBuffer);
  39905. case "Array":
  39906. if (urls.length === 0)
  39907. urls = urlOrArrayBuffer;
  39908. // If we found a supported format, we load it immediately and stop the loop
  39909. for (var i = 0; i < urls.length; i++) {
  39910. var url = urls[i];
  39911. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  39912. codecSupportedFound = true;
  39913. }
  39914. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  39915. codecSupportedFound = true;
  39916. }
  39917. if (url.indexOf(".wav", url.length - 4) !== -1) {
  39918. codecSupportedFound = true;
  39919. }
  39920. if (codecSupportedFound) {
  39921. // Loading sound using XHR2
  39922. if (!this._streaming) {
  39923. BABYLON.Tools.LoadFile(url, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  39924. }
  39925. else {
  39926. this._htmlAudioElement = new Audio(url);
  39927. this._htmlAudioElement.controls = false;
  39928. this._htmlAudioElement.loop = this.loop;
  39929. this._htmlAudioElement.crossOrigin = "anonymous";
  39930. this._htmlAudioElement.preload = "auto";
  39931. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  39932. _this._isReadyToPlay = true;
  39933. if (_this.autoplay) {
  39934. _this.play();
  39935. }
  39936. if (_this._readyToPlayCallback) {
  39937. _this._readyToPlayCallback();
  39938. }
  39939. });
  39940. document.body.appendChild(this._htmlAudioElement);
  39941. }
  39942. break;
  39943. }
  39944. }
  39945. break;
  39946. default:
  39947. validParameter = false;
  39948. break;
  39949. }
  39950. if (!validParameter) {
  39951. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  39952. }
  39953. else {
  39954. if (!codecSupportedFound) {
  39955. this._isReadyToPlay = true;
  39956. // Simulating a ready to play event to avoid breaking code path
  39957. if (this._readyToPlayCallback) {
  39958. window.setTimeout(function () {
  39959. _this._readyToPlayCallback();
  39960. }, 1000);
  39961. }
  39962. }
  39963. }
  39964. }
  39965. }
  39966. else {
  39967. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  39968. this._scene.mainSoundTrack.AddSound(this);
  39969. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  39970. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  39971. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  39972. }
  39973. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  39974. if (this._readyToPlayCallback) {
  39975. window.setTimeout(function () {
  39976. _this._readyToPlayCallback();
  39977. }, 1000);
  39978. }
  39979. }
  39980. }
  39981. Sound.prototype.dispose = function () {
  39982. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  39983. if (this.isPlaying) {
  39984. this.stop();
  39985. }
  39986. this._isReadyToPlay = false;
  39987. if (this.soundTrackId === -1) {
  39988. this._scene.mainSoundTrack.RemoveSound(this);
  39989. }
  39990. else {
  39991. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  39992. }
  39993. if (this._soundGain) {
  39994. this._soundGain.disconnect();
  39995. this._soundGain = null;
  39996. }
  39997. if (this._soundPanner) {
  39998. this._soundPanner.disconnect();
  39999. this._soundPanner = null;
  40000. }
  40001. if (this._soundSource) {
  40002. this._soundSource.disconnect();
  40003. this._soundSource = null;
  40004. }
  40005. this._audioBuffer = null;
  40006. if (this._htmlAudioElement) {
  40007. this._htmlAudioElement.pause();
  40008. this._htmlAudioElement.src = "";
  40009. document.body.removeChild(this._htmlAudioElement);
  40010. }
  40011. if (this._connectedMesh) {
  40012. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  40013. this._connectedMesh = null;
  40014. }
  40015. }
  40016. };
  40017. Sound.prototype.isReady = function () {
  40018. return this._isReadyToPlay;
  40019. };
  40020. Sound.prototype._soundLoaded = function (audioData) {
  40021. var _this = this;
  40022. this._isLoaded = true;
  40023. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  40024. _this._audioBuffer = buffer;
  40025. _this._isReadyToPlay = true;
  40026. if (_this.autoplay) {
  40027. _this.play();
  40028. }
  40029. if (_this._readyToPlayCallback) {
  40030. _this._readyToPlayCallback();
  40031. }
  40032. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  40033. };
  40034. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  40035. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  40036. this._audioBuffer = audioBuffer;
  40037. this._isReadyToPlay = true;
  40038. }
  40039. };
  40040. Sound.prototype.updateOptions = function (options) {
  40041. if (options) {
  40042. this.loop = options.loop || this.loop;
  40043. this.maxDistance = options.maxDistance || this.maxDistance;
  40044. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  40045. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  40046. this.refDistance = options.refDistance || this.refDistance;
  40047. this.distanceModel = options.distanceModel || this.distanceModel;
  40048. this._playbackRate = options.playbackRate || this._playbackRate;
  40049. this._updateSpatialParameters();
  40050. if (this.isPlaying) {
  40051. if (this._streaming) {
  40052. this._htmlAudioElement.playbackRate = this._playbackRate;
  40053. }
  40054. else {
  40055. this._soundSource.playbackRate.value = this._playbackRate;
  40056. }
  40057. }
  40058. }
  40059. };
  40060. Sound.prototype._createSpatialParameters = function () {
  40061. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  40062. if (this._scene.headphone) {
  40063. this._panningModel = "HRTF";
  40064. }
  40065. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  40066. this._updateSpatialParameters();
  40067. this._soundPanner.connect(this._ouputAudioNode);
  40068. this._inputAudioNode = this._soundPanner;
  40069. }
  40070. };
  40071. Sound.prototype._updateSpatialParameters = function () {
  40072. if (this.spatialSound) {
  40073. if (this.useCustomAttenuation) {
  40074. // Tricks to disable in a way embedded Web Audio attenuation
  40075. this._soundPanner.distanceModel = "linear";
  40076. this._soundPanner.maxDistance = Number.MAX_VALUE;
  40077. this._soundPanner.refDistance = 1;
  40078. this._soundPanner.rolloffFactor = 1;
  40079. this._soundPanner.panningModel = this._panningModel;
  40080. }
  40081. else {
  40082. this._soundPanner.distanceModel = this.distanceModel;
  40083. this._soundPanner.maxDistance = this.maxDistance;
  40084. this._soundPanner.refDistance = this.refDistance;
  40085. this._soundPanner.rolloffFactor = this.rolloffFactor;
  40086. this._soundPanner.panningModel = this._panningModel;
  40087. }
  40088. }
  40089. };
  40090. Sound.prototype.switchPanningModelToHRTF = function () {
  40091. this._panningModel = "HRTF";
  40092. this._switchPanningModel();
  40093. };
  40094. Sound.prototype.switchPanningModelToEqualPower = function () {
  40095. this._panningModel = "equalpower";
  40096. this._switchPanningModel();
  40097. };
  40098. Sound.prototype._switchPanningModel = function () {
  40099. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  40100. this._soundPanner.panningModel = this._panningModel;
  40101. }
  40102. };
  40103. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  40104. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  40105. if (this._isOutputConnected) {
  40106. this._ouputAudioNode.disconnect();
  40107. }
  40108. this._ouputAudioNode.connect(soundTrackAudioNode);
  40109. this._isOutputConnected = true;
  40110. }
  40111. };
  40112. /**
  40113. * Transform this sound into a directional source
  40114. * @param coneInnerAngle Size of the inner cone in degree
  40115. * @param coneOuterAngle Size of the outer cone in degree
  40116. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  40117. */
  40118. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  40119. if (coneOuterAngle < coneInnerAngle) {
  40120. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  40121. return;
  40122. }
  40123. this._coneInnerAngle = coneInnerAngle;
  40124. this._coneOuterAngle = coneOuterAngle;
  40125. this._coneOuterGain = coneOuterGain;
  40126. this._isDirectional = true;
  40127. if (this.isPlaying && this.loop) {
  40128. this.stop();
  40129. this.play();
  40130. }
  40131. };
  40132. Sound.prototype.setPosition = function (newPosition) {
  40133. this._position = newPosition;
  40134. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  40135. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  40136. }
  40137. };
  40138. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  40139. this._localDirection = newLocalDirection;
  40140. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  40141. this._updateDirection();
  40142. }
  40143. };
  40144. Sound.prototype._updateDirection = function () {
  40145. var mat = this._connectedMesh.getWorldMatrix();
  40146. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  40147. direction.normalize();
  40148. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  40149. };
  40150. Sound.prototype.updateDistanceFromListener = function () {
  40151. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  40152. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  40153. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  40154. }
  40155. };
  40156. Sound.prototype.setAttenuationFunction = function (callback) {
  40157. this._customAttenuationFunction = callback;
  40158. };
  40159. /**
  40160. * Play the sound
  40161. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  40162. * @param offset (optional) Start the sound setting it at a specific time
  40163. */
  40164. Sound.prototype.play = function (time, offset) {
  40165. var _this = this;
  40166. if (this._isReadyToPlay && this._scene.audioEnabled) {
  40167. try {
  40168. if (this._startOffset < 0) {
  40169. time = -this._startOffset;
  40170. this._startOffset = 0;
  40171. }
  40172. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  40173. if (!this._soundSource || !this._streamingSource) {
  40174. if (this.spatialSound) {
  40175. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  40176. if (this._isDirectional) {
  40177. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  40178. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  40179. this._soundPanner.coneOuterGain = this._coneOuterGain;
  40180. if (this._connectedMesh) {
  40181. this._updateDirection();
  40182. }
  40183. else {
  40184. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  40185. }
  40186. }
  40187. }
  40188. }
  40189. if (this._streaming) {
  40190. if (!this._streamingSource) {
  40191. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  40192. this._htmlAudioElement.onended = function () { _this._onended(); };
  40193. this._htmlAudioElement.playbackRate = this._playbackRate;
  40194. }
  40195. this._streamingSource.disconnect();
  40196. this._streamingSource.connect(this._inputAudioNode);
  40197. this._htmlAudioElement.play();
  40198. }
  40199. else {
  40200. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  40201. this._soundSource.buffer = this._audioBuffer;
  40202. this._soundSource.connect(this._inputAudioNode);
  40203. this._soundSource.loop = this.loop;
  40204. this._soundSource.playbackRate.value = this._playbackRate;
  40205. this._soundSource.onended = function () { _this._onended(); };
  40206. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  40207. }
  40208. this._startTime = startTime;
  40209. this.isPlaying = true;
  40210. this.isPaused = false;
  40211. }
  40212. catch (ex) {
  40213. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  40214. }
  40215. }
  40216. };
  40217. Sound.prototype._onended = function () {
  40218. this.isPlaying = false;
  40219. if (this.onended) {
  40220. this.onended();
  40221. }
  40222. };
  40223. /**
  40224. * Stop the sound
  40225. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  40226. */
  40227. Sound.prototype.stop = function (time) {
  40228. if (this.isPlaying) {
  40229. if (this._streaming) {
  40230. this._htmlAudioElement.pause();
  40231. // Test needed for Firefox or it will generate an Invalid State Error
  40232. if (this._htmlAudioElement.currentTime > 0) {
  40233. this._htmlAudioElement.currentTime = 0;
  40234. }
  40235. }
  40236. else {
  40237. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  40238. this._soundSource.stop(stopTime);
  40239. this._soundSource.onended = null;
  40240. if (!this.isPaused) {
  40241. this._startOffset = 0;
  40242. }
  40243. }
  40244. this.isPlaying = false;
  40245. }
  40246. };
  40247. Sound.prototype.pause = function () {
  40248. if (this.isPlaying) {
  40249. this.isPaused = true;
  40250. if (this._streaming) {
  40251. this._htmlAudioElement.pause();
  40252. }
  40253. else {
  40254. this.stop(0);
  40255. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  40256. }
  40257. }
  40258. };
  40259. Sound.prototype.setVolume = function (newVolume, time) {
  40260. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  40261. if (time) {
  40262. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  40263. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  40264. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  40265. }
  40266. else {
  40267. this._soundGain.gain.value = newVolume;
  40268. }
  40269. }
  40270. this._volume = newVolume;
  40271. };
  40272. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  40273. this._playbackRate = newPlaybackRate;
  40274. if (this.isPlaying) {
  40275. if (this._streaming) {
  40276. this._htmlAudioElement.playbackRate = this._playbackRate;
  40277. }
  40278. else {
  40279. this._soundSource.playbackRate.value = this._playbackRate;
  40280. }
  40281. }
  40282. };
  40283. Sound.prototype.getVolume = function () {
  40284. return this._volume;
  40285. };
  40286. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  40287. var _this = this;
  40288. if (this._connectedMesh) {
  40289. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  40290. this._registerFunc = null;
  40291. }
  40292. this._connectedMesh = meshToConnectTo;
  40293. if (!this.spatialSound) {
  40294. this.spatialSound = true;
  40295. this._createSpatialParameters();
  40296. if (this.isPlaying && this.loop) {
  40297. this.stop();
  40298. this.play();
  40299. }
  40300. }
  40301. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  40302. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  40303. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  40304. };
  40305. Sound.prototype.detachFromMesh = function () {
  40306. if (this._connectedMesh) {
  40307. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  40308. this._registerFunc = null;
  40309. this._connectedMesh = null;
  40310. }
  40311. };
  40312. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  40313. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  40314. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  40315. this._updateDirection();
  40316. }
  40317. };
  40318. Sound.prototype.clone = function () {
  40319. var _this = this;
  40320. if (!this._streaming) {
  40321. var setBufferAndRun = function () {
  40322. if (_this._isReadyToPlay) {
  40323. clonedSound._audioBuffer = _this.getAudioBuffer();
  40324. clonedSound._isReadyToPlay = true;
  40325. if (clonedSound.autoplay) {
  40326. clonedSound.play();
  40327. }
  40328. }
  40329. else {
  40330. window.setTimeout(setBufferAndRun, 300);
  40331. }
  40332. };
  40333. var currentOptions = {
  40334. autoplay: this.autoplay, loop: this.loop,
  40335. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  40336. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  40337. refDistance: this.refDistance, distanceModel: this.distanceModel
  40338. };
  40339. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  40340. if (this.useCustomAttenuation) {
  40341. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  40342. }
  40343. clonedSound.setPosition(this._position);
  40344. clonedSound.setPlaybackRate(this._playbackRate);
  40345. setBufferAndRun();
  40346. return clonedSound;
  40347. }
  40348. else {
  40349. return null;
  40350. }
  40351. };
  40352. Sound.prototype.getAudioBuffer = function () {
  40353. return this._audioBuffer;
  40354. };
  40355. Sound.prototype.serialize = function () {
  40356. var serializationObject = {
  40357. name: this.name,
  40358. url: this.name,
  40359. autoplay: this.autoplay,
  40360. loop: this.loop,
  40361. volume: this._volume,
  40362. spatialSound: this.spatialSound,
  40363. maxDistance: this.maxDistance,
  40364. rolloffFactor: this.rolloffFactor,
  40365. refDistance: this.refDistance,
  40366. distanceModel: this.distanceModel,
  40367. playbackRate: this._playbackRate,
  40368. panningModel: this._panningModel,
  40369. soundTrackId: this.soundTrackId
  40370. };
  40371. if (this.spatialSound) {
  40372. if (this._connectedMesh)
  40373. serializationObject.connectedMeshId = this._connectedMesh.id;
  40374. serializationObject.position = this._position.asArray();
  40375. serializationObject.refDistance = this.refDistance;
  40376. serializationObject.distanceModel = this.distanceModel;
  40377. serializationObject.isDirectional = this._isDirectional;
  40378. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  40379. serializationObject.coneInnerAngle = this._coneInnerAngle;
  40380. serializationObject.coneOuterAngle = this._coneOuterAngle;
  40381. serializationObject.coneOuterGain = this._coneOuterGain;
  40382. }
  40383. return serializationObject;
  40384. };
  40385. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  40386. var soundName = parsedSound.name;
  40387. var soundUrl;
  40388. if (parsedSound.url) {
  40389. soundUrl = rootUrl + parsedSound.url;
  40390. }
  40391. else {
  40392. soundUrl = rootUrl + soundName;
  40393. }
  40394. var options = {
  40395. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  40396. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  40397. rolloffFactor: parsedSound.rolloffFactor,
  40398. refDistance: parsedSound.refDistance,
  40399. distanceModel: parsedSound.distanceModel,
  40400. playbackRate: parsedSound.playbackRate
  40401. };
  40402. var newSound;
  40403. if (!sourceSound) {
  40404. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  40405. scene._addPendingData(newSound);
  40406. }
  40407. else {
  40408. var setBufferAndRun = function () {
  40409. if (sourceSound._isReadyToPlay) {
  40410. newSound._audioBuffer = sourceSound.getAudioBuffer();
  40411. newSound._isReadyToPlay = true;
  40412. if (newSound.autoplay) {
  40413. newSound.play();
  40414. }
  40415. }
  40416. else {
  40417. window.setTimeout(setBufferAndRun, 300);
  40418. }
  40419. };
  40420. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  40421. setBufferAndRun();
  40422. }
  40423. if (parsedSound.position) {
  40424. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  40425. newSound.setPosition(soundPosition);
  40426. }
  40427. if (parsedSound.isDirectional) {
  40428. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  40429. if (parsedSound.localDirectionToMesh) {
  40430. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  40431. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  40432. }
  40433. }
  40434. if (parsedSound.connectedMeshId) {
  40435. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  40436. if (connectedMesh) {
  40437. newSound.attachToMesh(connectedMesh);
  40438. }
  40439. }
  40440. return newSound;
  40441. };
  40442. return Sound;
  40443. }());
  40444. BABYLON.Sound = Sound;
  40445. })(BABYLON || (BABYLON = {}));
  40446. //# sourceMappingURL=babylon.sound.js.map
  40447. var BABYLON;
  40448. (function (BABYLON) {
  40449. var SoundTrack = (function () {
  40450. function SoundTrack(scene, options) {
  40451. this.id = -1;
  40452. this._isMainTrack = false;
  40453. this._isInitialized = false;
  40454. this._scene = scene;
  40455. this.soundCollection = new Array();
  40456. this._options = options;
  40457. if (!this._isMainTrack) {
  40458. this._scene.soundTracks.push(this);
  40459. this.id = this._scene.soundTracks.length - 1;
  40460. }
  40461. }
  40462. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  40463. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  40464. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  40465. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  40466. if (this._options) {
  40467. if (this._options.volume) {
  40468. this._outputAudioNode.gain.value = this._options.volume;
  40469. }
  40470. if (this._options.mainTrack) {
  40471. this._isMainTrack = this._options.mainTrack;
  40472. }
  40473. }
  40474. this._isInitialized = true;
  40475. }
  40476. };
  40477. SoundTrack.prototype.dispose = function () {
  40478. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  40479. if (this._connectedAnalyser) {
  40480. this._connectedAnalyser.stopDebugCanvas();
  40481. }
  40482. while (this.soundCollection.length) {
  40483. this.soundCollection[0].dispose();
  40484. }
  40485. if (this._outputAudioNode) {
  40486. this._outputAudioNode.disconnect();
  40487. }
  40488. this._outputAudioNode = null;
  40489. }
  40490. };
  40491. SoundTrack.prototype.AddSound = function (sound) {
  40492. if (!this._isInitialized) {
  40493. this._initializeSoundTrackAudioGraph();
  40494. }
  40495. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  40496. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  40497. }
  40498. if (sound.soundTrackId) {
  40499. if (sound.soundTrackId === -1) {
  40500. this._scene.mainSoundTrack.RemoveSound(sound);
  40501. }
  40502. else {
  40503. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  40504. }
  40505. }
  40506. this.soundCollection.push(sound);
  40507. sound.soundTrackId = this.id;
  40508. };
  40509. SoundTrack.prototype.RemoveSound = function (sound) {
  40510. var index = this.soundCollection.indexOf(sound);
  40511. if (index !== -1) {
  40512. this.soundCollection.splice(index, 1);
  40513. }
  40514. };
  40515. SoundTrack.prototype.setVolume = function (newVolume) {
  40516. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  40517. this._outputAudioNode.gain.value = newVolume;
  40518. }
  40519. };
  40520. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  40521. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  40522. for (var i = 0; i < this.soundCollection.length; i++) {
  40523. this.soundCollection[i].switchPanningModelToHRTF();
  40524. }
  40525. }
  40526. };
  40527. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  40528. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  40529. for (var i = 0; i < this.soundCollection.length; i++) {
  40530. this.soundCollection[i].switchPanningModelToEqualPower();
  40531. }
  40532. }
  40533. };
  40534. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  40535. if (this._connectedAnalyser) {
  40536. this._connectedAnalyser.stopDebugCanvas();
  40537. }
  40538. this._connectedAnalyser = analyser;
  40539. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  40540. this._outputAudioNode.disconnect();
  40541. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  40542. }
  40543. };
  40544. return SoundTrack;
  40545. }());
  40546. BABYLON.SoundTrack = SoundTrack;
  40547. })(BABYLON || (BABYLON = {}));
  40548. //# sourceMappingURL=babylon.soundtrack.js.map
  40549. var BABYLON;
  40550. (function (BABYLON) {
  40551. var Analyser = (function () {
  40552. function Analyser(scene) {
  40553. this.SMOOTHING = 0.75;
  40554. this.FFT_SIZE = 512;
  40555. this.BARGRAPHAMPLITUDE = 256;
  40556. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  40557. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  40558. this._scene = scene;
  40559. this._audioEngine = BABYLON.Engine.audioEngine;
  40560. if (this._audioEngine.canUseWebAudio) {
  40561. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  40562. this._webAudioAnalyser.minDecibels = -140;
  40563. this._webAudioAnalyser.maxDecibels = 0;
  40564. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  40565. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  40566. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  40567. }
  40568. }
  40569. Analyser.prototype.getFrequencyBinCount = function () {
  40570. if (this._audioEngine.canUseWebAudio) {
  40571. return this._webAudioAnalyser.frequencyBinCount;
  40572. }
  40573. else {
  40574. return 0;
  40575. }
  40576. };
  40577. Analyser.prototype.getByteFrequencyData = function () {
  40578. if (this._audioEngine.canUseWebAudio) {
  40579. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  40580. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  40581. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  40582. }
  40583. return this._byteFreqs;
  40584. };
  40585. Analyser.prototype.getByteTimeDomainData = function () {
  40586. if (this._audioEngine.canUseWebAudio) {
  40587. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  40588. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  40589. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  40590. }
  40591. return this._byteTime;
  40592. };
  40593. Analyser.prototype.getFloatFrequencyData = function () {
  40594. if (this._audioEngine.canUseWebAudio) {
  40595. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  40596. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  40597. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  40598. }
  40599. return this._floatFreqs;
  40600. };
  40601. Analyser.prototype.drawDebugCanvas = function () {
  40602. var _this = this;
  40603. if (this._audioEngine.canUseWebAudio) {
  40604. if (!this._debugCanvas) {
  40605. this._debugCanvas = document.createElement("canvas");
  40606. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  40607. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  40608. this._debugCanvas.style.position = "absolute";
  40609. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  40610. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  40611. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  40612. document.body.appendChild(this._debugCanvas);
  40613. this._registerFunc = function () {
  40614. _this.drawDebugCanvas();
  40615. };
  40616. this._scene.registerBeforeRender(this._registerFunc);
  40617. }
  40618. if (this._registerFunc) {
  40619. var workingArray = this.getByteFrequencyData();
  40620. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  40621. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  40622. // Draw the frequency domain chart.
  40623. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  40624. var value = workingArray[i];
  40625. var percent = value / this.BARGRAPHAMPLITUDE;
  40626. var height = this.DEBUGCANVASSIZE.height * percent;
  40627. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  40628. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  40629. var hue = i / this.getFrequencyBinCount() * 360;
  40630. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  40631. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  40632. }
  40633. }
  40634. }
  40635. };
  40636. Analyser.prototype.stopDebugCanvas = function () {
  40637. if (this._debugCanvas) {
  40638. this._scene.unregisterBeforeRender(this._registerFunc);
  40639. this._registerFunc = null;
  40640. document.body.removeChild(this._debugCanvas);
  40641. this._debugCanvas = null;
  40642. this._debugCanvasContext = null;
  40643. }
  40644. };
  40645. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  40646. if (this._audioEngine.canUseWebAudio) {
  40647. inputAudioNode.connect(this._webAudioAnalyser);
  40648. this._webAudioAnalyser.connect(outputAudioNode);
  40649. }
  40650. };
  40651. Analyser.prototype.dispose = function () {
  40652. if (this._audioEngine.canUseWebAudio) {
  40653. this._webAudioAnalyser.disconnect();
  40654. }
  40655. };
  40656. return Analyser;
  40657. }());
  40658. BABYLON.Analyser = Analyser;
  40659. })(BABYLON || (BABYLON = {}));
  40660. //# sourceMappingURL=babylon.analyser.js.map
  40661. var BABYLON;
  40662. (function (BABYLON) {
  40663. var CubeTexture = (function (_super) {
  40664. __extends(CubeTexture, _super);
  40665. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format) {
  40666. if (onLoad === void 0) { onLoad = null; }
  40667. if (onError === void 0) { onError = null; }
  40668. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  40669. var _this = _super.call(this, scene) || this;
  40670. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  40671. _this.name = rootUrl;
  40672. _this.url = rootUrl;
  40673. _this._noMipmap = noMipmap;
  40674. _this.hasAlpha = false;
  40675. _this._format = format;
  40676. if (!rootUrl && !files) {
  40677. return _this;
  40678. }
  40679. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  40680. if (!files) {
  40681. if (!extensions) {
  40682. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  40683. }
  40684. files = [];
  40685. for (var index = 0; index < extensions.length; index++) {
  40686. files.push(rootUrl + extensions[index]);
  40687. }
  40688. _this._extensions = extensions;
  40689. }
  40690. _this._files = files;
  40691. if (!_this._texture) {
  40692. if (!scene.useDelayedTextureLoading) {
  40693. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format);
  40694. }
  40695. else {
  40696. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  40697. }
  40698. }
  40699. else if (onLoad) {
  40700. if (_this._texture.isReady) {
  40701. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  40702. }
  40703. else {
  40704. _this._texture.onLoadedCallbacks.push(onLoad);
  40705. }
  40706. }
  40707. _this.isCube = true;
  40708. _this._textureMatrix = BABYLON.Matrix.Identity();
  40709. return _this;
  40710. }
  40711. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  40712. return new CubeTexture("", scene, null, noMipmap, files);
  40713. };
  40714. // Methods
  40715. CubeTexture.prototype.delayLoad = function () {
  40716. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  40717. return;
  40718. }
  40719. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  40720. this._texture = this._getFromCache(this.url, this._noMipmap);
  40721. if (!this._texture) {
  40722. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._files, this._noMipmap, undefined, undefined, this._format);
  40723. }
  40724. };
  40725. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  40726. return this._textureMatrix;
  40727. };
  40728. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  40729. var texture = BABYLON.SerializationHelper.Parse(function () {
  40730. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  40731. }, parsedTexture, scene);
  40732. // Animations
  40733. if (parsedTexture.animations) {
  40734. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  40735. var parsedAnimation = parsedTexture.animations[animationIndex];
  40736. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  40737. }
  40738. }
  40739. return texture;
  40740. };
  40741. CubeTexture.prototype.clone = function () {
  40742. var _this = this;
  40743. return BABYLON.SerializationHelper.Clone(function () {
  40744. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  40745. }, this);
  40746. };
  40747. return CubeTexture;
  40748. }(BABYLON.BaseTexture));
  40749. BABYLON.CubeTexture = CubeTexture;
  40750. })(BABYLON || (BABYLON = {}));
  40751. //# sourceMappingURL=babylon.cubeTexture.js.map
  40752. var BABYLON;
  40753. (function (BABYLON) {
  40754. var RenderTargetTexture = (function (_super) {
  40755. __extends(RenderTargetTexture, _super);
  40756. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer) {
  40757. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  40758. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  40759. if (isCube === void 0) { isCube = false; }
  40760. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  40761. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  40762. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  40763. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  40764. _this.isCube = isCube;
  40765. /**
  40766. * Use this list to define the list of mesh you want to render.
  40767. */
  40768. _this.renderList = new Array();
  40769. _this.renderParticles = true;
  40770. _this.renderSprites = false;
  40771. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  40772. // Events
  40773. /**
  40774. * An event triggered when the texture is unbind.
  40775. * @type {BABYLON.Observable}
  40776. */
  40777. _this.onAfterUnbindObservable = new BABYLON.Observable();
  40778. /**
  40779. * An event triggered before rendering the texture
  40780. * @type {BABYLON.Observable}
  40781. */
  40782. _this.onBeforeRenderObservable = new BABYLON.Observable();
  40783. /**
  40784. * An event triggered after rendering the texture
  40785. * @type {BABYLON.Observable}
  40786. */
  40787. _this.onAfterRenderObservable = new BABYLON.Observable();
  40788. /**
  40789. * An event triggered after the texture clear
  40790. * @type {BABYLON.Observable}
  40791. */
  40792. _this.onClearObservable = new BABYLON.Observable();
  40793. _this._currentRefreshId = -1;
  40794. _this._refreshRate = 1;
  40795. _this._samples = 1;
  40796. _this.name = name;
  40797. _this.isRenderTarget = true;
  40798. _this._size = size;
  40799. _this._generateMipMaps = generateMipMaps;
  40800. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  40801. _this._renderTargetOptions = {
  40802. generateMipMaps: generateMipMaps,
  40803. type: type,
  40804. samplingMode: samplingMode,
  40805. generateDepthBuffer: generateDepthBuffer,
  40806. generateStencilBuffer: generateStencilBuffer
  40807. };
  40808. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  40809. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40810. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40811. }
  40812. if (isCube) {
  40813. _this._texture = scene.getEngine().createRenderTargetCubeTexture(size, _this._renderTargetOptions);
  40814. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  40815. _this._textureMatrix = BABYLON.Matrix.Identity();
  40816. }
  40817. else {
  40818. _this._texture = scene.getEngine().createRenderTargetTexture(size, _this._renderTargetOptions);
  40819. }
  40820. // Rendering groups
  40821. _this._renderingManager = new BABYLON.RenderingManager(scene);
  40822. return _this;
  40823. }
  40824. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  40825. get: function () {
  40826. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  40827. },
  40828. enumerable: true,
  40829. configurable: true
  40830. });
  40831. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  40832. get: function () {
  40833. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  40834. },
  40835. enumerable: true,
  40836. configurable: true
  40837. });
  40838. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  40839. get: function () {
  40840. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  40841. },
  40842. enumerable: true,
  40843. configurable: true
  40844. });
  40845. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  40846. set: function (callback) {
  40847. if (this._onAfterUnbindObserver) {
  40848. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  40849. }
  40850. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  40851. },
  40852. enumerable: true,
  40853. configurable: true
  40854. });
  40855. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  40856. set: function (callback) {
  40857. if (this._onBeforeRenderObserver) {
  40858. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  40859. }
  40860. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  40861. },
  40862. enumerable: true,
  40863. configurable: true
  40864. });
  40865. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  40866. set: function (callback) {
  40867. if (this._onAfterRenderObserver) {
  40868. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  40869. }
  40870. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  40871. },
  40872. enumerable: true,
  40873. configurable: true
  40874. });
  40875. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  40876. set: function (callback) {
  40877. if (this._onClearObserver) {
  40878. this.onClearObservable.remove(this._onClearObserver);
  40879. }
  40880. this._onClearObserver = this.onClearObservable.add(callback);
  40881. },
  40882. enumerable: true,
  40883. configurable: true
  40884. });
  40885. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  40886. get: function () {
  40887. return this._samples;
  40888. },
  40889. set: function (value) {
  40890. if (this._samples === value) {
  40891. return;
  40892. }
  40893. this._samples = this.getScene().getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  40894. },
  40895. enumerable: true,
  40896. configurable: true
  40897. });
  40898. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  40899. this._currentRefreshId = -1;
  40900. };
  40901. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  40902. get: function () {
  40903. return this._refreshRate;
  40904. },
  40905. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  40906. set: function (value) {
  40907. this._refreshRate = value;
  40908. this.resetRefreshCounter();
  40909. },
  40910. enumerable: true,
  40911. configurable: true
  40912. });
  40913. RenderTargetTexture.prototype._shouldRender = function () {
  40914. if (this._currentRefreshId === -1) {
  40915. this._currentRefreshId = 1;
  40916. return true;
  40917. }
  40918. if (this.refreshRate === this._currentRefreshId) {
  40919. this._currentRefreshId = 1;
  40920. return true;
  40921. }
  40922. this._currentRefreshId++;
  40923. return false;
  40924. };
  40925. RenderTargetTexture.prototype.isReady = function () {
  40926. if (!this.getScene().renderTargetsEnabled) {
  40927. return false;
  40928. }
  40929. return _super.prototype.isReady.call(this);
  40930. };
  40931. RenderTargetTexture.prototype.getRenderSize = function () {
  40932. return this._size;
  40933. };
  40934. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  40935. get: function () {
  40936. return true;
  40937. },
  40938. enumerable: true,
  40939. configurable: true
  40940. });
  40941. RenderTargetTexture.prototype.scale = function (ratio) {
  40942. var newSize = this._size * ratio;
  40943. this.resize(newSize);
  40944. };
  40945. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  40946. if (this.isCube) {
  40947. return this._textureMatrix;
  40948. }
  40949. return _super.prototype.getReflectionTextureMatrix.call(this);
  40950. };
  40951. RenderTargetTexture.prototype.resize = function (size) {
  40952. this.releaseInternalTexture();
  40953. if (this.isCube) {
  40954. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size, this._renderTargetOptions);
  40955. }
  40956. else {
  40957. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, this._renderTargetOptions);
  40958. }
  40959. };
  40960. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  40961. var scene = this.getScene();
  40962. var engine = scene.getEngine();
  40963. if (this.useCameraPostProcesses !== undefined) {
  40964. useCameraPostProcess = this.useCameraPostProcesses;
  40965. }
  40966. if (this._waitingRenderList) {
  40967. this.renderList = [];
  40968. for (var index = 0; index < this._waitingRenderList.length; index++) {
  40969. var id = this._waitingRenderList[index];
  40970. this.renderList.push(scene.getMeshByID(id));
  40971. }
  40972. delete this._waitingRenderList;
  40973. }
  40974. // Is predicate defined?
  40975. if (this.renderListPredicate) {
  40976. this.renderList.splice(0); // Clear previous renderList
  40977. var sceneMeshes = this.getScene().meshes;
  40978. for (var index = 0; index < sceneMeshes.length; index++) {
  40979. var mesh = sceneMeshes[index];
  40980. if (this.renderListPredicate(mesh)) {
  40981. this.renderList.push(mesh);
  40982. }
  40983. }
  40984. }
  40985. if (this.renderList && this.renderList.length === 0) {
  40986. return;
  40987. }
  40988. // Set custom projection.
  40989. // Needs to be before binding to prevent changing the aspect ratio.
  40990. if (this.activeCamera) {
  40991. engine.setViewport(this.activeCamera.viewport);
  40992. if (this.activeCamera !== scene.activeCamera) {
  40993. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  40994. }
  40995. }
  40996. else {
  40997. engine.setViewport(scene.activeCamera.viewport);
  40998. }
  40999. // Prepare renderingManager
  41000. this._renderingManager.reset();
  41001. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  41002. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  41003. var sceneRenderId = scene.getRenderId();
  41004. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  41005. var mesh = currentRenderList[meshIndex];
  41006. if (mesh) {
  41007. if (!mesh.isReady()) {
  41008. // Reset _currentRefreshId
  41009. this.resetRefreshCounter();
  41010. continue;
  41011. }
  41012. mesh._preActivateForIntermediateRendering(sceneRenderId);
  41013. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  41014. mesh._activate(sceneRenderId);
  41015. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  41016. var subMesh = mesh.subMeshes[subIndex];
  41017. scene._activeIndices.addCount(subMesh.indexCount, false);
  41018. this._renderingManager.dispatch(subMesh);
  41019. }
  41020. }
  41021. }
  41022. }
  41023. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  41024. var particleSystem = scene.particleSystems[particleIndex];
  41025. if (!particleSystem.isStarted() || !particleSystem.emitter || !particleSystem.emitter.position || !particleSystem.emitter.isEnabled()) {
  41026. continue;
  41027. }
  41028. if (currentRenderList.indexOf(particleSystem.emitter) >= 0) {
  41029. this._renderingManager.dispatchParticles(particleSystem);
  41030. }
  41031. }
  41032. if (this.isCube) {
  41033. for (var face = 0; face < 6; face++) {
  41034. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  41035. scene.incrementRenderId();
  41036. scene.resetCachedMaterial();
  41037. }
  41038. }
  41039. else {
  41040. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  41041. }
  41042. this.onAfterUnbindObservable.notifyObservers(this);
  41043. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  41044. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  41045. }
  41046. engine.setViewport(scene.activeCamera.viewport);
  41047. scene.resetCachedMaterial();
  41048. };
  41049. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  41050. var _this = this;
  41051. var scene = this.getScene();
  41052. var engine = scene.getEngine();
  41053. // Bind
  41054. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  41055. if (this.isCube) {
  41056. engine.bindFramebuffer(this._texture, faceIndex);
  41057. }
  41058. else {
  41059. engine.bindFramebuffer(this._texture);
  41060. }
  41061. }
  41062. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  41063. // Clear
  41064. if (this.onClearObservable.hasObservers()) {
  41065. this.onClearObservable.notifyObservers(engine);
  41066. }
  41067. else {
  41068. engine.clear(scene.clearColor, true, true, true);
  41069. }
  41070. if (!this._doNotChangeAspectRatio) {
  41071. scene.updateTransformMatrix(true);
  41072. }
  41073. // Render
  41074. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  41075. if (useCameraPostProcess) {
  41076. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  41077. }
  41078. if (!this._doNotChangeAspectRatio) {
  41079. scene.updateTransformMatrix(true);
  41080. }
  41081. // Dump ?
  41082. if (dumpForDebug) {
  41083. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  41084. }
  41085. // Unbind
  41086. if (!this.isCube || faceIndex === 5) {
  41087. if (this.isCube) {
  41088. if (faceIndex === 5) {
  41089. engine.generateMipMapsForCubemap(this._texture);
  41090. }
  41091. }
  41092. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  41093. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  41094. });
  41095. }
  41096. else {
  41097. this.onAfterRenderObservable.notifyObservers(faceIndex);
  41098. }
  41099. };
  41100. /**
  41101. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  41102. * This allowed control for front to back rendering or reversly depending of the special needs.
  41103. *
  41104. * @param renderingGroupId The rendering group id corresponding to its index
  41105. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  41106. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  41107. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  41108. */
  41109. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  41110. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  41111. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  41112. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  41113. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  41114. };
  41115. /**
  41116. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  41117. *
  41118. * @param renderingGroupId The rendering group id corresponding to its index
  41119. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  41120. */
  41121. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  41122. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  41123. };
  41124. RenderTargetTexture.prototype.clone = function () {
  41125. var textureSize = this.getSize();
  41126. 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);
  41127. // Base texture
  41128. newTexture.hasAlpha = this.hasAlpha;
  41129. newTexture.level = this.level;
  41130. // RenderTarget Texture
  41131. newTexture.coordinatesMode = this.coordinatesMode;
  41132. newTexture.renderList = this.renderList.slice(0);
  41133. return newTexture;
  41134. };
  41135. RenderTargetTexture.prototype.serialize = function () {
  41136. if (!this.name) {
  41137. return null;
  41138. }
  41139. var serializationObject = _super.prototype.serialize.call(this);
  41140. serializationObject.renderTargetSize = this.getRenderSize();
  41141. serializationObject.renderList = [];
  41142. for (var index = 0; index < this.renderList.length; index++) {
  41143. serializationObject.renderList.push(this.renderList[index].id);
  41144. }
  41145. return serializationObject;
  41146. };
  41147. return RenderTargetTexture;
  41148. }(BABYLON.Texture));
  41149. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  41150. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  41151. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  41152. BABYLON.RenderTargetTexture = RenderTargetTexture;
  41153. })(BABYLON || (BABYLON = {}));
  41154. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  41155. /// <reference path="babylon.renderTargetTexture.ts" />
  41156. var BABYLON;
  41157. (function (BABYLON) {
  41158. var MirrorTexture = (function (_super) {
  41159. __extends(MirrorTexture, _super);
  41160. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  41161. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  41162. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  41163. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  41164. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  41165. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  41166. _this._transformMatrix = BABYLON.Matrix.Zero();
  41167. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  41168. _this.onBeforeRenderObservable.add(function () {
  41169. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  41170. _this._savedViewMatrix = scene.getViewMatrix();
  41171. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  41172. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  41173. scene.clipPlane = _this.mirrorPlane;
  41174. scene.getEngine().cullBackFaces = false;
  41175. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  41176. });
  41177. _this.onAfterRenderObservable.add(function () {
  41178. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  41179. scene.getEngine().cullBackFaces = true;
  41180. scene._mirroredCameraPosition = null;
  41181. delete scene.clipPlane;
  41182. });
  41183. return _this;
  41184. }
  41185. MirrorTexture.prototype.clone = function () {
  41186. var textureSize = this.getSize();
  41187. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  41188. // Base texture
  41189. newTexture.hasAlpha = this.hasAlpha;
  41190. newTexture.level = this.level;
  41191. // Mirror Texture
  41192. newTexture.mirrorPlane = this.mirrorPlane.clone();
  41193. newTexture.renderList = this.renderList.slice(0);
  41194. return newTexture;
  41195. };
  41196. MirrorTexture.prototype.serialize = function () {
  41197. if (!this.name) {
  41198. return null;
  41199. }
  41200. var serializationObject = _super.prototype.serialize.call(this);
  41201. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  41202. return serializationObject;
  41203. };
  41204. return MirrorTexture;
  41205. }(BABYLON.RenderTargetTexture));
  41206. BABYLON.MirrorTexture = MirrorTexture;
  41207. })(BABYLON || (BABYLON = {}));
  41208. //# sourceMappingURL=babylon.mirrorTexture.js.map
  41209. /// <reference path="babylon.renderTargetTexture.ts" />
  41210. var BABYLON;
  41211. (function (BABYLON) {
  41212. /**
  41213. * Creates a refraction texture used by refraction channel of the standard material.
  41214. * @param name the texture name
  41215. * @param size size of the underlying texture
  41216. * @param scene root scene
  41217. */
  41218. var RefractionTexture = (function (_super) {
  41219. __extends(RefractionTexture, _super);
  41220. function RefractionTexture(name, size, scene, generateMipMaps) {
  41221. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  41222. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  41223. _this.depth = 2.0;
  41224. _this.onBeforeRenderObservable.add(function () {
  41225. scene.clipPlane = _this.refractionPlane;
  41226. });
  41227. _this.onAfterRenderObservable.add(function () {
  41228. delete scene.clipPlane;
  41229. });
  41230. return _this;
  41231. }
  41232. RefractionTexture.prototype.clone = function () {
  41233. var textureSize = this.getSize();
  41234. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  41235. // Base texture
  41236. newTexture.hasAlpha = this.hasAlpha;
  41237. newTexture.level = this.level;
  41238. // Refraction Texture
  41239. newTexture.refractionPlane = this.refractionPlane.clone();
  41240. newTexture.renderList = this.renderList.slice(0);
  41241. newTexture.depth = this.depth;
  41242. return newTexture;
  41243. };
  41244. RefractionTexture.prototype.serialize = function () {
  41245. if (!this.name) {
  41246. return null;
  41247. }
  41248. var serializationObject = _super.prototype.serialize.call(this);
  41249. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  41250. serializationObject.depth = this.depth;
  41251. return serializationObject;
  41252. };
  41253. return RefractionTexture;
  41254. }(BABYLON.RenderTargetTexture));
  41255. BABYLON.RefractionTexture = RefractionTexture;
  41256. })(BABYLON || (BABYLON = {}));
  41257. //# sourceMappingURL=babylon.refractionTexture.js.map
  41258. /// <reference path="babylon.texture.ts" />
  41259. var BABYLON;
  41260. (function (BABYLON) {
  41261. var DynamicTexture = (function (_super) {
  41262. __extends(DynamicTexture, _super);
  41263. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  41264. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  41265. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  41266. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  41267. _this.name = name;
  41268. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41269. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41270. _this._generateMipMaps = generateMipMaps;
  41271. if (options.getContext) {
  41272. _this._canvas = options;
  41273. _this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  41274. }
  41275. else {
  41276. _this._canvas = document.createElement("canvas");
  41277. if (options.width) {
  41278. _this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  41279. }
  41280. else {
  41281. _this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  41282. }
  41283. }
  41284. var textureSize = _this.getSize();
  41285. _this._canvas.width = textureSize.width;
  41286. _this._canvas.height = textureSize.height;
  41287. _this._context = _this._canvas.getContext("2d");
  41288. return _this;
  41289. }
  41290. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  41291. get: function () {
  41292. return true;
  41293. },
  41294. enumerable: true,
  41295. configurable: true
  41296. });
  41297. DynamicTexture.prototype.scale = function (ratio) {
  41298. var textureSize = this.getSize();
  41299. textureSize.width *= ratio;
  41300. textureSize.height *= ratio;
  41301. this._canvas.width = textureSize.width;
  41302. this._canvas.height = textureSize.height;
  41303. this.releaseInternalTexture();
  41304. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  41305. };
  41306. DynamicTexture.prototype.getContext = function () {
  41307. return this._context;
  41308. };
  41309. DynamicTexture.prototype.clear = function () {
  41310. var size = this.getSize();
  41311. this._context.fillRect(0, 0, size.width, size.height);
  41312. };
  41313. DynamicTexture.prototype.update = function (invertY) {
  41314. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format);
  41315. };
  41316. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  41317. if (update === void 0) { update = true; }
  41318. var size = this.getSize();
  41319. if (clearColor) {
  41320. this._context.fillStyle = clearColor;
  41321. this._context.fillRect(0, 0, size.width, size.height);
  41322. }
  41323. this._context.font = font;
  41324. if (x === null || x === undefined) {
  41325. var textSize = this._context.measureText(text);
  41326. x = (size.width - textSize.width) / 2;
  41327. }
  41328. if (y === null || y === undefined) {
  41329. var fontSize = parseInt((font.replace(/\D/g, '')));
  41330. ;
  41331. y = (size.height / 2) + (fontSize / 3.65);
  41332. }
  41333. this._context.fillStyle = color;
  41334. this._context.fillText(text, x, y);
  41335. if (update) {
  41336. this.update(invertY);
  41337. }
  41338. };
  41339. DynamicTexture.prototype.clone = function () {
  41340. var textureSize = this.getSize();
  41341. var newTexture = new DynamicTexture(this.name, textureSize, this.getScene(), this._generateMipMaps);
  41342. // Base texture
  41343. newTexture.hasAlpha = this.hasAlpha;
  41344. newTexture.level = this.level;
  41345. // Dynamic Texture
  41346. newTexture.wrapU = this.wrapU;
  41347. newTexture.wrapV = this.wrapV;
  41348. return newTexture;
  41349. };
  41350. return DynamicTexture;
  41351. }(BABYLON.Texture));
  41352. BABYLON.DynamicTexture = DynamicTexture;
  41353. })(BABYLON || (BABYLON = {}));
  41354. //# sourceMappingURL=babylon.dynamicTexture.js.map
  41355. var BABYLON;
  41356. (function (BABYLON) {
  41357. var VideoTexture = (function (_super) {
  41358. __extends(VideoTexture, _super);
  41359. /**
  41360. * Creates a video texture.
  41361. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  41362. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  41363. * @param {BABYLON.Scene} scene is obviously the current scene.
  41364. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  41365. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  41366. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  41367. */
  41368. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  41369. if (generateMipMaps === void 0) { generateMipMaps = false; }
  41370. if (invertY === void 0) { invertY = false; }
  41371. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  41372. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  41373. _this._autoLaunch = true;
  41374. var urls;
  41375. _this.name = name;
  41376. if (urlsOrVideo instanceof HTMLVideoElement) {
  41377. _this.video = urlsOrVideo;
  41378. }
  41379. else {
  41380. urls = urlsOrVideo;
  41381. _this.video = document.createElement("video");
  41382. _this.video.autoplay = false;
  41383. _this.video.loop = true;
  41384. }
  41385. _this._generateMipMaps = generateMipMaps;
  41386. _this._samplingMode = samplingMode;
  41387. if (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight)) {
  41388. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  41389. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  41390. }
  41391. else {
  41392. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41393. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41394. _this._generateMipMaps = false;
  41395. }
  41396. if (urls) {
  41397. _this.video.addEventListener("canplay", function () {
  41398. _this._createTexture();
  41399. });
  41400. urls.forEach(function (url) {
  41401. var source = document.createElement("source");
  41402. source.src = url;
  41403. _this.video.appendChild(source);
  41404. });
  41405. }
  41406. else {
  41407. _this._createTexture();
  41408. }
  41409. _this._lastUpdate = BABYLON.Tools.Now;
  41410. return _this;
  41411. }
  41412. VideoTexture.prototype._createTexture = function () {
  41413. var _this = this;
  41414. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  41415. if (this._autoLaunch) {
  41416. this._autoLaunch = false;
  41417. this.video.play();
  41418. }
  41419. this.video.addEventListener("playing", function () {
  41420. _this._texture.isReady = true;
  41421. });
  41422. };
  41423. VideoTexture.prototype.update = function () {
  41424. var now = BABYLON.Tools.Now;
  41425. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  41426. return false;
  41427. }
  41428. this._lastUpdate = now;
  41429. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  41430. return true;
  41431. };
  41432. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  41433. var video = document.createElement("video");
  41434. var constraintsDeviceId;
  41435. if (constraints && constraints.deviceId) {
  41436. constraintsDeviceId = {
  41437. exact: constraints.deviceId
  41438. };
  41439. }
  41440. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  41441. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  41442. if (navigator.getUserMedia) {
  41443. navigator.getUserMedia({
  41444. video: {
  41445. deviceId: constraintsDeviceId,
  41446. width: {
  41447. min: (constraints && constraints.minWidth) || 256,
  41448. max: (constraints && constraints.maxWidth) || 640
  41449. },
  41450. height: {
  41451. min: (constraints && constraints.minHeight) || 256,
  41452. max: (constraints && constraints.maxHeight) || 480
  41453. }
  41454. }
  41455. }, function (stream) {
  41456. if (video.mozSrcObject !== undefined) {
  41457. video.mozSrcObject = stream;
  41458. }
  41459. else {
  41460. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  41461. }
  41462. video.play();
  41463. if (onReady) {
  41464. onReady(new BABYLON.VideoTexture("video", video, scene, true, true));
  41465. }
  41466. }, function (e) {
  41467. BABYLON.Tools.Error(e.name);
  41468. });
  41469. }
  41470. };
  41471. return VideoTexture;
  41472. }(BABYLON.Texture));
  41473. BABYLON.VideoTexture = VideoTexture;
  41474. })(BABYLON || (BABYLON = {}));
  41475. //# sourceMappingURL=babylon.videoTexture.js.map
  41476. var BABYLON;
  41477. (function (BABYLON) {
  41478. var RawTexture = (function (_super) {
  41479. __extends(RawTexture, _super);
  41480. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  41481. if (generateMipMaps === void 0) { generateMipMaps = true; }
  41482. if (invertY === void 0) { invertY = false; }
  41483. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  41484. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  41485. _this.format = format;
  41486. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  41487. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41488. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41489. return _this;
  41490. }
  41491. RawTexture.prototype.update = function (data) {
  41492. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  41493. };
  41494. // Statics
  41495. RawTexture.CreateLuminanceTexture = 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, scene, generateMipMaps, invertY, samplingMode);
  41500. };
  41501. RawTexture.CreateLuminanceAlphaTexture = 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_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  41506. };
  41507. RawTexture.CreateAlphaTexture = 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_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  41512. };
  41513. RawTexture.CreateRGBTexture = 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_RGB, scene, generateMipMaps, invertY, samplingMode);
  41518. };
  41519. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  41520. if (generateMipMaps === void 0) { generateMipMaps = true; }
  41521. if (invertY === void 0) { invertY = false; }
  41522. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  41523. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  41524. };
  41525. return RawTexture;
  41526. }(BABYLON.Texture));
  41527. BABYLON.RawTexture = RawTexture;
  41528. })(BABYLON || (BABYLON = {}));
  41529. //# sourceMappingURL=babylon.rawTexture.js.map
  41530. var BABYLON;
  41531. (function (BABYLON) {
  41532. var PostProcess = (function () {
  41533. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType) {
  41534. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  41535. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  41536. this.name = name;
  41537. this.width = -1;
  41538. this.height = -1;
  41539. /*
  41540. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  41541. Can only be used on a single postprocess or on the last one of a chain.
  41542. */
  41543. this.enablePixelPerfectMode = false;
  41544. this.samples = 1;
  41545. this._reusable = false;
  41546. this._textures = new BABYLON.SmartArray(2);
  41547. this._currentRenderTextureInd = 0;
  41548. this._scaleRatio = new BABYLON.Vector2(1, 1);
  41549. // Events
  41550. /**
  41551. * An event triggered when the postprocess is activated.
  41552. * @type {BABYLON.Observable}
  41553. */
  41554. this.onActivateObservable = new BABYLON.Observable();
  41555. /**
  41556. * An event triggered when the postprocess changes its size.
  41557. * @type {BABYLON.Observable}
  41558. */
  41559. this.onSizeChangedObservable = new BABYLON.Observable();
  41560. /**
  41561. * An event triggered when the postprocess applies its effect.
  41562. * @type {BABYLON.Observable}
  41563. */
  41564. this.onApplyObservable = new BABYLON.Observable();
  41565. /**
  41566. * An event triggered before rendering the postprocess
  41567. * @type {BABYLON.Observable}
  41568. */
  41569. this.onBeforeRenderObservable = new BABYLON.Observable();
  41570. /**
  41571. * An event triggered after rendering the postprocess
  41572. * @type {BABYLON.Observable}
  41573. */
  41574. this.onAfterRenderObservable = new BABYLON.Observable();
  41575. if (camera != null) {
  41576. this._camera = camera;
  41577. this._scene = camera.getScene();
  41578. camera.attachPostProcess(this);
  41579. this._engine = this._scene.getEngine();
  41580. }
  41581. else {
  41582. this._engine = engine;
  41583. }
  41584. this._options = options;
  41585. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  41586. this._reusable = reusable || false;
  41587. this._textureType = textureType;
  41588. this._samplers = samplers || [];
  41589. this._samplers.push("textureSampler");
  41590. this._fragmentUrl = fragmentUrl;
  41591. this._parameters = parameters || [];
  41592. this._parameters.push("scale");
  41593. this.updateEffect(defines);
  41594. }
  41595. Object.defineProperty(PostProcess.prototype, "onActivate", {
  41596. set: function (callback) {
  41597. if (this._onActivateObserver) {
  41598. this.onActivateObservable.remove(this._onActivateObserver);
  41599. }
  41600. this._onActivateObserver = this.onActivateObservable.add(callback);
  41601. },
  41602. enumerable: true,
  41603. configurable: true
  41604. });
  41605. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  41606. set: function (callback) {
  41607. if (this._onSizeChangedObserver) {
  41608. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  41609. }
  41610. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  41611. },
  41612. enumerable: true,
  41613. configurable: true
  41614. });
  41615. Object.defineProperty(PostProcess.prototype, "onApply", {
  41616. set: function (callback) {
  41617. if (this._onApplyObserver) {
  41618. this.onApplyObservable.remove(this._onApplyObserver);
  41619. }
  41620. this._onApplyObserver = this.onApplyObservable.add(callback);
  41621. },
  41622. enumerable: true,
  41623. configurable: true
  41624. });
  41625. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  41626. set: function (callback) {
  41627. if (this._onBeforeRenderObserver) {
  41628. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  41629. }
  41630. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  41631. },
  41632. enumerable: true,
  41633. configurable: true
  41634. });
  41635. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  41636. set: function (callback) {
  41637. if (this._onAfterRenderObserver) {
  41638. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  41639. }
  41640. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  41641. },
  41642. enumerable: true,
  41643. configurable: true
  41644. });
  41645. PostProcess.prototype.updateEffect = function (defines) {
  41646. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  41647. };
  41648. PostProcess.prototype.isReusable = function () {
  41649. return this._reusable;
  41650. };
  41651. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  41652. PostProcess.prototype.markTextureDirty = function () {
  41653. this.width = -1;
  41654. };
  41655. PostProcess.prototype.activate = function (camera, sourceTexture) {
  41656. var _this = this;
  41657. camera = camera || this._camera;
  41658. var scene = camera.getScene();
  41659. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  41660. var requiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._options) | 0;
  41661. var requiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._options) | 0;
  41662. var desiredWidth = this._options.width || requiredWidth;
  41663. var desiredHeight = this._options.height || requiredHeight;
  41664. if (this.renderTargetSamplingMode !== BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  41665. if (!this._options.width) {
  41666. desiredWidth = BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  41667. }
  41668. if (!this._options.height) {
  41669. desiredHeight = BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  41670. }
  41671. }
  41672. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  41673. if (this._textures.length > 0) {
  41674. for (var i = 0; i < this._textures.length; i++) {
  41675. this._engine._releaseTexture(this._textures.data[i]);
  41676. }
  41677. this._textures.reset();
  41678. }
  41679. this.width = desiredWidth;
  41680. this.height = desiredHeight;
  41681. var textureSize = { width: this.width, height: this.height };
  41682. var textureOptions = {
  41683. generateMipMaps: false,
  41684. generateDepthBuffer: camera._postProcesses.indexOf(this) === 0,
  41685. generateStencilBuffer: camera._postProcesses.indexOf(this) === 0 && this._engine.isStencilEnable,
  41686. samplingMode: this.renderTargetSamplingMode,
  41687. type: this._textureType
  41688. };
  41689. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  41690. if (this._reusable) {
  41691. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  41692. }
  41693. this.onSizeChangedObservable.notifyObservers(this);
  41694. }
  41695. this._textures.forEach(function (texture) {
  41696. if (texture.samples !== _this.samples) {
  41697. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  41698. }
  41699. });
  41700. if (this.enablePixelPerfectMode) {
  41701. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  41702. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd], 0, requiredWidth, requiredHeight);
  41703. }
  41704. else {
  41705. this._scaleRatio.copyFromFloats(1, 1);
  41706. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  41707. }
  41708. this.onActivateObservable.notifyObservers(camera);
  41709. // Clear
  41710. if (this.clearColor) {
  41711. this._engine.clear(this.clearColor, true, true, true);
  41712. }
  41713. else {
  41714. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true, true);
  41715. }
  41716. if (this._reusable) {
  41717. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  41718. }
  41719. };
  41720. Object.defineProperty(PostProcess.prototype, "isSupported", {
  41721. get: function () {
  41722. return this._effect.isSupported;
  41723. },
  41724. enumerable: true,
  41725. configurable: true
  41726. });
  41727. PostProcess.prototype.apply = function () {
  41728. // Check
  41729. if (!this._effect.isReady())
  41730. return null;
  41731. // States
  41732. this._engine.enableEffect(this._effect);
  41733. this._engine.setState(false);
  41734. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  41735. this._engine.setDepthBuffer(false);
  41736. this._engine.setDepthWrite(false);
  41737. // Texture
  41738. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  41739. // Parameters
  41740. this._effect.setVector2("scale", this._scaleRatio);
  41741. this.onApplyObservable.notifyObservers(this._effect);
  41742. return this._effect;
  41743. };
  41744. PostProcess.prototype.dispose = function (camera) {
  41745. camera = camera || this._camera;
  41746. if (this._textures.length > 0) {
  41747. for (var i = 0; i < this._textures.length; i++) {
  41748. this._engine._releaseTexture(this._textures.data[i]);
  41749. }
  41750. }
  41751. this._textures.dispose();
  41752. if (!camera) {
  41753. return;
  41754. }
  41755. camera.detachPostProcess(this);
  41756. var index = camera._postProcesses.indexOf(this);
  41757. if (index === 0 && camera._postProcesses.length > 0) {
  41758. this._camera._postProcesses[0].markTextureDirty();
  41759. }
  41760. this.onActivateObservable.clear();
  41761. this.onAfterRenderObservable.clear();
  41762. this.onApplyObservable.clear();
  41763. this.onBeforeRenderObservable.clear();
  41764. this.onSizeChangedObservable.clear();
  41765. };
  41766. return PostProcess;
  41767. }());
  41768. BABYLON.PostProcess = PostProcess;
  41769. })(BABYLON || (BABYLON = {}));
  41770. //# sourceMappingURL=babylon.postProcess.js.map
  41771. var BABYLON;
  41772. (function (BABYLON) {
  41773. var PassPostProcess = (function (_super) {
  41774. __extends(PassPostProcess, _super);
  41775. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  41776. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  41777. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  41778. }
  41779. return PassPostProcess;
  41780. }(BABYLON.PostProcess));
  41781. BABYLON.PassPostProcess = PassPostProcess;
  41782. })(BABYLON || (BABYLON = {}));
  41783. //# sourceMappingURL=babylon.passPostProcess.js.map
  41784. var BABYLON;
  41785. (function (BABYLON) {
  41786. var ShadowGenerator = (function () {
  41787. /**
  41788. * Creates a ShadowGenerator object.
  41789. * A ShadowGenerator is the required tool to use the shadows.
  41790. * Each light casting shadows needs to use its own ShadowGenerator.
  41791. * Required parameters :
  41792. * - `mapSize` (integer), the size of the texture what stores the shadows. Example : 1024.
  41793. * - `light` : the light object generating the shadows.
  41794. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  41795. */
  41796. function ShadowGenerator(mapSize, light) {
  41797. var _this = this;
  41798. // Members
  41799. this._filter = ShadowGenerator.FILTER_NONE;
  41800. this.blurScale = 2;
  41801. this._blurBoxOffset = 0;
  41802. this._bias = 0.00005;
  41803. this._lightDirection = BABYLON.Vector3.Zero();
  41804. this.forceBackFacesOnly = false;
  41805. this._darkness = 0;
  41806. this._transparencyShadow = false;
  41807. this._viewMatrix = BABYLON.Matrix.Zero();
  41808. this._projectionMatrix = BABYLON.Matrix.Zero();
  41809. this._transformMatrix = BABYLON.Matrix.Zero();
  41810. this._worldViewProjection = BABYLON.Matrix.Zero();
  41811. this._currentFaceIndex = 0;
  41812. this._currentFaceIndexCache = 0;
  41813. this._useFullFloat = true;
  41814. this._light = light;
  41815. this._scene = light.getScene();
  41816. this._mapSize = mapSize;
  41817. light._shadowGenerator = this;
  41818. light._markMeshesAsLightDirty();
  41819. // Texture type fallback from float to int if not supported.
  41820. var textureType;
  41821. var caps = this._scene.getEngine().getCaps();
  41822. if (caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender) {
  41823. this._useFullFloat = true;
  41824. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  41825. }
  41826. else {
  41827. this._useFullFloat = false;
  41828. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  41829. }
  41830. // Render target
  41831. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, textureType, light.needCube());
  41832. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41833. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41834. this._shadowMap.anisotropicFilteringLevel = 1;
  41835. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  41836. this._shadowMap.renderParticles = false;
  41837. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  41838. _this._currentFaceIndex = faceIndex;
  41839. });
  41840. this._shadowMap.onAfterUnbindObservable.add(function () {
  41841. if (!_this.useBlurExponentialShadowMap) {
  41842. return;
  41843. }
  41844. if (!_this._shadowMap2) {
  41845. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false, true, textureType);
  41846. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41847. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41848. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  41849. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine(), false, textureType);
  41850. _this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  41851. effect.setTexture("textureSampler", _this._shadowMap);
  41852. });
  41853. _this.blurBoxOffset = 1;
  41854. }
  41855. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  41856. });
  41857. // Custom render function
  41858. var renderSubMesh = function (subMesh) {
  41859. var mesh = subMesh.getRenderingMesh();
  41860. var scene = _this._scene;
  41861. var engine = scene.getEngine();
  41862. // Culling
  41863. engine.setState(subMesh.getMaterial().backFaceCulling);
  41864. // Managing instances
  41865. var batch = mesh._getInstancesRenderList(subMesh._id);
  41866. if (batch.mustReturn) {
  41867. return;
  41868. }
  41869. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  41870. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  41871. engine.enableEffect(_this._effect);
  41872. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  41873. var material = subMesh.getMaterial();
  41874. _this._effect.setFloat2("biasAndScale", _this.bias, _this.depthScale);
  41875. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  41876. _this._effect.setVector3("lightPosition", _this.getLight().position);
  41877. if (_this.getLight().needCube()) {
  41878. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  41879. }
  41880. // Alpha test
  41881. if (material && material.needAlphaTesting()) {
  41882. var alphaTexture = material.getAlphaTestTexture();
  41883. _this._effect.setTexture("diffuseSampler", alphaTexture);
  41884. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  41885. }
  41886. // Bones
  41887. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  41888. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  41889. }
  41890. if (_this.forceBackFacesOnly) {
  41891. engine.setState(true, 0, false, true);
  41892. }
  41893. // Draw
  41894. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  41895. if (_this.forceBackFacesOnly) {
  41896. engine.setState(true, 0, false, false);
  41897. }
  41898. }
  41899. else {
  41900. // Need to reset refresh rate of the shadowMap
  41901. _this._shadowMap.resetRefreshCounter();
  41902. }
  41903. };
  41904. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  41905. var index;
  41906. for (index = 0; index < opaqueSubMeshes.length; index++) {
  41907. renderSubMesh(opaqueSubMeshes.data[index]);
  41908. }
  41909. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  41910. renderSubMesh(alphaTestSubMeshes.data[index]);
  41911. }
  41912. if (_this._transparencyShadow) {
  41913. for (index = 0; index < transparentSubMeshes.length; index++) {
  41914. renderSubMesh(transparentSubMeshes.data[index]);
  41915. }
  41916. }
  41917. };
  41918. this._shadowMap.onClearObservable.add(function (engine) {
  41919. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  41920. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  41921. }
  41922. else {
  41923. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  41924. }
  41925. });
  41926. }
  41927. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  41928. // Static
  41929. get: function () {
  41930. return ShadowGenerator._FILTER_NONE;
  41931. },
  41932. enumerable: true,
  41933. configurable: true
  41934. });
  41935. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  41936. get: function () {
  41937. return ShadowGenerator._FILTER_POISSONSAMPLING;
  41938. },
  41939. enumerable: true,
  41940. configurable: true
  41941. });
  41942. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  41943. get: function () {
  41944. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  41945. },
  41946. enumerable: true,
  41947. configurable: true
  41948. });
  41949. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  41950. get: function () {
  41951. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  41952. },
  41953. enumerable: true,
  41954. configurable: true
  41955. });
  41956. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  41957. get: function () {
  41958. return this._bias;
  41959. },
  41960. set: function (bias) {
  41961. this._bias = bias;
  41962. },
  41963. enumerable: true,
  41964. configurable: true
  41965. });
  41966. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  41967. get: function () {
  41968. return this._blurBoxOffset;
  41969. },
  41970. set: function (value) {
  41971. var _this = this;
  41972. if (this._blurBoxOffset === value) {
  41973. return;
  41974. }
  41975. this._blurBoxOffset = value;
  41976. if (this._boxBlurPostprocess) {
  41977. this._boxBlurPostprocess.dispose();
  41978. }
  41979. var textureType;
  41980. var caps = this._scene.getEngine().getCaps();
  41981. if (this._useFullFloat) {
  41982. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  41983. }
  41984. else {
  41985. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  41986. }
  41987. 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);
  41988. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  41989. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  41990. });
  41991. },
  41992. enumerable: true,
  41993. configurable: true
  41994. });
  41995. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  41996. get: function () {
  41997. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  41998. },
  41999. set: function (value) {
  42000. this._depthScale = value;
  42001. },
  42002. enumerable: true,
  42003. configurable: true
  42004. });
  42005. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  42006. get: function () {
  42007. return this._filter;
  42008. },
  42009. set: function (value) {
  42010. if (this._filter === value) {
  42011. return;
  42012. }
  42013. this._filter = value;
  42014. if (this.usePoissonSampling || this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  42015. this._shadowMap.anisotropicFilteringLevel = 16;
  42016. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  42017. }
  42018. else {
  42019. this._shadowMap.anisotropicFilteringLevel = 1;
  42020. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  42021. }
  42022. this._light._markMeshesAsLightDirty();
  42023. },
  42024. enumerable: true,
  42025. configurable: true
  42026. });
  42027. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  42028. get: function () {
  42029. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  42030. return this.useExponentialShadowMap;
  42031. },
  42032. set: function (value) {
  42033. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  42034. this.useExponentialShadowMap = value;
  42035. },
  42036. enumerable: true,
  42037. configurable: true
  42038. });
  42039. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  42040. get: function () {
  42041. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  42042. },
  42043. set: function (value) {
  42044. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  42045. },
  42046. enumerable: true,
  42047. configurable: true
  42048. });
  42049. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  42050. get: function () {
  42051. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  42052. },
  42053. set: function (value) {
  42054. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  42055. },
  42056. enumerable: true,
  42057. configurable: true
  42058. });
  42059. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  42060. get: function () {
  42061. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  42062. return this.useBlurExponentialShadowMap;
  42063. },
  42064. set: function (value) {
  42065. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  42066. this.useBlurExponentialShadowMap = value;
  42067. },
  42068. enumerable: true,
  42069. configurable: true
  42070. });
  42071. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  42072. get: function () {
  42073. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  42074. },
  42075. set: function (value) {
  42076. if (this._light.needCube() && value) {
  42077. this.useExponentialShadowMap = true; // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  42078. }
  42079. else {
  42080. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  42081. }
  42082. },
  42083. enumerable: true,
  42084. configurable: true
  42085. });
  42086. /**
  42087. * Boolean : true when the ShadowGenerator is finally computed.
  42088. */
  42089. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  42090. var defines = [];
  42091. if (this._useFullFloat) {
  42092. defines.push("#define FULLFLOAT");
  42093. }
  42094. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  42095. defines.push("#define ESM");
  42096. }
  42097. if (this.getLight().needCube()) {
  42098. defines.push("#define CUBEMAP");
  42099. }
  42100. var attribs = [BABYLON.VertexBuffer.PositionKind];
  42101. var mesh = subMesh.getMesh();
  42102. var material = subMesh.getMaterial();
  42103. // Alpha test
  42104. if (material && material.needAlphaTesting()) {
  42105. defines.push("#define ALPHATEST");
  42106. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  42107. attribs.push(BABYLON.VertexBuffer.UVKind);
  42108. defines.push("#define UV1");
  42109. }
  42110. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  42111. var alphaTexture = material.getAlphaTestTexture();
  42112. if (alphaTexture.coordinatesIndex === 1) {
  42113. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  42114. defines.push("#define UV2");
  42115. }
  42116. }
  42117. }
  42118. // Bones
  42119. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  42120. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  42121. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  42122. if (mesh.numBoneInfluencers > 4) {
  42123. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  42124. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  42125. }
  42126. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  42127. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  42128. }
  42129. else {
  42130. defines.push("#define NUM_BONE_INFLUENCERS 0");
  42131. }
  42132. // Instances
  42133. if (useInstances) {
  42134. defines.push("#define INSTANCES");
  42135. attribs.push("world0");
  42136. attribs.push("world1");
  42137. attribs.push("world2");
  42138. attribs.push("world3");
  42139. }
  42140. // Get correct effect
  42141. var join = defines.join("\n");
  42142. if (this._cachedDefines !== join) {
  42143. this._cachedDefines = join;
  42144. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  42145. }
  42146. return this._effect.isReady();
  42147. };
  42148. /**
  42149. * Returns a RenderTargetTexture object : the shadow map texture.
  42150. */
  42151. ShadowGenerator.prototype.getShadowMap = function () {
  42152. return this._shadowMap;
  42153. };
  42154. /**
  42155. * Returns the most ready computed shadow map as a RenderTargetTexture object.
  42156. */
  42157. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  42158. if (this._shadowMap2) {
  42159. return this._shadowMap2;
  42160. }
  42161. return this._shadowMap;
  42162. };
  42163. /**
  42164. * Returns the associated light object.
  42165. */
  42166. ShadowGenerator.prototype.getLight = function () {
  42167. return this._light;
  42168. };
  42169. // Methods
  42170. /**
  42171. * Returns a Matrix object : the updated transformation matrix.
  42172. */
  42173. ShadowGenerator.prototype.getTransformMatrix = function () {
  42174. var scene = this._scene;
  42175. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  42176. return this._transformMatrix;
  42177. }
  42178. this._currentRenderID = scene.getRenderId();
  42179. this._currentFaceIndexCache = this._currentFaceIndex;
  42180. var lightPosition = this._light.position;
  42181. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  42182. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  42183. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  42184. }
  42185. if (this._light.computeTransformedPosition()) {
  42186. lightPosition = this._light.transformedPosition;
  42187. }
  42188. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  42189. this._cachedPosition = lightPosition.clone();
  42190. this._cachedDirection = this._lightDirection.clone();
  42191. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  42192. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  42193. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  42194. }
  42195. return this._transformMatrix;
  42196. };
  42197. /**
  42198. * Returns the darkness value (float).
  42199. */
  42200. ShadowGenerator.prototype.getDarkness = function () {
  42201. return this._darkness;
  42202. };
  42203. /**
  42204. * Sets the ShadowGenerator darkness value (float <= 1.0).
  42205. * Returns the ShadowGenerator.
  42206. */
  42207. ShadowGenerator.prototype.setDarkness = function (darkness) {
  42208. if (darkness >= 1.0)
  42209. this._darkness = 1.0;
  42210. else if (darkness <= 0.0)
  42211. this._darkness = 0.0;
  42212. else
  42213. this._darkness = darkness;
  42214. return this;
  42215. };
  42216. /**
  42217. * Sets the ability to have transparent shadow (boolean).
  42218. * Returns the ShadowGenerator.
  42219. */
  42220. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  42221. this._transparencyShadow = hasShadow;
  42222. return this;
  42223. };
  42224. ShadowGenerator.prototype._packHalf = function (depth) {
  42225. var scale = depth * 255.0;
  42226. var fract = scale - Math.floor(scale);
  42227. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  42228. };
  42229. /**
  42230. * Disposes the ShadowGenerator.
  42231. * Returns nothing.
  42232. */
  42233. ShadowGenerator.prototype.dispose = function () {
  42234. this._shadowMap.dispose();
  42235. if (this._shadowMap2) {
  42236. this._shadowMap2.dispose();
  42237. }
  42238. if (this._downSamplePostprocess) {
  42239. this._downSamplePostprocess.dispose();
  42240. }
  42241. if (this._boxBlurPostprocess) {
  42242. this._boxBlurPostprocess.dispose();
  42243. }
  42244. this._light._shadowGenerator = null;
  42245. this._light._markMeshesAsLightDirty();
  42246. };
  42247. /**
  42248. * Serializes the ShadowGenerator and returns a serializationObject.
  42249. */
  42250. ShadowGenerator.prototype.serialize = function () {
  42251. var serializationObject = {};
  42252. serializationObject.lightId = this._light.id;
  42253. serializationObject.mapSize = this.getShadowMap().getRenderSize();
  42254. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  42255. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  42256. serializationObject.usePoissonSampling = this.usePoissonSampling;
  42257. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  42258. serializationObject.depthScale = this.depthScale;
  42259. serializationObject.darkness = this.getDarkness();
  42260. serializationObject.renderList = [];
  42261. for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
  42262. var mesh = this.getShadowMap().renderList[meshIndex];
  42263. serializationObject.renderList.push(mesh.id);
  42264. }
  42265. return serializationObject;
  42266. };
  42267. /**
  42268. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  42269. */
  42270. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  42271. //casting to point light, as light is missing the position attr and typescript complains.
  42272. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  42273. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  42274. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  42275. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  42276. meshes.forEach(function (mesh) {
  42277. shadowGenerator.getShadowMap().renderList.push(mesh);
  42278. });
  42279. }
  42280. if (parsedShadowGenerator.usePoissonSampling) {
  42281. shadowGenerator.usePoissonSampling = true;
  42282. }
  42283. else if (parsedShadowGenerator.useExponentialShadowMap) {
  42284. shadowGenerator.useExponentialShadowMap = true;
  42285. }
  42286. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  42287. shadowGenerator.useBlurExponentialShadowMap = true;
  42288. }
  42289. else if (parsedShadowGenerator.useVarianceShadowMap) {
  42290. shadowGenerator.useExponentialShadowMap = true;
  42291. }
  42292. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  42293. shadowGenerator.useBlurExponentialShadowMap = true;
  42294. }
  42295. if (parsedShadowGenerator.depthScale) {
  42296. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  42297. }
  42298. if (parsedShadowGenerator.blurScale) {
  42299. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  42300. }
  42301. if (parsedShadowGenerator.blurBoxOffset) {
  42302. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  42303. }
  42304. if (parsedShadowGenerator.bias !== undefined) {
  42305. shadowGenerator.bias = parsedShadowGenerator.bias;
  42306. }
  42307. if (parsedShadowGenerator.darkness) {
  42308. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  42309. }
  42310. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  42311. return shadowGenerator;
  42312. };
  42313. return ShadowGenerator;
  42314. }());
  42315. ShadowGenerator._FILTER_NONE = 0;
  42316. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  42317. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  42318. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  42319. BABYLON.ShadowGenerator = ShadowGenerator;
  42320. })(BABYLON || (BABYLON = {}));
  42321. //# sourceMappingURL=babylon.shadowGenerator.js.map
  42322. var BABYLON;
  42323. (function (BABYLON) {
  42324. var DefaultLoadingScreen = (function () {
  42325. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  42326. if (_loadingText === void 0) { _loadingText = ""; }
  42327. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  42328. var _this = this;
  42329. this._renderingCanvas = _renderingCanvas;
  42330. this._loadingText = _loadingText;
  42331. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  42332. // Resize
  42333. this._resizeLoadingUI = function () {
  42334. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  42335. _this._loadingDiv.style.position = "absolute";
  42336. _this._loadingDiv.style.left = canvasRect.left + "px";
  42337. _this._loadingDiv.style.top = canvasRect.top + "px";
  42338. _this._loadingDiv.style.width = canvasRect.width + "px";
  42339. _this._loadingDiv.style.height = canvasRect.height + "px";
  42340. };
  42341. }
  42342. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  42343. var _this = this;
  42344. if (this._loadingDiv) {
  42345. // Do not add a loading screen if there is already one
  42346. return;
  42347. }
  42348. this._loadingDiv = document.createElement("div");
  42349. this._loadingDiv.id = "babylonjsLoadingDiv";
  42350. this._loadingDiv.style.opacity = "0";
  42351. this._loadingDiv.style.transition = "opacity 1.5s ease";
  42352. // Loading text
  42353. this._loadingTextDiv = document.createElement("div");
  42354. this._loadingTextDiv.style.position = "absolute";
  42355. this._loadingTextDiv.style.left = "0";
  42356. this._loadingTextDiv.style.top = "50%";
  42357. this._loadingTextDiv.style.marginTop = "80px";
  42358. this._loadingTextDiv.style.width = "100%";
  42359. this._loadingTextDiv.style.height = "20px";
  42360. this._loadingTextDiv.style.fontFamily = "Arial";
  42361. this._loadingTextDiv.style.fontSize = "14px";
  42362. this._loadingTextDiv.style.color = "white";
  42363. this._loadingTextDiv.style.textAlign = "center";
  42364. this._loadingTextDiv.innerHTML = "Loading";
  42365. this._loadingDiv.appendChild(this._loadingTextDiv);
  42366. //set the predefined text
  42367. this._loadingTextDiv.innerHTML = this._loadingText;
  42368. // Loading img
  42369. var imgBack = new Image();
  42370. 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==";
  42371. imgBack.style.position = "absolute";
  42372. imgBack.style.left = "50%";
  42373. imgBack.style.top = "50%";
  42374. imgBack.style.marginLeft = "-50px";
  42375. imgBack.style.marginTop = "-50px";
  42376. imgBack.style.transition = "transform 1.0s ease";
  42377. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  42378. var deg = 360;
  42379. var onTransitionEnd = function () {
  42380. deg += 360;
  42381. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  42382. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  42383. };
  42384. imgBack.addEventListener("transitionend", onTransitionEnd);
  42385. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  42386. this._loadingDiv.appendChild(imgBack);
  42387. // front image
  42388. var imgFront = new Image();
  42389. 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=";
  42390. imgFront.style.position = "absolute";
  42391. imgFront.style.left = "50%";
  42392. imgFront.style.top = "50%";
  42393. imgFront.style.marginLeft = "-50px";
  42394. imgFront.style.marginTop = "-50px";
  42395. this._loadingDiv.appendChild(imgFront);
  42396. this._resizeLoadingUI();
  42397. window.addEventListener("resize", this._resizeLoadingUI);
  42398. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  42399. document.body.appendChild(this._loadingDiv);
  42400. setTimeout(function () {
  42401. _this._loadingDiv.style.opacity = "1";
  42402. imgBack.style.transform = "rotateZ(360deg)";
  42403. imgBack.style.webkitTransform = "rotateZ(360deg)";
  42404. }, 0);
  42405. };
  42406. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  42407. var _this = this;
  42408. if (!this._loadingDiv) {
  42409. return;
  42410. }
  42411. var onTransitionEnd = function () {
  42412. if (!_this._loadingDiv) {
  42413. return;
  42414. }
  42415. document.body.removeChild(_this._loadingDiv);
  42416. window.removeEventListener("resize", _this._resizeLoadingUI);
  42417. _this._loadingDiv = null;
  42418. };
  42419. this._loadingDiv.style.opacity = "0";
  42420. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  42421. };
  42422. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  42423. set: function (text) {
  42424. this._loadingText = text;
  42425. if (this._loadingTextDiv) {
  42426. this._loadingTextDiv.innerHTML = this._loadingText;
  42427. }
  42428. },
  42429. enumerable: true,
  42430. configurable: true
  42431. });
  42432. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  42433. get: function () {
  42434. return this._loadingDivBackgroundColor;
  42435. },
  42436. set: function (color) {
  42437. this._loadingDivBackgroundColor = color;
  42438. if (!this._loadingDiv) {
  42439. return;
  42440. }
  42441. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  42442. },
  42443. enumerable: true,
  42444. configurable: true
  42445. });
  42446. return DefaultLoadingScreen;
  42447. }());
  42448. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  42449. })(BABYLON || (BABYLON = {}));
  42450. //# sourceMappingURL=babylon.loadingScreen.js.map
  42451. var BABYLON;
  42452. (function (BABYLON) {
  42453. var SceneLoader = (function () {
  42454. function SceneLoader() {
  42455. }
  42456. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  42457. get: function () {
  42458. return 0;
  42459. },
  42460. enumerable: true,
  42461. configurable: true
  42462. });
  42463. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  42464. get: function () {
  42465. return 1;
  42466. },
  42467. enumerable: true,
  42468. configurable: true
  42469. });
  42470. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  42471. get: function () {
  42472. return 2;
  42473. },
  42474. enumerable: true,
  42475. configurable: true
  42476. });
  42477. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  42478. get: function () {
  42479. return 3;
  42480. },
  42481. enumerable: true,
  42482. configurable: true
  42483. });
  42484. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  42485. get: function () {
  42486. return SceneLoader._ForceFullSceneLoadingForIncremental;
  42487. },
  42488. set: function (value) {
  42489. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  42490. },
  42491. enumerable: true,
  42492. configurable: true
  42493. });
  42494. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  42495. get: function () {
  42496. return SceneLoader._ShowLoadingScreen;
  42497. },
  42498. set: function (value) {
  42499. SceneLoader._ShowLoadingScreen = value;
  42500. },
  42501. enumerable: true,
  42502. configurable: true
  42503. });
  42504. Object.defineProperty(SceneLoader, "loggingLevel", {
  42505. get: function () {
  42506. return SceneLoader._loggingLevel;
  42507. },
  42508. set: function (value) {
  42509. SceneLoader._loggingLevel = value;
  42510. },
  42511. enumerable: true,
  42512. configurable: true
  42513. });
  42514. SceneLoader._getDefaultPlugin = function () {
  42515. return SceneLoader._registeredPlugins[".babylon"];
  42516. };
  42517. SceneLoader._getPluginForExtension = function (extension) {
  42518. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  42519. if (registeredPlugin) {
  42520. return registeredPlugin;
  42521. }
  42522. return SceneLoader._getDefaultPlugin();
  42523. };
  42524. SceneLoader._getPluginForFilename = function (sceneFilename) {
  42525. if (sceneFilename.name) {
  42526. sceneFilename = sceneFilename.name;
  42527. }
  42528. var dotPosition = sceneFilename.lastIndexOf(".");
  42529. var queryStringPosition = sceneFilename.indexOf("?");
  42530. if (queryStringPosition === -1) {
  42531. queryStringPosition = sceneFilename.length;
  42532. }
  42533. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  42534. return SceneLoader._getPluginForExtension(extension);
  42535. };
  42536. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  42537. SceneLoader._getDirectLoad = function (sceneFilename) {
  42538. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  42539. return sceneFilename.substr(5);
  42540. }
  42541. return null;
  42542. };
  42543. // Public functions
  42544. SceneLoader.GetPluginForExtension = function (extension) {
  42545. return SceneLoader._getPluginForExtension(extension).plugin;
  42546. };
  42547. SceneLoader.RegisterPlugin = function (plugin) {
  42548. if (typeof plugin.extensions === "string") {
  42549. var extension = plugin.extensions;
  42550. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  42551. plugin: plugin,
  42552. isBinary: false
  42553. };
  42554. }
  42555. else {
  42556. var extensions = plugin.extensions;
  42557. Object.keys(extensions).forEach(function (extension) {
  42558. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  42559. plugin: plugin,
  42560. isBinary: extensions[extension].isBinary
  42561. };
  42562. });
  42563. }
  42564. };
  42565. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  42566. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  42567. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  42568. return;
  42569. }
  42570. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  42571. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  42572. return;
  42573. }
  42574. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  42575. var loadingToken = {};
  42576. scene._addPendingData(loadingToken);
  42577. var manifestChecked = function (success) {
  42578. scene.database = database;
  42579. var registeredPlugin = directLoad ? SceneLoader._getDefaultPlugin() : SceneLoader._getPluginForFilename(sceneFilename);
  42580. var plugin = registeredPlugin.plugin;
  42581. var useArrayBuffer = registeredPlugin.isBinary;
  42582. var importMeshFromData = function (data) {
  42583. var meshes = [];
  42584. var particleSystems = [];
  42585. var skeletons = [];
  42586. if (scene.isDisposed) {
  42587. if (onerror) {
  42588. onerror(scene, 'Scene was disposed before being able to load ' + rootUrl + sceneFilename);
  42589. }
  42590. return;
  42591. }
  42592. try {
  42593. if (plugin.importMesh) {
  42594. var syncedPlugin = plugin;
  42595. if (!syncedPlugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  42596. if (onerror) {
  42597. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  42598. }
  42599. scene._removePendingData(loadingToken);
  42600. return;
  42601. }
  42602. if (onsuccess) {
  42603. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  42604. onsuccess(meshes, particleSystems, skeletons);
  42605. scene._removePendingData(loadingToken);
  42606. }
  42607. }
  42608. else {
  42609. var asyncedPlugin = plugin;
  42610. asyncedPlugin.importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  42611. if (onsuccess) {
  42612. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  42613. onsuccess(meshes, particleSystems, skeletons);
  42614. scene._removePendingData(loadingToken);
  42615. }
  42616. }, function () {
  42617. if (onerror) {
  42618. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  42619. }
  42620. scene._removePendingData(loadingToken);
  42621. });
  42622. }
  42623. }
  42624. catch (e) {
  42625. if (onerror) {
  42626. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename, e);
  42627. }
  42628. scene._removePendingData(loadingToken);
  42629. }
  42630. };
  42631. if (directLoad) {
  42632. importMeshFromData(directLoad);
  42633. return;
  42634. }
  42635. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  42636. importMeshFromData(data);
  42637. }, progressCallBack, database, useArrayBuffer, function () {
  42638. if (onerror) {
  42639. onerror(scene, 'Unable to load file ' + rootUrl + sceneFilename);
  42640. }
  42641. });
  42642. };
  42643. if (scene.getEngine().enableOfflineSupport && !directLoad) {
  42644. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  42645. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  42646. }
  42647. else {
  42648. // If the scene is a data stream or offline support is not enabled, it's a direct load
  42649. manifestChecked(true);
  42650. }
  42651. };
  42652. /**
  42653. * Load a scene
  42654. * @param rootUrl a string that defines the root url for scene and resources
  42655. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  42656. * @param engine is the instance of BABYLON.Engine to use to create the scene
  42657. */
  42658. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  42659. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  42660. };
  42661. /**
  42662. * Append a scene
  42663. * @param rootUrl a string that defines the root url for scene and resources
  42664. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  42665. * @param scene is the instance of BABYLON.Scene to append to
  42666. */
  42667. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  42668. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  42669. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  42670. return;
  42671. }
  42672. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  42673. var registeredPlugin = directLoad ? SceneLoader._getDefaultPlugin() : SceneLoader._getPluginForFilename(sceneFilename);
  42674. var plugin = registeredPlugin.plugin;
  42675. var useArrayBuffer = registeredPlugin.isBinary;
  42676. var database;
  42677. var loadingToken = {};
  42678. scene._addPendingData(loadingToken);
  42679. if (SceneLoader.ShowLoadingScreen) {
  42680. scene.getEngine().displayLoadingUI();
  42681. }
  42682. var loadSceneFromData = function (data) {
  42683. scene.database = database;
  42684. if (plugin.load) {
  42685. var syncedPlugin = plugin;
  42686. if (!syncedPlugin.load(scene, data, rootUrl)) {
  42687. if (onerror) {
  42688. onerror(scene);
  42689. }
  42690. scene._removePendingData(loadingToken);
  42691. scene.getEngine().hideLoadingUI();
  42692. return;
  42693. }
  42694. if (onsuccess) {
  42695. onsuccess(scene);
  42696. }
  42697. scene._removePendingData(loadingToken);
  42698. }
  42699. else {
  42700. var asyncedPlugin = plugin;
  42701. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  42702. if (onsuccess) {
  42703. onsuccess(scene);
  42704. }
  42705. scene._removePendingData(loadingToken);
  42706. }, function () {
  42707. if (onerror) {
  42708. onerror(scene);
  42709. }
  42710. scene._removePendingData(loadingToken);
  42711. scene.getEngine().hideLoadingUI();
  42712. });
  42713. }
  42714. if (SceneLoader.ShowLoadingScreen) {
  42715. scene.executeWhenReady(function () {
  42716. scene.getEngine().hideLoadingUI();
  42717. });
  42718. }
  42719. };
  42720. var manifestChecked = function (success) {
  42721. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database, useArrayBuffer);
  42722. };
  42723. if (directLoad) {
  42724. loadSceneFromData(directLoad);
  42725. return;
  42726. }
  42727. if (rootUrl.indexOf("file:") === -1) {
  42728. if (scene.getEngine().enableOfflineSupport) {
  42729. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  42730. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  42731. }
  42732. else {
  42733. manifestChecked(true);
  42734. }
  42735. }
  42736. else {
  42737. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack, useArrayBuffer);
  42738. }
  42739. };
  42740. return SceneLoader;
  42741. }());
  42742. // Flags
  42743. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  42744. SceneLoader._ShowLoadingScreen = true;
  42745. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  42746. // Members
  42747. SceneLoader._registeredPlugins = {};
  42748. BABYLON.SceneLoader = SceneLoader;
  42749. ;
  42750. })(BABYLON || (BABYLON = {}));
  42751. //# sourceMappingURL=babylon.sceneLoader.js.map
  42752. var BABYLON;
  42753. (function (BABYLON) {
  42754. var Internals;
  42755. (function (Internals) {
  42756. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  42757. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  42758. var parsedMaterial = parsedData.materials[index];
  42759. if (parsedMaterial.id === id) {
  42760. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  42761. }
  42762. }
  42763. return null;
  42764. };
  42765. var isDescendantOf = function (mesh, names, hierarchyIds) {
  42766. names = (names instanceof Array) ? names : [names];
  42767. for (var i in names) {
  42768. if (mesh.name === names[i]) {
  42769. hierarchyIds.push(mesh.id);
  42770. return true;
  42771. }
  42772. }
  42773. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  42774. hierarchyIds.push(mesh.id);
  42775. return true;
  42776. }
  42777. return false;
  42778. };
  42779. var logOperation = function (operation, producer) {
  42780. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  42781. };
  42782. BABYLON.SceneLoader.RegisterPlugin({
  42783. extensions: ".babylon",
  42784. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  42785. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  42786. // when SceneLoader.debugLogging = true (default), or exception encountered.
  42787. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  42788. // and avoid problems with multiple concurrent .babylon loads.
  42789. var log = "importMesh has failed JSON parse";
  42790. try {
  42791. var parsedData = JSON.parse(data);
  42792. log = "";
  42793. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  42794. var loadedSkeletonsIds = [];
  42795. var loadedMaterialsIds = [];
  42796. var hierarchyIds = [];
  42797. var index;
  42798. var cache;
  42799. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  42800. var parsedMesh = parsedData.meshes[index];
  42801. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  42802. if (meshesNames instanceof Array) {
  42803. // Remove found mesh name from list.
  42804. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  42805. }
  42806. //Geometry?
  42807. if (parsedMesh.geometryId) {
  42808. //does the file contain geometries?
  42809. if (parsedData.geometries) {
  42810. //find the correct geometry and add it to the scene
  42811. var found = false;
  42812. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  42813. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  42814. return;
  42815. }
  42816. else {
  42817. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  42818. if (parsedGeometryData.id === parsedMesh.geometryId) {
  42819. switch (geometryType) {
  42820. case "boxes":
  42821. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  42822. break;
  42823. case "spheres":
  42824. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  42825. break;
  42826. case "cylinders":
  42827. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  42828. break;
  42829. case "toruses":
  42830. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  42831. break;
  42832. case "grounds":
  42833. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  42834. break;
  42835. case "planes":
  42836. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  42837. break;
  42838. case "torusKnots":
  42839. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  42840. break;
  42841. case "vertexData":
  42842. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  42843. break;
  42844. }
  42845. found = true;
  42846. }
  42847. });
  42848. }
  42849. });
  42850. if (!found) {
  42851. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  42852. }
  42853. }
  42854. }
  42855. // Material ?
  42856. if (parsedMesh.materialId) {
  42857. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  42858. if (!materialFound && parsedData.multiMaterials) {
  42859. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  42860. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  42861. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  42862. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  42863. var subMatId = parsedMultiMaterial.materials[matIndex];
  42864. loadedMaterialsIds.push(subMatId);
  42865. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  42866. log += "\n\tMaterial " + mat.toString(fullDetails);
  42867. }
  42868. loadedMaterialsIds.push(parsedMultiMaterial.id);
  42869. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  42870. materialFound = true;
  42871. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  42872. break;
  42873. }
  42874. }
  42875. }
  42876. if (!materialFound) {
  42877. loadedMaterialsIds.push(parsedMesh.materialId);
  42878. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  42879. if (!mat) {
  42880. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  42881. }
  42882. else {
  42883. log += "\n\tMaterial " + mat.toString(fullDetails);
  42884. }
  42885. }
  42886. }
  42887. // Skeleton ?
  42888. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  42889. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  42890. if (!skeletonAlreadyLoaded) {
  42891. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  42892. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  42893. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  42894. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  42895. skeletons.push(skeleton);
  42896. loadedSkeletonsIds.push(parsedSkeleton.id);
  42897. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  42898. }
  42899. }
  42900. }
  42901. }
  42902. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  42903. meshes.push(mesh);
  42904. log += "\n\tMesh " + mesh.toString(fullDetails);
  42905. }
  42906. }
  42907. // Connecting parents
  42908. var currentMesh;
  42909. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  42910. currentMesh = scene.meshes[index];
  42911. if (currentMesh._waitingParentId) {
  42912. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  42913. currentMesh._waitingParentId = undefined;
  42914. }
  42915. }
  42916. // freeze and compute world matrix application
  42917. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  42918. currentMesh = scene.meshes[index];
  42919. if (currentMesh._waitingFreezeWorldMatrix) {
  42920. currentMesh.freezeWorldMatrix();
  42921. currentMesh._waitingFreezeWorldMatrix = undefined;
  42922. }
  42923. else {
  42924. currentMesh.computeWorldMatrix(true);
  42925. }
  42926. }
  42927. // Particles
  42928. if (parsedData.particleSystems) {
  42929. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  42930. var parsedParticleSystem = parsedData.particleSystems[index];
  42931. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  42932. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  42933. }
  42934. }
  42935. }
  42936. return true;
  42937. }
  42938. catch (err) {
  42939. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log);
  42940. log = null;
  42941. throw err;
  42942. }
  42943. finally {
  42944. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  42945. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  42946. }
  42947. }
  42948. },
  42949. load: function (scene, data, rootUrl) {
  42950. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  42951. // when SceneLoader.debugLogging = true (default), or exception encountered.
  42952. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  42953. // and avoid problems with multiple concurrent .babylon loads.
  42954. var log = "importScene has failed JSON parse";
  42955. try {
  42956. var parsedData = JSON.parse(data);
  42957. log = "";
  42958. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  42959. // Scene
  42960. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  42961. scene.autoClear = parsedData.autoClear;
  42962. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  42963. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  42964. if (parsedData.gravity) {
  42965. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  42966. }
  42967. // Fog
  42968. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  42969. scene.fogMode = parsedData.fogMode;
  42970. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  42971. scene.fogStart = parsedData.fogStart;
  42972. scene.fogEnd = parsedData.fogEnd;
  42973. scene.fogDensity = parsedData.fogDensity;
  42974. log += "\tFog mode for scene: ";
  42975. switch (scene.fogMode) {
  42976. // getters not compiling, so using hardcoded
  42977. case 1:
  42978. log += "exp\n";
  42979. break;
  42980. case 2:
  42981. log += "exp2\n";
  42982. break;
  42983. case 3:
  42984. log += "linear\n";
  42985. break;
  42986. }
  42987. }
  42988. //Physics
  42989. if (parsedData.physicsEnabled) {
  42990. var physicsPlugin;
  42991. if (parsedData.physicsEngine === "cannon") {
  42992. physicsPlugin = new BABYLON.CannonJSPlugin();
  42993. }
  42994. else if (parsedData.physicsEngine === "oimo") {
  42995. physicsPlugin = new BABYLON.OimoJSPlugin();
  42996. }
  42997. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  42998. //else - default engine, which is currently oimo
  42999. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  43000. scene.enablePhysics(physicsGravity, physicsPlugin);
  43001. }
  43002. // Metadata
  43003. if (parsedData.metadata !== undefined) {
  43004. scene.metadata = parsedData.metadata;
  43005. }
  43006. //collisions, if defined. otherwise, default is true
  43007. if (parsedData.collisionsEnabled != undefined) {
  43008. scene.collisionsEnabled = parsedData.collisionsEnabled;
  43009. }
  43010. scene.workerCollisions = !!parsedData.workerCollisions;
  43011. var index;
  43012. var cache;
  43013. // Lights
  43014. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  43015. var parsedLight = parsedData.lights[index];
  43016. var light = BABYLON.Light.Parse(parsedLight, scene);
  43017. log += (index === 0 ? "\n\tLights:" : "");
  43018. log += "\n\t\t" + light.toString(fullDetails);
  43019. }
  43020. // Animations
  43021. if (parsedData.animations) {
  43022. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  43023. var parsedAnimation = parsedData.animations[index];
  43024. var animation = BABYLON.Animation.Parse(parsedAnimation);
  43025. scene.animations.push(animation);
  43026. log += (index === 0 ? "\n\tAnimations:" : "");
  43027. log += "\n\t\t" + animation.toString(fullDetails);
  43028. }
  43029. }
  43030. if (parsedData.autoAnimate) {
  43031. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  43032. }
  43033. // Materials
  43034. if (parsedData.materials) {
  43035. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  43036. var parsedMaterial = parsedData.materials[index];
  43037. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  43038. log += (index === 0 ? "\n\tMaterials:" : "");
  43039. log += "\n\t\t" + mat.toString(fullDetails);
  43040. }
  43041. }
  43042. if (parsedData.multiMaterials) {
  43043. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  43044. var parsedMultiMaterial = parsedData.multiMaterials[index];
  43045. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  43046. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  43047. log += "\n\t\t" + mmat.toString(fullDetails);
  43048. }
  43049. }
  43050. // Morph targets
  43051. if (parsedData.morphTargetManagers) {
  43052. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  43053. var managerData = _a[_i];
  43054. var parsedManager = BABYLON.MorphTargetManager.Parse(managerData, scene);
  43055. }
  43056. }
  43057. // Skeletons
  43058. if (parsedData.skeletons) {
  43059. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  43060. var parsedSkeleton = parsedData.skeletons[index];
  43061. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  43062. log += (index === 0 ? "\n\tSkeletons:" : "");
  43063. log += "\n\t\t" + skeleton.toString(fullDetails);
  43064. }
  43065. }
  43066. // Geometries
  43067. var geometries = parsedData.geometries;
  43068. if (geometries) {
  43069. // Boxes
  43070. var boxes = geometries.boxes;
  43071. if (boxes) {
  43072. for (index = 0, cache = boxes.length; index < cache; index++) {
  43073. var parsedBox = boxes[index];
  43074. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  43075. }
  43076. }
  43077. // Spheres
  43078. var spheres = geometries.spheres;
  43079. if (spheres) {
  43080. for (index = 0, cache = spheres.length; index < cache; index++) {
  43081. var parsedSphere = spheres[index];
  43082. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  43083. }
  43084. }
  43085. // Cylinders
  43086. var cylinders = geometries.cylinders;
  43087. if (cylinders) {
  43088. for (index = 0, cache = cylinders.length; index < cache; index++) {
  43089. var parsedCylinder = cylinders[index];
  43090. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  43091. }
  43092. }
  43093. // Toruses
  43094. var toruses = geometries.toruses;
  43095. if (toruses) {
  43096. for (index = 0, cache = toruses.length; index < cache; index++) {
  43097. var parsedTorus = toruses[index];
  43098. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  43099. }
  43100. }
  43101. // Grounds
  43102. var grounds = geometries.grounds;
  43103. if (grounds) {
  43104. for (index = 0, cache = grounds.length; index < cache; index++) {
  43105. var parsedGround = grounds[index];
  43106. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  43107. }
  43108. }
  43109. // Planes
  43110. var planes = geometries.planes;
  43111. if (planes) {
  43112. for (index = 0, cache = planes.length; index < cache; index++) {
  43113. var parsedPlane = planes[index];
  43114. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  43115. }
  43116. }
  43117. // TorusKnots
  43118. var torusKnots = geometries.torusKnots;
  43119. if (torusKnots) {
  43120. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  43121. var parsedTorusKnot = torusKnots[index];
  43122. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  43123. }
  43124. }
  43125. // VertexData
  43126. var vertexData = geometries.vertexData;
  43127. if (vertexData) {
  43128. for (index = 0, cache = vertexData.length; index < cache; index++) {
  43129. var parsedVertexData = vertexData[index];
  43130. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  43131. }
  43132. }
  43133. }
  43134. // Meshes
  43135. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  43136. var parsedMesh = parsedData.meshes[index];
  43137. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  43138. log += (index === 0 ? "\n\tMeshes:" : "");
  43139. log += "\n\t\t" + mesh.toString(fullDetails);
  43140. }
  43141. // Cameras
  43142. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  43143. var parsedCamera = parsedData.cameras[index];
  43144. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  43145. log += (index === 0 ? "\n\tCameras:" : "");
  43146. log += "\n\t\t" + camera.toString(fullDetails);
  43147. }
  43148. if (parsedData.activeCameraID) {
  43149. scene.setActiveCameraByID(parsedData.activeCameraID);
  43150. }
  43151. // Browsing all the graph to connect the dots
  43152. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  43153. var camera = scene.cameras[index];
  43154. if (camera._waitingParentId) {
  43155. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  43156. camera._waitingParentId = undefined;
  43157. }
  43158. }
  43159. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  43160. var light = scene.lights[index];
  43161. if (light._waitingParentId) {
  43162. light.parent = scene.getLastEntryByID(light._waitingParentId);
  43163. light._waitingParentId = undefined;
  43164. }
  43165. }
  43166. // Sounds
  43167. var loadedSounds = [];
  43168. var loadedSound;
  43169. if (BABYLON.AudioEngine && parsedData.sounds) {
  43170. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  43171. var parsedSound = parsedData.sounds[index];
  43172. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  43173. if (!parsedSound.url)
  43174. parsedSound.url = parsedSound.name;
  43175. if (!loadedSounds[parsedSound.url]) {
  43176. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  43177. loadedSounds[parsedSound.url] = loadedSound;
  43178. }
  43179. else {
  43180. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  43181. }
  43182. }
  43183. else {
  43184. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  43185. }
  43186. }
  43187. }
  43188. loadedSounds = [];
  43189. // Connect parents & children and parse actions
  43190. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  43191. var mesh = scene.meshes[index];
  43192. if (mesh._waitingParentId) {
  43193. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  43194. mesh._waitingParentId = undefined;
  43195. }
  43196. if (mesh._waitingActions) {
  43197. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  43198. mesh._waitingActions = undefined;
  43199. }
  43200. }
  43201. // freeze world matrix application
  43202. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  43203. var currentMesh = scene.meshes[index];
  43204. if (currentMesh._waitingFreezeWorldMatrix) {
  43205. currentMesh.freezeWorldMatrix();
  43206. currentMesh._waitingFreezeWorldMatrix = undefined;
  43207. }
  43208. else {
  43209. currentMesh.computeWorldMatrix(true);
  43210. }
  43211. }
  43212. // Particles Systems
  43213. if (parsedData.particleSystems) {
  43214. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  43215. var parsedParticleSystem = parsedData.particleSystems[index];
  43216. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  43217. }
  43218. }
  43219. // Lens flares
  43220. if (parsedData.lensFlareSystems) {
  43221. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  43222. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  43223. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  43224. }
  43225. }
  43226. // Shadows
  43227. if (parsedData.shadowGenerators) {
  43228. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  43229. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  43230. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  43231. }
  43232. }
  43233. // Lights exclusions / inclusions
  43234. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  43235. var light = scene.lights[index];
  43236. // Excluded check
  43237. if (light._excludedMeshesIds.length > 0) {
  43238. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  43239. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  43240. if (excludedMesh) {
  43241. light.excludedMeshes.push(excludedMesh);
  43242. }
  43243. }
  43244. light._excludedMeshesIds = [];
  43245. }
  43246. // Included check
  43247. if (light._includedOnlyMeshesIds.length > 0) {
  43248. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  43249. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  43250. if (includedOnlyMesh) {
  43251. light.includedOnlyMeshes.push(includedOnlyMesh);
  43252. }
  43253. }
  43254. light._includedOnlyMeshesIds = [];
  43255. }
  43256. }
  43257. // Actions (scene)
  43258. if (parsedData.actions) {
  43259. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  43260. }
  43261. // Finish
  43262. return true;
  43263. }
  43264. catch (err) {
  43265. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log);
  43266. log = null;
  43267. throw err;
  43268. }
  43269. finally {
  43270. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  43271. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  43272. }
  43273. }
  43274. }
  43275. });
  43276. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  43277. })(BABYLON || (BABYLON = {}));
  43278. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  43279. var BABYLON;
  43280. (function (BABYLON) {
  43281. var FilesInput = (function () {
  43282. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  43283. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  43284. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  43285. this._engine = p_engine;
  43286. this._canvas = p_canvas;
  43287. this._currentScene = p_scene;
  43288. this._sceneLoadedCallback = p_sceneLoadedCallback;
  43289. this._progressCallback = p_progressCallback;
  43290. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  43291. this._textureLoadingCallback = p_textureLoadingCallback;
  43292. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  43293. }
  43294. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  43295. var _this = this;
  43296. if (p_elementToMonitor) {
  43297. this._elementToMonitor = p_elementToMonitor;
  43298. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  43299. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  43300. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  43301. }
  43302. };
  43303. FilesInput.prototype.renderFunction = function () {
  43304. if (this._additionnalRenderLoopLogicCallback) {
  43305. this._additionnalRenderLoopLogicCallback();
  43306. }
  43307. if (this._currentScene) {
  43308. if (this._textureLoadingCallback) {
  43309. var remaining = this._currentScene.getWaitingItemsCount();
  43310. if (remaining > 0) {
  43311. this._textureLoadingCallback(remaining);
  43312. }
  43313. }
  43314. this._currentScene.render();
  43315. }
  43316. };
  43317. FilesInput.prototype.drag = function (e) {
  43318. e.stopPropagation();
  43319. e.preventDefault();
  43320. };
  43321. FilesInput.prototype.drop = function (eventDrop) {
  43322. eventDrop.stopPropagation();
  43323. eventDrop.preventDefault();
  43324. this.loadFiles(eventDrop);
  43325. };
  43326. FilesInput.prototype.loadFiles = function (event) {
  43327. if (this._startingProcessingFilesCallback)
  43328. this._startingProcessingFilesCallback();
  43329. // Handling data transfer via drag'n'drop
  43330. if (event && event.dataTransfer && event.dataTransfer.files) {
  43331. this._filesToLoad = event.dataTransfer.files;
  43332. }
  43333. // Handling files from input files
  43334. if (event && event.target && event.target.files) {
  43335. this._filesToLoad = event.target.files;
  43336. }
  43337. if (this._filesToLoad && this._filesToLoad.length > 0) {
  43338. for (var i = 0; i < this._filesToLoad.length; i++) {
  43339. var name_1 = this._filesToLoad[i].name.toLowerCase();
  43340. var extension = name_1.split('.').pop();
  43341. var type = this._filesToLoad[i].type;
  43342. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  43343. && name_1.indexOf(".binary.babylon") === -1 && name_1.indexOf(".incremental.babylon") === -1) {
  43344. this._sceneFileToLoad = this._filesToLoad[i];
  43345. }
  43346. else {
  43347. FilesInput.FilesToLoad[name_1] = this._filesToLoad[i];
  43348. }
  43349. }
  43350. this.reload();
  43351. }
  43352. };
  43353. FilesInput.prototype.reload = function () {
  43354. var _this = this;
  43355. var that = this;
  43356. // If a ".babylon" file has been provided
  43357. if (this._sceneFileToLoad) {
  43358. if (this._currentScene) {
  43359. if (BABYLON.Tools.errorsCount > 0) {
  43360. BABYLON.Tools.ClearLogCache();
  43361. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  43362. }
  43363. this._engine.stopRenderLoop();
  43364. this._currentScene.dispose();
  43365. }
  43366. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  43367. that._currentScene = newScene;
  43368. // Wait for textures and shaders to be ready
  43369. that._currentScene.executeWhenReady(function () {
  43370. if (that._sceneLoadedCallback) {
  43371. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  43372. }
  43373. that._engine.runRenderLoop(function () { that.renderFunction(); });
  43374. });
  43375. }, function (progress) {
  43376. if (_this._progressCallback) {
  43377. _this._progressCallback(progress);
  43378. }
  43379. });
  43380. }
  43381. else {
  43382. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  43383. }
  43384. };
  43385. return FilesInput;
  43386. }());
  43387. FilesInput.FilesToLoad = new Array();
  43388. BABYLON.FilesInput = FilesInput;
  43389. })(BABYLON || (BABYLON = {}));
  43390. //# sourceMappingURL=babylon.filesInput.js.map
  43391. var BABYLON;
  43392. (function (BABYLON) {
  43393. /**
  43394. * This class implement a typical dictionary using a string as key and the generic type T as value.
  43395. * The underlying implementation relies on an associative array to ensure the best performances.
  43396. * The value can be anything including 'null' but except 'undefined'
  43397. */
  43398. var StringDictionary = (function () {
  43399. function StringDictionary() {
  43400. this._count = 0;
  43401. this._data = {};
  43402. }
  43403. /**
  43404. * This will clear this dictionary and copy the content from the 'source' one.
  43405. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  43406. * @param source the dictionary to take the content from and copy to this dictionary
  43407. */
  43408. StringDictionary.prototype.copyFrom = function (source) {
  43409. var _this = this;
  43410. this.clear();
  43411. source.forEach(function (t, v) { return _this.add(t, v); });
  43412. };
  43413. /**
  43414. * Get a value based from its key
  43415. * @param key the given key to get the matching value from
  43416. * @return the value if found, otherwise undefined is returned
  43417. */
  43418. StringDictionary.prototype.get = function (key) {
  43419. var val = this._data[key];
  43420. if (val !== undefined) {
  43421. return val;
  43422. }
  43423. return undefined;
  43424. };
  43425. /**
  43426. * Get a value from its key or add it if it doesn't exist.
  43427. * This method will ensure you that a given key/data will be present in the dictionary.
  43428. * @param key the given key to get the matching value from
  43429. * @param factory the factory that will create the value if the key is not present in the dictionary.
  43430. * The factory will only be invoked if there's no data for the given key.
  43431. * @return the value corresponding to the key.
  43432. */
  43433. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  43434. var val = this.get(key);
  43435. if (val !== undefined) {
  43436. return val;
  43437. }
  43438. val = factory(key);
  43439. if (val) {
  43440. this.add(key, val);
  43441. }
  43442. return val;
  43443. };
  43444. /**
  43445. * Get a value from its key if present in the dictionary otherwise add it
  43446. * @param key the key to get the value from
  43447. * @param val if there's no such key/value pair in the dictionary add it with this value
  43448. * @return the value corresponding to the key
  43449. */
  43450. StringDictionary.prototype.getOrAdd = function (key, val) {
  43451. var curVal = this.get(key);
  43452. if (curVal !== undefined) {
  43453. return curVal;
  43454. }
  43455. this.add(key, val);
  43456. return val;
  43457. };
  43458. /**
  43459. * Check if there's a given key in the dictionary
  43460. * @param key the key to check for
  43461. * @return true if the key is present, false otherwise
  43462. */
  43463. StringDictionary.prototype.contains = function (key) {
  43464. return this._data[key] !== undefined;
  43465. };
  43466. /**
  43467. * Add a new key and its corresponding value
  43468. * @param key the key to add
  43469. * @param value the value corresponding to the key
  43470. * @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
  43471. */
  43472. StringDictionary.prototype.add = function (key, value) {
  43473. if (this._data[key] !== undefined) {
  43474. return false;
  43475. }
  43476. this._data[key] = value;
  43477. ++this._count;
  43478. return true;
  43479. };
  43480. StringDictionary.prototype.set = function (key, value) {
  43481. if (this._data[key] === undefined) {
  43482. return false;
  43483. }
  43484. this._data[key] = value;
  43485. return true;
  43486. };
  43487. /**
  43488. * Get the element of the given key and remove it from the dictionary
  43489. * @param key
  43490. */
  43491. StringDictionary.prototype.getAndRemove = function (key) {
  43492. var val = this.get(key);
  43493. if (val !== undefined) {
  43494. delete this._data[key];
  43495. --this._count;
  43496. return val;
  43497. }
  43498. return null;
  43499. };
  43500. /**
  43501. * Remove a key/value from the dictionary.
  43502. * @param key the key to remove
  43503. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  43504. */
  43505. StringDictionary.prototype.remove = function (key) {
  43506. if (this.contains(key)) {
  43507. delete this._data[key];
  43508. --this._count;
  43509. return true;
  43510. }
  43511. return false;
  43512. };
  43513. /**
  43514. * Clear the whole content of the dictionary
  43515. */
  43516. StringDictionary.prototype.clear = function () {
  43517. this._data = {};
  43518. this._count = 0;
  43519. };
  43520. Object.defineProperty(StringDictionary.prototype, "count", {
  43521. get: function () {
  43522. return this._count;
  43523. },
  43524. enumerable: true,
  43525. configurable: true
  43526. });
  43527. /**
  43528. * Execute a callback on each key/val of the dictionary.
  43529. * Note that you can remove any element in this dictionary in the callback implementation
  43530. * @param callback the callback to execute on a given key/value pair
  43531. */
  43532. StringDictionary.prototype.forEach = function (callback) {
  43533. for (var cur in this._data) {
  43534. var val = this._data[cur];
  43535. callback(cur, val);
  43536. }
  43537. };
  43538. /**
  43539. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  43540. * If the callback returns null or undefined the method will iterate to the next key/value pair
  43541. * Note that you can remove any element in this dictionary in the callback implementation
  43542. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  43543. */
  43544. StringDictionary.prototype.first = function (callback) {
  43545. for (var cur in this._data) {
  43546. var val = this._data[cur];
  43547. var res = callback(cur, val);
  43548. if (res) {
  43549. return res;
  43550. }
  43551. }
  43552. return null;
  43553. };
  43554. return StringDictionary;
  43555. }());
  43556. BABYLON.StringDictionary = StringDictionary;
  43557. })(BABYLON || (BABYLON = {}));
  43558. //# sourceMappingURL=babylon.stringDictionary.js.map
  43559. var BABYLON;
  43560. (function (BABYLON) {
  43561. var Tags = (function () {
  43562. function Tags() {
  43563. }
  43564. Tags.EnableFor = function (obj) {
  43565. obj._tags = obj._tags || {};
  43566. obj.hasTags = function () {
  43567. return Tags.HasTags(obj);
  43568. };
  43569. obj.addTags = function (tagsString) {
  43570. return Tags.AddTagsTo(obj, tagsString);
  43571. };
  43572. obj.removeTags = function (tagsString) {
  43573. return Tags.RemoveTagsFrom(obj, tagsString);
  43574. };
  43575. obj.matchesTagsQuery = function (tagsQuery) {
  43576. return Tags.MatchesQuery(obj, tagsQuery);
  43577. };
  43578. };
  43579. Tags.DisableFor = function (obj) {
  43580. delete obj._tags;
  43581. delete obj.hasTags;
  43582. delete obj.addTags;
  43583. delete obj.removeTags;
  43584. delete obj.matchesTagsQuery;
  43585. };
  43586. Tags.HasTags = function (obj) {
  43587. if (!obj._tags) {
  43588. return false;
  43589. }
  43590. return !BABYLON.Tools.IsEmpty(obj._tags);
  43591. };
  43592. Tags.GetTags = function (obj, asString) {
  43593. if (asString === void 0) { asString = true; }
  43594. if (!obj._tags) {
  43595. return null;
  43596. }
  43597. if (asString) {
  43598. var tagsArray = [];
  43599. for (var tag in obj._tags) {
  43600. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  43601. tagsArray.push(tag);
  43602. }
  43603. }
  43604. return tagsArray.join(" ");
  43605. }
  43606. else {
  43607. return obj._tags;
  43608. }
  43609. };
  43610. // the tags 'true' and 'false' are reserved and cannot be used as tags
  43611. // a tag cannot start with '||', '&&', and '!'
  43612. // it cannot contain whitespaces
  43613. Tags.AddTagsTo = function (obj, tagsString) {
  43614. if (!tagsString) {
  43615. return;
  43616. }
  43617. if (typeof tagsString !== "string") {
  43618. return;
  43619. }
  43620. var tags = tagsString.split(" ");
  43621. tags.forEach(function (tag, index, array) {
  43622. Tags._AddTagTo(obj, tag);
  43623. });
  43624. };
  43625. Tags._AddTagTo = function (obj, tag) {
  43626. tag = tag.trim();
  43627. if (tag === "" || tag === "true" || tag === "false") {
  43628. return;
  43629. }
  43630. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  43631. return;
  43632. }
  43633. Tags.EnableFor(obj);
  43634. obj._tags[tag] = true;
  43635. };
  43636. Tags.RemoveTagsFrom = function (obj, tagsString) {
  43637. if (!Tags.HasTags(obj)) {
  43638. return;
  43639. }
  43640. var tags = tagsString.split(" ");
  43641. for (var t in tags) {
  43642. Tags._RemoveTagFrom(obj, tags[t]);
  43643. }
  43644. };
  43645. Tags._RemoveTagFrom = function (obj, tag) {
  43646. delete obj._tags[tag];
  43647. };
  43648. Tags.MatchesQuery = function (obj, tagsQuery) {
  43649. if (tagsQuery === undefined) {
  43650. return true;
  43651. }
  43652. if (tagsQuery === "") {
  43653. return Tags.HasTags(obj);
  43654. }
  43655. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  43656. };
  43657. return Tags;
  43658. }());
  43659. BABYLON.Tags = Tags;
  43660. })(BABYLON || (BABYLON = {}));
  43661. //# sourceMappingURL=babylon.tags.js.map
  43662. var BABYLON;
  43663. (function (BABYLON) {
  43664. var Internals;
  43665. (function (Internals) {
  43666. var AndOrNotEvaluator = (function () {
  43667. function AndOrNotEvaluator() {
  43668. }
  43669. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  43670. if (!query.match(/\([^\(\)]*\)/g)) {
  43671. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  43672. }
  43673. else {
  43674. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  43675. // remove parenthesis
  43676. r = r.slice(1, r.length - 1);
  43677. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  43678. });
  43679. }
  43680. if (query === "true") {
  43681. return true;
  43682. }
  43683. if (query === "false") {
  43684. return false;
  43685. }
  43686. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  43687. };
  43688. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  43689. evaluateCallback = evaluateCallback || (function (r) {
  43690. return r === "true" ? true : false;
  43691. });
  43692. var result;
  43693. var or = parenthesisContent.split("||");
  43694. for (var i in or) {
  43695. if (or.hasOwnProperty(i)) {
  43696. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  43697. var and = ori.split("&&");
  43698. if (and.length > 1) {
  43699. for (var j = 0; j < and.length; ++j) {
  43700. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  43701. if (andj !== "true" && andj !== "false") {
  43702. if (andj[0] === "!") {
  43703. result = !evaluateCallback(andj.substring(1));
  43704. }
  43705. else {
  43706. result = evaluateCallback(andj);
  43707. }
  43708. }
  43709. else {
  43710. result = andj === "true" ? true : false;
  43711. }
  43712. if (!result) {
  43713. ori = "false";
  43714. break;
  43715. }
  43716. }
  43717. }
  43718. if (result || ori === "true") {
  43719. result = true;
  43720. break;
  43721. }
  43722. // result equals false (or undefined)
  43723. if (ori !== "true" && ori !== "false") {
  43724. if (ori[0] === "!") {
  43725. result = !evaluateCallback(ori.substring(1));
  43726. }
  43727. else {
  43728. result = evaluateCallback(ori);
  43729. }
  43730. }
  43731. else {
  43732. result = ori === "true" ? true : false;
  43733. }
  43734. }
  43735. }
  43736. // the whole parenthesis scope is replaced by 'true' or 'false'
  43737. return result ? "true" : "false";
  43738. };
  43739. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  43740. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  43741. // remove whitespaces
  43742. r = r.replace(/[\s]/g, function () { return ""; });
  43743. return r.length % 2 ? "!" : "";
  43744. });
  43745. booleanString = booleanString.trim();
  43746. if (booleanString === "!true") {
  43747. booleanString = "false";
  43748. }
  43749. else if (booleanString === "!false") {
  43750. booleanString = "true";
  43751. }
  43752. return booleanString;
  43753. };
  43754. return AndOrNotEvaluator;
  43755. }());
  43756. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  43757. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  43758. })(BABYLON || (BABYLON = {}));
  43759. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  43760. var BABYLON;
  43761. (function (BABYLON) {
  43762. var Database = (function () {
  43763. function Database(urlToScene, callbackManifestChecked) {
  43764. // Handling various flavors of prefixed version of IndexedDB
  43765. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  43766. this.callbackManifestChecked = callbackManifestChecked;
  43767. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  43768. this.db = null;
  43769. this.enableSceneOffline = false;
  43770. this.enableTexturesOffline = false;
  43771. this.manifestVersionFound = 0;
  43772. this.mustUpdateRessources = false;
  43773. this.hasReachedQuota = false;
  43774. if (!Database.IDBStorageEnabled) {
  43775. this.callbackManifestChecked(true);
  43776. }
  43777. else {
  43778. this.checkManifestFile();
  43779. }
  43780. }
  43781. Database.prototype.checkManifestFile = function () {
  43782. var _this = this;
  43783. function noManifestFile() {
  43784. that.enableSceneOffline = false;
  43785. that.enableTexturesOffline = false;
  43786. that.callbackManifestChecked(false);
  43787. }
  43788. var that = this;
  43789. var timeStampUsed = false;
  43790. var manifestURL = this.currentSceneUrl + ".manifest";
  43791. var xhr = new XMLHttpRequest();
  43792. if (navigator.onLine) {
  43793. // Adding a timestamp to by-pass browsers' cache
  43794. timeStampUsed = true;
  43795. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  43796. }
  43797. xhr.open("GET", manifestURL, true);
  43798. xhr.addEventListener("load", function () {
  43799. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  43800. try {
  43801. var manifestFile = JSON.parse(xhr.response);
  43802. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  43803. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  43804. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  43805. _this.manifestVersionFound = manifestFile.version;
  43806. }
  43807. if (_this.callbackManifestChecked) {
  43808. _this.callbackManifestChecked(true);
  43809. }
  43810. }
  43811. catch (ex) {
  43812. noManifestFile();
  43813. }
  43814. }
  43815. else {
  43816. noManifestFile();
  43817. }
  43818. }, false);
  43819. xhr.addEventListener("error", function (event) {
  43820. if (timeStampUsed) {
  43821. timeStampUsed = false;
  43822. // Let's retry without the timeStamp
  43823. // It could fail when coupled with HTML5 Offline API
  43824. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  43825. xhr.open("GET", retryManifestURL, true);
  43826. xhr.send();
  43827. }
  43828. else {
  43829. noManifestFile();
  43830. }
  43831. }, false);
  43832. try {
  43833. xhr.send();
  43834. }
  43835. catch (ex) {
  43836. BABYLON.Tools.Error("Error on XHR send request.");
  43837. that.callbackManifestChecked(false);
  43838. }
  43839. };
  43840. Database.prototype.openAsync = function (successCallback, errorCallback) {
  43841. var _this = this;
  43842. function handleError() {
  43843. that.isSupported = false;
  43844. if (errorCallback)
  43845. errorCallback();
  43846. }
  43847. var that = this;
  43848. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  43849. // Your browser doesn't support IndexedDB
  43850. this.isSupported = false;
  43851. if (errorCallback)
  43852. errorCallback();
  43853. }
  43854. else {
  43855. // If the DB hasn't been opened or created yet
  43856. if (!this.db) {
  43857. this.hasReachedQuota = false;
  43858. this.isSupported = true;
  43859. var request = this.idbFactory.open("babylonjs", 1);
  43860. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  43861. request.onerror = function (event) {
  43862. handleError();
  43863. };
  43864. // executes when a version change transaction cannot complete due to other active transactions
  43865. request.onblocked = function (event) {
  43866. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  43867. handleError();
  43868. };
  43869. // DB has been opened successfully
  43870. request.onsuccess = function (event) {
  43871. _this.db = request.result;
  43872. successCallback();
  43873. };
  43874. // Initialization of the DB. Creating Scenes & Textures stores
  43875. request.onupgradeneeded = function (event) {
  43876. _this.db = (event.target).result;
  43877. try {
  43878. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  43879. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  43880. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  43881. }
  43882. catch (ex) {
  43883. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  43884. handleError();
  43885. }
  43886. };
  43887. }
  43888. else {
  43889. if (successCallback)
  43890. successCallback();
  43891. }
  43892. }
  43893. };
  43894. Database.prototype.loadImageFromDB = function (url, image) {
  43895. var _this = this;
  43896. var completeURL = Database.ReturnFullUrlLocation(url);
  43897. var saveAndLoadImage = function () {
  43898. if (!_this.hasReachedQuota && _this.db !== null) {
  43899. // the texture is not yet in the DB, let's try to save it
  43900. _this._saveImageIntoDBAsync(completeURL, image);
  43901. }
  43902. else {
  43903. image.src = url;
  43904. }
  43905. };
  43906. if (!this.mustUpdateRessources) {
  43907. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  43908. }
  43909. else {
  43910. saveAndLoadImage();
  43911. }
  43912. };
  43913. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  43914. if (this.isSupported && this.db !== null) {
  43915. var texture;
  43916. var transaction = this.db.transaction(["textures"]);
  43917. transaction.onabort = function (event) {
  43918. image.src = url;
  43919. };
  43920. transaction.oncomplete = function (event) {
  43921. var blobTextureURL;
  43922. if (texture) {
  43923. var URL = window.URL || window.webkitURL;
  43924. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  43925. image.onerror = function () {
  43926. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  43927. image.src = url;
  43928. };
  43929. image.src = blobTextureURL;
  43930. }
  43931. else {
  43932. notInDBCallback();
  43933. }
  43934. };
  43935. var getRequest = transaction.objectStore("textures").get(url);
  43936. getRequest.onsuccess = function (event) {
  43937. texture = (event.target).result;
  43938. };
  43939. getRequest.onerror = function (event) {
  43940. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  43941. image.src = url;
  43942. };
  43943. }
  43944. else {
  43945. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  43946. image.src = url;
  43947. }
  43948. };
  43949. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  43950. var _this = this;
  43951. if (this.isSupported) {
  43952. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  43953. var generateBlobUrl = function () {
  43954. var blobTextureURL;
  43955. if (blob) {
  43956. var URL = window.URL || window.webkitURL;
  43957. try {
  43958. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  43959. }
  43960. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  43961. catch (ex) {
  43962. blobTextureURL = URL.createObjectURL(blob);
  43963. }
  43964. }
  43965. image.src = blobTextureURL;
  43966. };
  43967. if (Database.IsUASupportingBlobStorage) {
  43968. var xhr = new XMLHttpRequest(), blob;
  43969. xhr.open("GET", url, true);
  43970. xhr.responseType = "blob";
  43971. xhr.addEventListener("load", function () {
  43972. if (xhr.status === 200) {
  43973. // Blob as response (XHR2)
  43974. blob = xhr.response;
  43975. var transaction = _this.db.transaction(["textures"], "readwrite");
  43976. // the transaction could abort because of a QuotaExceededError error
  43977. transaction.onabort = function (event) {
  43978. try {
  43979. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  43980. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  43981. _this.hasReachedQuota = true;
  43982. }
  43983. }
  43984. catch (ex) { }
  43985. generateBlobUrl();
  43986. };
  43987. transaction.oncomplete = function (event) {
  43988. generateBlobUrl();
  43989. };
  43990. var newTexture = { textureUrl: url, data: blob };
  43991. try {
  43992. // Put the blob into the dabase
  43993. var addRequest = transaction.objectStore("textures").put(newTexture);
  43994. addRequest.onsuccess = function (event) {
  43995. };
  43996. addRequest.onerror = function (event) {
  43997. generateBlobUrl();
  43998. };
  43999. }
  44000. catch (ex) {
  44001. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  44002. if (ex.code === 25) {
  44003. Database.IsUASupportingBlobStorage = false;
  44004. }
  44005. image.src = url;
  44006. }
  44007. }
  44008. else {
  44009. image.src = url;
  44010. }
  44011. }, false);
  44012. xhr.addEventListener("error", function (event) {
  44013. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  44014. image.src = url;
  44015. }, false);
  44016. xhr.send();
  44017. }
  44018. else {
  44019. image.src = url;
  44020. }
  44021. }
  44022. else {
  44023. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  44024. image.src = url;
  44025. }
  44026. };
  44027. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  44028. var _this = this;
  44029. var updateVersion = function (event) {
  44030. // the version is not yet in the DB or we need to update it
  44031. _this._saveVersionIntoDBAsync(url, versionLoaded);
  44032. };
  44033. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  44034. };
  44035. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  44036. var _this = this;
  44037. if (this.isSupported) {
  44038. var version;
  44039. try {
  44040. var transaction = this.db.transaction(["versions"]);
  44041. transaction.oncomplete = function (event) {
  44042. if (version) {
  44043. // If the version in the JSON file is > than the version in DB
  44044. if (_this.manifestVersionFound > version.data) {
  44045. _this.mustUpdateRessources = true;
  44046. updateInDBCallback();
  44047. }
  44048. else {
  44049. callback(version.data);
  44050. }
  44051. }
  44052. else {
  44053. _this.mustUpdateRessources = true;
  44054. updateInDBCallback();
  44055. }
  44056. };
  44057. transaction.onabort = function (event) {
  44058. callback(-1);
  44059. };
  44060. var getRequest = transaction.objectStore("versions").get(url);
  44061. getRequest.onsuccess = function (event) {
  44062. version = (event.target).result;
  44063. };
  44064. getRequest.onerror = function (event) {
  44065. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  44066. callback(-1);
  44067. };
  44068. }
  44069. catch (ex) {
  44070. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  44071. callback(-1);
  44072. }
  44073. }
  44074. else {
  44075. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  44076. callback(-1);
  44077. }
  44078. };
  44079. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  44080. var _this = this;
  44081. if (this.isSupported && !this.hasReachedQuota) {
  44082. try {
  44083. // Open a transaction to the database
  44084. var transaction = this.db.transaction(["versions"], "readwrite");
  44085. // the transaction could abort because of a QuotaExceededError error
  44086. transaction.onabort = function (event) {
  44087. try {
  44088. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  44089. _this.hasReachedQuota = true;
  44090. }
  44091. }
  44092. catch (ex) { }
  44093. callback(-1);
  44094. };
  44095. transaction.oncomplete = function (event) {
  44096. callback(_this.manifestVersionFound);
  44097. };
  44098. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  44099. // Put the scene into the database
  44100. var addRequest = transaction.objectStore("versions").put(newVersion);
  44101. addRequest.onsuccess = function (event) {
  44102. };
  44103. addRequest.onerror = function (event) {
  44104. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  44105. };
  44106. }
  44107. catch (ex) {
  44108. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  44109. callback(-1);
  44110. }
  44111. }
  44112. else {
  44113. callback(-1);
  44114. }
  44115. };
  44116. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  44117. var _this = this;
  44118. var completeUrl = Database.ReturnFullUrlLocation(url);
  44119. var saveAndLoadFile = function (event) {
  44120. // the scene is not yet in the DB, let's try to save it
  44121. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  44122. };
  44123. this._checkVersionFromDB(completeUrl, function (version) {
  44124. if (version !== -1) {
  44125. if (!_this.mustUpdateRessources) {
  44126. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  44127. }
  44128. else {
  44129. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  44130. }
  44131. }
  44132. else {
  44133. errorCallback();
  44134. }
  44135. });
  44136. };
  44137. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  44138. if (this.isSupported) {
  44139. var targetStore;
  44140. if (url.indexOf(".babylon") !== -1) {
  44141. targetStore = "scenes";
  44142. }
  44143. else {
  44144. targetStore = "textures";
  44145. }
  44146. var file;
  44147. var transaction = this.db.transaction([targetStore]);
  44148. transaction.oncomplete = function (event) {
  44149. if (file) {
  44150. callback(file.data);
  44151. }
  44152. else {
  44153. notInDBCallback();
  44154. }
  44155. };
  44156. transaction.onabort = function (event) {
  44157. notInDBCallback();
  44158. };
  44159. var getRequest = transaction.objectStore(targetStore).get(url);
  44160. getRequest.onsuccess = function (event) {
  44161. file = (event.target).result;
  44162. };
  44163. getRequest.onerror = function (event) {
  44164. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  44165. notInDBCallback();
  44166. };
  44167. }
  44168. else {
  44169. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  44170. callback();
  44171. }
  44172. };
  44173. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  44174. var _this = this;
  44175. if (this.isSupported) {
  44176. var targetStore;
  44177. if (url.indexOf(".babylon") !== -1) {
  44178. targetStore = "scenes";
  44179. }
  44180. else {
  44181. targetStore = "textures";
  44182. }
  44183. // Create XHR
  44184. var xhr = new XMLHttpRequest(), fileData;
  44185. xhr.open("GET", url, true);
  44186. if (useArrayBuffer) {
  44187. xhr.responseType = "arraybuffer";
  44188. }
  44189. xhr.onprogress = progressCallback;
  44190. xhr.addEventListener("load", function () {
  44191. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  44192. // Blob as response (XHR2)
  44193. //fileData = xhr.responseText;
  44194. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  44195. if (!_this.hasReachedQuota) {
  44196. // Open a transaction to the database
  44197. var transaction = _this.db.transaction([targetStore], "readwrite");
  44198. // the transaction could abort because of a QuotaExceededError error
  44199. transaction.onabort = function (event) {
  44200. try {
  44201. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  44202. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  44203. _this.hasReachedQuota = true;
  44204. }
  44205. }
  44206. catch (ex) { }
  44207. callback(fileData);
  44208. };
  44209. transaction.oncomplete = function (event) {
  44210. callback(fileData);
  44211. };
  44212. var newFile;
  44213. if (targetStore === "scenes") {
  44214. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  44215. }
  44216. else {
  44217. newFile = { textureUrl: url, data: fileData };
  44218. }
  44219. try {
  44220. // Put the scene into the database
  44221. var addRequest = transaction.objectStore(targetStore).put(newFile);
  44222. addRequest.onsuccess = function (event) {
  44223. };
  44224. addRequest.onerror = function (event) {
  44225. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  44226. };
  44227. }
  44228. catch (ex) {
  44229. callback(fileData);
  44230. }
  44231. }
  44232. else {
  44233. callback(fileData);
  44234. }
  44235. }
  44236. else {
  44237. callback();
  44238. }
  44239. }, false);
  44240. xhr.addEventListener("error", function (event) {
  44241. BABYLON.Tools.Error("error on XHR request.");
  44242. callback();
  44243. }, false);
  44244. xhr.send();
  44245. }
  44246. else {
  44247. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  44248. callback();
  44249. }
  44250. };
  44251. return Database;
  44252. }());
  44253. Database.IsUASupportingBlobStorage = true;
  44254. Database.IDBStorageEnabled = true;
  44255. Database.parseURL = function (url) {
  44256. var a = document.createElement('a');
  44257. a.href = url;
  44258. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  44259. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  44260. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  44261. return absLocation;
  44262. };
  44263. Database.ReturnFullUrlLocation = function (url) {
  44264. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  44265. return (Database.parseURL(window.location.href) + url);
  44266. }
  44267. else {
  44268. return url;
  44269. }
  44270. };
  44271. BABYLON.Database = Database;
  44272. })(BABYLON || (BABYLON = {}));
  44273. //# sourceMappingURL=babylon.database.js.map
  44274. var BABYLON;
  44275. (function (BABYLON) {
  44276. var FresnelParameters = (function () {
  44277. function FresnelParameters() {
  44278. this._isEnabled = true;
  44279. this.leftColor = BABYLON.Color3.White();
  44280. this.rightColor = BABYLON.Color3.Black();
  44281. this.bias = 0;
  44282. this.power = 1;
  44283. }
  44284. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  44285. get: function () {
  44286. return this._isEnabled;
  44287. },
  44288. set: function (value) {
  44289. if (this._isEnabled === value) {
  44290. return;
  44291. }
  44292. this._isEnabled = value;
  44293. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  44294. },
  44295. enumerable: true,
  44296. configurable: true
  44297. });
  44298. FresnelParameters.prototype.clone = function () {
  44299. var newFresnelParameters = new FresnelParameters();
  44300. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  44301. return newFresnelParameters;
  44302. };
  44303. FresnelParameters.prototype.serialize = function () {
  44304. var serializationObject = {};
  44305. serializationObject.isEnabled = this.isEnabled;
  44306. serializationObject.leftColor = this.leftColor;
  44307. serializationObject.rightColor = this.rightColor;
  44308. serializationObject.bias = this.bias;
  44309. serializationObject.power = this.power;
  44310. return serializationObject;
  44311. };
  44312. FresnelParameters.Parse = function (parsedFresnelParameters) {
  44313. var fresnelParameters = new FresnelParameters();
  44314. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  44315. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  44316. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  44317. fresnelParameters.bias = parsedFresnelParameters.bias;
  44318. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  44319. return fresnelParameters;
  44320. };
  44321. return FresnelParameters;
  44322. }());
  44323. BABYLON.FresnelParameters = FresnelParameters;
  44324. })(BABYLON || (BABYLON = {}));
  44325. //# sourceMappingURL=babylon.fresnelParameters.js.map
  44326. var BABYLON;
  44327. (function (BABYLON) {
  44328. var MultiMaterial = (function (_super) {
  44329. __extends(MultiMaterial, _super);
  44330. function MultiMaterial(name, scene) {
  44331. var _this = _super.call(this, name, scene, true) || this;
  44332. _this.subMaterials = new Array();
  44333. scene.multiMaterials.push(_this);
  44334. return _this;
  44335. }
  44336. // Properties
  44337. MultiMaterial.prototype.getSubMaterial = function (index) {
  44338. if (index < 0 || index >= this.subMaterials.length) {
  44339. return this.getScene().defaultMaterial;
  44340. }
  44341. return this.subMaterials[index];
  44342. };
  44343. // Methods
  44344. MultiMaterial.prototype.getClassName = function () {
  44345. return "MultiMaterial";
  44346. };
  44347. MultiMaterial.prototype.isReady = function (mesh) {
  44348. for (var index = 0; index < this.subMaterials.length; index++) {
  44349. var subMaterial = this.subMaterials[index];
  44350. if (subMaterial) {
  44351. if (!this.subMaterials[index].isReady(mesh)) {
  44352. return false;
  44353. }
  44354. }
  44355. }
  44356. return true;
  44357. };
  44358. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  44359. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  44360. for (var index = 0; index < this.subMaterials.length; index++) {
  44361. var subMaterial = null;
  44362. if (cloneChildren) {
  44363. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  44364. }
  44365. else {
  44366. subMaterial = this.subMaterials[index];
  44367. }
  44368. newMultiMaterial.subMaterials.push(subMaterial);
  44369. }
  44370. return newMultiMaterial;
  44371. };
  44372. MultiMaterial.prototype.serialize = function () {
  44373. var serializationObject = {};
  44374. serializationObject.name = this.name;
  44375. serializationObject.id = this.id;
  44376. serializationObject.tags = BABYLON.Tags.GetTags(this);
  44377. serializationObject.materials = [];
  44378. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  44379. var subMat = this.subMaterials[matIndex];
  44380. if (subMat) {
  44381. serializationObject.materials.push(subMat.id);
  44382. }
  44383. else {
  44384. serializationObject.materials.push(null);
  44385. }
  44386. }
  44387. return serializationObject;
  44388. };
  44389. return MultiMaterial;
  44390. }(BABYLON.Material));
  44391. BABYLON.MultiMaterial = MultiMaterial;
  44392. })(BABYLON || (BABYLON = {}));
  44393. //# sourceMappingURL=babylon.multiMaterial.js.map
  44394. var BABYLON;
  44395. (function (BABYLON) {
  44396. var FreeCameraTouchInput = (function () {
  44397. function FreeCameraTouchInput() {
  44398. this._offsetX = null;
  44399. this._offsetY = null;
  44400. this._pointerCount = 0;
  44401. this._pointerPressed = [];
  44402. this.touchAngularSensibility = 200000.0;
  44403. this.touchMoveSensibility = 250.0;
  44404. }
  44405. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  44406. var _this = this;
  44407. var previousPosition;
  44408. if (this._pointerInput === undefined) {
  44409. this._onLostFocus = function (evt) {
  44410. _this._offsetX = null;
  44411. _this._offsetY = null;
  44412. };
  44413. this._pointerInput = function (p, s) {
  44414. var evt = p.event;
  44415. if (evt.pointerType === "mouse") {
  44416. return;
  44417. }
  44418. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  44419. if (!noPreventDefault) {
  44420. evt.preventDefault();
  44421. }
  44422. _this._pointerPressed.push(evt.pointerId);
  44423. if (_this._pointerPressed.length !== 1) {
  44424. return;
  44425. }
  44426. previousPosition = {
  44427. x: evt.clientX,
  44428. y: evt.clientY
  44429. };
  44430. }
  44431. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  44432. if (!noPreventDefault) {
  44433. evt.preventDefault();
  44434. }
  44435. var index = _this._pointerPressed.indexOf(evt.pointerId);
  44436. if (index === -1) {
  44437. return;
  44438. }
  44439. _this._pointerPressed.splice(index, 1);
  44440. if (index != 0) {
  44441. return;
  44442. }
  44443. previousPosition = null;
  44444. _this._offsetX = null;
  44445. _this._offsetY = null;
  44446. }
  44447. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  44448. if (!noPreventDefault) {
  44449. evt.preventDefault();
  44450. }
  44451. if (!previousPosition) {
  44452. return;
  44453. }
  44454. var index = _this._pointerPressed.indexOf(evt.pointerId);
  44455. if (index != 0) {
  44456. return;
  44457. }
  44458. _this._offsetX = evt.clientX - previousPosition.x;
  44459. _this._offsetY = -(evt.clientY - previousPosition.y);
  44460. }
  44461. };
  44462. }
  44463. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  44464. element.addEventListener("blur", this._onLostFocus);
  44465. };
  44466. FreeCameraTouchInput.prototype.detachControl = function (element) {
  44467. if (this._pointerInput && element) {
  44468. this.camera.getScene().onPointerObservable.remove(this._observer);
  44469. this._observer = null;
  44470. element.removeEventListener("blur", this._onLostFocus);
  44471. this._onLostFocus = null;
  44472. this._pointerPressed = [];
  44473. this._offsetX = null;
  44474. this._offsetY = null;
  44475. this._pointerCount = 0;
  44476. }
  44477. };
  44478. FreeCameraTouchInput.prototype.checkInputs = function () {
  44479. if (this._offsetX) {
  44480. var camera = this.camera;
  44481. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  44482. if (this._pointerPressed.length > 1) {
  44483. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  44484. }
  44485. else {
  44486. var speed = camera._computeLocalCameraSpeed();
  44487. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  44488. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  44489. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  44490. }
  44491. }
  44492. };
  44493. FreeCameraTouchInput.prototype.getTypeName = function () {
  44494. return "FreeCameraTouchInput";
  44495. };
  44496. FreeCameraTouchInput.prototype.getSimpleName = function () {
  44497. return "touch";
  44498. };
  44499. return FreeCameraTouchInput;
  44500. }());
  44501. __decorate([
  44502. BABYLON.serialize()
  44503. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  44504. __decorate([
  44505. BABYLON.serialize()
  44506. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  44507. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  44508. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  44509. })(BABYLON || (BABYLON = {}));
  44510. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  44511. /// <reference path="babylon.freeCamera.ts" />
  44512. var BABYLON;
  44513. (function (BABYLON) {
  44514. // We're mainly based on the logic defined into the FreeCamera code
  44515. var TouchCamera = (function (_super) {
  44516. __extends(TouchCamera, _super);
  44517. //-- end properties for backward compatibility for inputs
  44518. function TouchCamera(name, position, scene) {
  44519. var _this = _super.call(this, name, position, scene) || this;
  44520. _this.inputs.addTouch();
  44521. _this._setupInputs();
  44522. return _this;
  44523. }
  44524. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  44525. //-- Begin properties for backward compatibility for inputs
  44526. get: function () {
  44527. var touch = this.inputs.attached["touch"];
  44528. if (touch)
  44529. return touch.touchAngularSensibility;
  44530. },
  44531. set: function (value) {
  44532. var touch = this.inputs.attached["touch"];
  44533. if (touch)
  44534. touch.touchAngularSensibility = value;
  44535. },
  44536. enumerable: true,
  44537. configurable: true
  44538. });
  44539. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  44540. get: function () {
  44541. var touch = this.inputs.attached["touch"];
  44542. if (touch)
  44543. return touch.touchMoveSensibility;
  44544. },
  44545. set: function (value) {
  44546. var touch = this.inputs.attached["touch"];
  44547. if (touch)
  44548. touch.touchMoveSensibility = value;
  44549. },
  44550. enumerable: true,
  44551. configurable: true
  44552. });
  44553. TouchCamera.prototype.getClassName = function () {
  44554. return "TouchCamera";
  44555. };
  44556. TouchCamera.prototype._setupInputs = function () {
  44557. var mouse = this.inputs.attached["mouse"];
  44558. if (mouse) {
  44559. mouse.touchEnabled = false;
  44560. }
  44561. };
  44562. return TouchCamera;
  44563. }(BABYLON.FreeCamera));
  44564. BABYLON.TouchCamera = TouchCamera;
  44565. })(BABYLON || (BABYLON = {}));
  44566. //# sourceMappingURL=babylon.touchCamera.js.map
  44567. var BABYLON;
  44568. (function (BABYLON) {
  44569. var ProceduralTexture = (function (_super) {
  44570. __extends(ProceduralTexture, _super);
  44571. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  44572. if (generateMipMaps === void 0) { generateMipMaps = true; }
  44573. if (isCube === void 0) { isCube = false; }
  44574. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  44575. _this.isCube = isCube;
  44576. _this.isEnabled = true;
  44577. _this._currentRefreshId = -1;
  44578. _this._refreshRate = 1;
  44579. _this._vertexBuffers = {};
  44580. _this._uniforms = new Array();
  44581. _this._samplers = new Array();
  44582. _this._textures = new Array();
  44583. _this._floats = new Array();
  44584. _this._floatsArrays = {};
  44585. _this._colors3 = new Array();
  44586. _this._colors4 = new Array();
  44587. _this._vectors2 = new Array();
  44588. _this._vectors3 = new Array();
  44589. _this._matrices = new Array();
  44590. _this._fallbackTextureUsed = false;
  44591. scene._proceduralTextures.push(_this);
  44592. _this.name = name;
  44593. _this.isRenderTarget = true;
  44594. _this._size = size;
  44595. _this._generateMipMaps = generateMipMaps;
  44596. _this.setFragment(fragment);
  44597. _this._fallbackTexture = fallbackTexture;
  44598. var engine = scene.getEngine();
  44599. if (isCube) {
  44600. _this._texture = engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  44601. _this.setFloat("face", 0);
  44602. }
  44603. else {
  44604. _this._texture = engine.createRenderTargetTexture(size, generateMipMaps);
  44605. }
  44606. // VBO
  44607. var vertices = [];
  44608. vertices.push(1, 1);
  44609. vertices.push(-1, 1);
  44610. vertices.push(-1, -1);
  44611. vertices.push(1, -1);
  44612. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  44613. // Indices
  44614. var indices = [];
  44615. indices.push(0);
  44616. indices.push(1);
  44617. indices.push(2);
  44618. indices.push(0);
  44619. indices.push(2);
  44620. indices.push(3);
  44621. _this._indexBuffer = engine.createIndexBuffer(indices);
  44622. return _this;
  44623. }
  44624. ProceduralTexture.prototype.reset = function () {
  44625. if (this._effect === undefined) {
  44626. return;
  44627. }
  44628. var engine = this.getScene().getEngine();
  44629. engine._releaseEffect(this._effect);
  44630. };
  44631. ProceduralTexture.prototype.isReady = function () {
  44632. var _this = this;
  44633. var engine = this.getScene().getEngine();
  44634. var shaders;
  44635. if (!this._fragment) {
  44636. return false;
  44637. }
  44638. if (this._fallbackTextureUsed) {
  44639. return true;
  44640. }
  44641. if (this._fragment.fragmentElement !== undefined) {
  44642. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  44643. }
  44644. else {
  44645. shaders = { vertex: "procedural", fragment: this._fragment };
  44646. }
  44647. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", null, null, function () {
  44648. _this.releaseInternalTexture();
  44649. if (_this._fallbackTexture) {
  44650. _this._texture = _this._fallbackTexture._texture;
  44651. _this._texture.references++;
  44652. }
  44653. _this._fallbackTextureUsed = true;
  44654. });
  44655. return this._effect.isReady();
  44656. };
  44657. ProceduralTexture.prototype.resetRefreshCounter = function () {
  44658. this._currentRefreshId = -1;
  44659. };
  44660. ProceduralTexture.prototype.setFragment = function (fragment) {
  44661. this._fragment = fragment;
  44662. };
  44663. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  44664. get: function () {
  44665. return this._refreshRate;
  44666. },
  44667. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  44668. set: function (value) {
  44669. this._refreshRate = value;
  44670. this.resetRefreshCounter();
  44671. },
  44672. enumerable: true,
  44673. configurable: true
  44674. });
  44675. ProceduralTexture.prototype._shouldRender = function () {
  44676. if (!this.isEnabled || !this.isReady() || !this._texture) {
  44677. return false;
  44678. }
  44679. if (this._fallbackTextureUsed) {
  44680. return false;
  44681. }
  44682. if (this._currentRefreshId === -1) {
  44683. this._currentRefreshId = 1;
  44684. return true;
  44685. }
  44686. if (this.refreshRate === this._currentRefreshId) {
  44687. this._currentRefreshId = 1;
  44688. return true;
  44689. }
  44690. this._currentRefreshId++;
  44691. return false;
  44692. };
  44693. ProceduralTexture.prototype.getRenderSize = function () {
  44694. return this._size;
  44695. };
  44696. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  44697. if (this._fallbackTextureUsed) {
  44698. return;
  44699. }
  44700. this.releaseInternalTexture();
  44701. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  44702. };
  44703. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  44704. if (this._uniforms.indexOf(uniformName) === -1) {
  44705. this._uniforms.push(uniformName);
  44706. }
  44707. };
  44708. ProceduralTexture.prototype.setTexture = function (name, texture) {
  44709. if (this._samplers.indexOf(name) === -1) {
  44710. this._samplers.push(name);
  44711. }
  44712. this._textures[name] = texture;
  44713. return this;
  44714. };
  44715. ProceduralTexture.prototype.setFloat = function (name, value) {
  44716. this._checkUniform(name);
  44717. this._floats[name] = value;
  44718. return this;
  44719. };
  44720. ProceduralTexture.prototype.setFloats = function (name, value) {
  44721. this._checkUniform(name);
  44722. this._floatsArrays[name] = value;
  44723. return this;
  44724. };
  44725. ProceduralTexture.prototype.setColor3 = function (name, value) {
  44726. this._checkUniform(name);
  44727. this._colors3[name] = value;
  44728. return this;
  44729. };
  44730. ProceduralTexture.prototype.setColor4 = function (name, value) {
  44731. this._checkUniform(name);
  44732. this._colors4[name] = value;
  44733. return this;
  44734. };
  44735. ProceduralTexture.prototype.setVector2 = function (name, value) {
  44736. this._checkUniform(name);
  44737. this._vectors2[name] = value;
  44738. return this;
  44739. };
  44740. ProceduralTexture.prototype.setVector3 = function (name, value) {
  44741. this._checkUniform(name);
  44742. this._vectors3[name] = value;
  44743. return this;
  44744. };
  44745. ProceduralTexture.prototype.setMatrix = function (name, value) {
  44746. this._checkUniform(name);
  44747. this._matrices[name] = value;
  44748. return this;
  44749. };
  44750. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  44751. var scene = this.getScene();
  44752. var engine = scene.getEngine();
  44753. // Render
  44754. engine.enableEffect(this._effect);
  44755. engine.setState(false);
  44756. // Texture
  44757. for (var name in this._textures) {
  44758. this._effect.setTexture(name, this._textures[name]);
  44759. }
  44760. // Float
  44761. for (name in this._floats) {
  44762. this._effect.setFloat(name, this._floats[name]);
  44763. }
  44764. // Floats
  44765. for (name in this._floatsArrays) {
  44766. this._effect.setArray(name, this._floatsArrays[name]);
  44767. }
  44768. // Color3
  44769. for (name in this._colors3) {
  44770. this._effect.setColor3(name, this._colors3[name]);
  44771. }
  44772. // Color4
  44773. for (name in this._colors4) {
  44774. var color = this._colors4[name];
  44775. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  44776. }
  44777. // Vector2
  44778. for (name in this._vectors2) {
  44779. this._effect.setVector2(name, this._vectors2[name]);
  44780. }
  44781. // Vector3
  44782. for (name in this._vectors3) {
  44783. this._effect.setVector3(name, this._vectors3[name]);
  44784. }
  44785. // Matrix
  44786. for (name in this._matrices) {
  44787. this._effect.setMatrix(name, this._matrices[name]);
  44788. }
  44789. if (this.isCube) {
  44790. for (var face = 0; face < 6; face++) {
  44791. engine.bindFramebuffer(this._texture, face);
  44792. // VBOs
  44793. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  44794. this._effect.setFloat("face", face);
  44795. // Clear
  44796. engine.clear(scene.clearColor, true, true, true);
  44797. // Draw order
  44798. engine.draw(true, 0, 6);
  44799. // Mipmaps
  44800. if (face === 5) {
  44801. engine.generateMipMapsForCubemap(this._texture);
  44802. }
  44803. }
  44804. }
  44805. else {
  44806. engine.bindFramebuffer(this._texture);
  44807. // VBOs
  44808. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  44809. // Clear
  44810. engine.clear(scene.clearColor, true, true, true);
  44811. // Draw order
  44812. engine.draw(true, 0, 6);
  44813. }
  44814. // Unbind
  44815. engine.unBindFramebuffer(this._texture, this.isCube);
  44816. if (this.onGenerated) {
  44817. this.onGenerated();
  44818. }
  44819. };
  44820. ProceduralTexture.prototype.clone = function () {
  44821. var textureSize = this.getSize();
  44822. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  44823. // Base texture
  44824. newTexture.hasAlpha = this.hasAlpha;
  44825. newTexture.level = this.level;
  44826. // RenderTarget Texture
  44827. newTexture.coordinatesMode = this.coordinatesMode;
  44828. return newTexture;
  44829. };
  44830. ProceduralTexture.prototype.dispose = function () {
  44831. var index = this.getScene()._proceduralTextures.indexOf(this);
  44832. if (index >= 0) {
  44833. this.getScene()._proceduralTextures.splice(index, 1);
  44834. }
  44835. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  44836. if (vertexBuffer) {
  44837. vertexBuffer.dispose();
  44838. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  44839. }
  44840. if (this._indexBuffer && this.getScene().getEngine()._releaseBuffer(this._indexBuffer)) {
  44841. this._indexBuffer = null;
  44842. }
  44843. _super.prototype.dispose.call(this);
  44844. };
  44845. return ProceduralTexture;
  44846. }(BABYLON.Texture));
  44847. BABYLON.ProceduralTexture = ProceduralTexture;
  44848. })(BABYLON || (BABYLON = {}));
  44849. //# sourceMappingURL=babylon.proceduralTexture.js.map
  44850. /// <reference path="babylon.proceduralTexture.ts" />
  44851. var BABYLON;
  44852. (function (BABYLON) {
  44853. var CustomProceduralTexture = (function (_super) {
  44854. __extends(CustomProceduralTexture, _super);
  44855. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  44856. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  44857. _this._animate = true;
  44858. _this._time = 0;
  44859. _this._texturePath = texturePath;
  44860. //Try to load json
  44861. _this.loadJson(texturePath);
  44862. _this.refreshRate = 1;
  44863. return _this;
  44864. }
  44865. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  44866. var _this = this;
  44867. var that = this;
  44868. function noConfigFile() {
  44869. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  44870. try {
  44871. that.setFragment(that._texturePath);
  44872. }
  44873. catch (ex) {
  44874. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  44875. }
  44876. }
  44877. var configFileUrl = jsonUrl + "/config.json";
  44878. var xhr = new XMLHttpRequest();
  44879. xhr.open("GET", configFileUrl, true);
  44880. xhr.addEventListener("load", function () {
  44881. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  44882. try {
  44883. _this._config = JSON.parse(xhr.response);
  44884. _this.updateShaderUniforms();
  44885. _this.updateTextures();
  44886. _this.setFragment(_this._texturePath + "/custom");
  44887. _this._animate = _this._config.animate;
  44888. _this.refreshRate = _this._config.refreshrate;
  44889. }
  44890. catch (ex) {
  44891. noConfigFile();
  44892. }
  44893. }
  44894. else {
  44895. noConfigFile();
  44896. }
  44897. }, false);
  44898. xhr.addEventListener("error", function () {
  44899. noConfigFile();
  44900. }, false);
  44901. try {
  44902. xhr.send();
  44903. }
  44904. catch (ex) {
  44905. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  44906. }
  44907. };
  44908. CustomProceduralTexture.prototype.isReady = function () {
  44909. if (!_super.prototype.isReady.call(this)) {
  44910. return false;
  44911. }
  44912. for (var name in this._textures) {
  44913. var texture = this._textures[name];
  44914. if (!texture.isReady()) {
  44915. return false;
  44916. }
  44917. }
  44918. return true;
  44919. };
  44920. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  44921. if (this._animate) {
  44922. this._time += this.getScene().getAnimationRatio() * 0.03;
  44923. this.updateShaderUniforms();
  44924. }
  44925. _super.prototype.render.call(this, useCameraPostProcess);
  44926. };
  44927. CustomProceduralTexture.prototype.updateTextures = function () {
  44928. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  44929. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  44930. }
  44931. };
  44932. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  44933. if (this._config) {
  44934. for (var j = 0; j < this._config.uniforms.length; j++) {
  44935. var uniform = this._config.uniforms[j];
  44936. switch (uniform.type) {
  44937. case "float":
  44938. this.setFloat(uniform.name, uniform.value);
  44939. break;
  44940. case "color3":
  44941. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  44942. break;
  44943. case "color4":
  44944. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  44945. break;
  44946. case "vector2":
  44947. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  44948. break;
  44949. case "vector3":
  44950. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  44951. break;
  44952. }
  44953. }
  44954. }
  44955. this.setFloat("time", this._time);
  44956. };
  44957. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  44958. get: function () {
  44959. return this._animate;
  44960. },
  44961. set: function (value) {
  44962. this._animate = value;
  44963. },
  44964. enumerable: true,
  44965. configurable: true
  44966. });
  44967. return CustomProceduralTexture;
  44968. }(BABYLON.ProceduralTexture));
  44969. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  44970. })(BABYLON || (BABYLON = {}));
  44971. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  44972. var BABYLON;
  44973. (function (BABYLON) {
  44974. var FreeCameraGamepadInput = (function () {
  44975. function FreeCameraGamepadInput() {
  44976. this.gamepadAngularSensibility = 200;
  44977. this.gamepadMoveSensibility = 40;
  44978. // private members
  44979. this._cameraTransform = BABYLON.Matrix.Identity();
  44980. this._deltaTransform = BABYLON.Vector3.Zero();
  44981. this._vector3 = BABYLON.Vector3.Zero();
  44982. this._vector2 = BABYLON.Vector2.Zero();
  44983. }
  44984. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  44985. var _this = this;
  44986. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  44987. };
  44988. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  44989. if (this._gamepads) {
  44990. this._gamepads.dispose();
  44991. }
  44992. this.gamepad = null;
  44993. };
  44994. FreeCameraGamepadInput.prototype.checkInputs = function () {
  44995. if (this.gamepad && this.gamepad.leftStick) {
  44996. var camera = this.camera;
  44997. var LSValues = this.gamepad.leftStick;
  44998. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  44999. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  45000. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  45001. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  45002. var RSValues = this.gamepad.rightStick;
  45003. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  45004. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  45005. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  45006. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  45007. if (!camera.rotationQuaternion) {
  45008. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  45009. }
  45010. else {
  45011. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  45012. }
  45013. var speed = camera._computeLocalCameraSpeed() * 50.0;
  45014. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  45015. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  45016. camera.cameraDirection.addInPlace(this._deltaTransform);
  45017. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  45018. camera.cameraRotation.addInPlace(this._vector2);
  45019. }
  45020. };
  45021. FreeCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  45022. // Only the first gamepad found can control the camera
  45023. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  45024. // prioritize XBOX gamepads.
  45025. if (!this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  45026. this.gamepad = gamepad;
  45027. }
  45028. }
  45029. };
  45030. FreeCameraGamepadInput.prototype.getTypeName = function () {
  45031. return "FreeCameraGamepadInput";
  45032. };
  45033. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  45034. return "gamepad";
  45035. };
  45036. return FreeCameraGamepadInput;
  45037. }());
  45038. __decorate([
  45039. BABYLON.serialize()
  45040. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  45041. __decorate([
  45042. BABYLON.serialize()
  45043. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  45044. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  45045. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  45046. })(BABYLON || (BABYLON = {}));
  45047. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  45048. var BABYLON;
  45049. (function (BABYLON) {
  45050. var ArcRotateCameraGamepadInput = (function () {
  45051. function ArcRotateCameraGamepadInput() {
  45052. this.gamepadRotationSensibility = 80;
  45053. this.gamepadMoveSensibility = 40;
  45054. }
  45055. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  45056. var _this = this;
  45057. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  45058. };
  45059. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  45060. if (this._gamepads) {
  45061. this._gamepads.dispose();
  45062. }
  45063. this.gamepad = null;
  45064. };
  45065. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  45066. if (this.gamepad) {
  45067. var camera = this.camera;
  45068. var RSValues = this.gamepad.rightStick;
  45069. if (RSValues.x != 0) {
  45070. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  45071. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  45072. camera.inertialAlphaOffset += normalizedRX;
  45073. }
  45074. }
  45075. if (RSValues.y != 0) {
  45076. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  45077. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  45078. camera.inertialBetaOffset += normalizedRY;
  45079. }
  45080. }
  45081. var LSValues = this.gamepad.leftStick;
  45082. if (LSValues.y != 0) {
  45083. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  45084. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  45085. this.camera.inertialRadiusOffset -= normalizedLY;
  45086. }
  45087. }
  45088. }
  45089. };
  45090. ArcRotateCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  45091. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  45092. // prioritize XBOX gamepads.
  45093. if (!this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  45094. this.gamepad = gamepad;
  45095. }
  45096. }
  45097. };
  45098. ArcRotateCameraGamepadInput.prototype.getTypeName = function () {
  45099. return "ArcRotateCameraGamepadInput";
  45100. };
  45101. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  45102. return "gamepad";
  45103. };
  45104. return ArcRotateCameraGamepadInput;
  45105. }());
  45106. __decorate([
  45107. BABYLON.serialize()
  45108. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  45109. __decorate([
  45110. BABYLON.serialize()
  45111. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  45112. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  45113. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  45114. })(BABYLON || (BABYLON = {}));
  45115. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  45116. var BABYLON;
  45117. (function (BABYLON) {
  45118. var Gamepads = (function () {
  45119. function Gamepads(ongamedpadconnected) {
  45120. var _this = this;
  45121. this.babylonGamepads = [];
  45122. this.oneGamepadConnected = false;
  45123. this.isMonitoring = false;
  45124. this.gamepadEventSupported = 'GamepadEvent' in window;
  45125. this.gamepadSupport = (navigator.getGamepads ||
  45126. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  45127. this._callbackGamepadConnected = ongamedpadconnected;
  45128. if (this.gamepadSupport) {
  45129. //first add already-connected gamepads
  45130. this._updateGamepadObjects();
  45131. if (this.babylonGamepads.length) {
  45132. this._startMonitoringGamepads();
  45133. }
  45134. // Checking if the gamepad connected event is supported (like in Firefox)
  45135. if (this.gamepadEventSupported) {
  45136. this._onGamepadConnectedEvent = function (evt) {
  45137. _this._onGamepadConnected(evt.gamepad);
  45138. };
  45139. this._onGamepadDisonnectedEvent = function (evt) {
  45140. _this._onGamepadDisconnected(evt);
  45141. };
  45142. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  45143. window.addEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  45144. }
  45145. else {
  45146. this._startMonitoringGamepads();
  45147. }
  45148. }
  45149. }
  45150. Gamepads.prototype.dispose = function () {
  45151. if (Gamepads.gamepadDOMInfo) {
  45152. document.body.removeChild(Gamepads.gamepadDOMInfo);
  45153. }
  45154. if (this._onGamepadConnectedEvent) {
  45155. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  45156. window.removeEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  45157. this._onGamepadConnectedEvent = null;
  45158. this._onGamepadDisonnectedEvent = null;
  45159. }
  45160. };
  45161. Gamepads.prototype._onGamepadConnected = function (gamepad) {
  45162. var newGamepad = this._addNewGamepad(gamepad);
  45163. if (this._callbackGamepadConnected)
  45164. this._callbackGamepadConnected(newGamepad);
  45165. this._startMonitoringGamepads();
  45166. };
  45167. Gamepads.prototype._addNewGamepad = function (gamepad) {
  45168. if (!this.oneGamepadConnected) {
  45169. this.oneGamepadConnected = true;
  45170. if (Gamepads.gamepadDOMInfo) {
  45171. document.body.removeChild(Gamepads.gamepadDOMInfo);
  45172. Gamepads.gamepadDOMInfo = null;
  45173. }
  45174. }
  45175. var newGamepad;
  45176. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  45177. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  45178. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  45179. }
  45180. else if (gamepad.pose) {
  45181. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  45182. }
  45183. else {
  45184. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  45185. }
  45186. this.babylonGamepads.push(newGamepad);
  45187. return newGamepad;
  45188. };
  45189. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  45190. // Remove the gamepad from the list of gamepads to monitor.
  45191. for (var i in this.babylonGamepads) {
  45192. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  45193. this.babylonGamepads.splice(+i, 1);
  45194. break;
  45195. }
  45196. }
  45197. // If no gamepads are left, stop the polling loop.
  45198. if (this.babylonGamepads.length == 0) {
  45199. this._stopMonitoringGamepads();
  45200. }
  45201. };
  45202. Gamepads.prototype._startMonitoringGamepads = function () {
  45203. if (!this.isMonitoring) {
  45204. this.isMonitoring = true;
  45205. this._checkGamepadsStatus();
  45206. }
  45207. };
  45208. Gamepads.prototype._stopMonitoringGamepads = function () {
  45209. this.isMonitoring = false;
  45210. };
  45211. Gamepads.prototype._checkGamepadsStatus = function () {
  45212. var _this = this;
  45213. // updating gamepad objects
  45214. this._updateGamepadObjects();
  45215. for (var i in this.babylonGamepads) {
  45216. this.babylonGamepads[i].update();
  45217. }
  45218. if (this.isMonitoring) {
  45219. if (window.requestAnimationFrame) {
  45220. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  45221. }
  45222. else if (window.mozRequestAnimationFrame) {
  45223. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  45224. }
  45225. else if (window.webkitRequestAnimationFrame) {
  45226. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  45227. }
  45228. }
  45229. };
  45230. // This function is called only on Chrome, which does not yet support
  45231. // connection/disconnection events, but requires you to monitor
  45232. // an array for changes.
  45233. Gamepads.prototype._updateGamepadObjects = function () {
  45234. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  45235. for (var i = 0; i < gamepads.length; i++) {
  45236. if (gamepads[i]) {
  45237. if (!(gamepads[i].index in this.babylonGamepads)) {
  45238. var newGamepad = this._addNewGamepad(gamepads[i]);
  45239. if (this._callbackGamepadConnected) {
  45240. this._callbackGamepadConnected(newGamepad);
  45241. }
  45242. }
  45243. else {
  45244. this.babylonGamepads[i].browserGamepad = gamepads[i];
  45245. }
  45246. }
  45247. }
  45248. };
  45249. return Gamepads;
  45250. }());
  45251. BABYLON.Gamepads = Gamepads;
  45252. var StickValues = (function () {
  45253. function StickValues(x, y) {
  45254. this.x = x;
  45255. this.y = y;
  45256. }
  45257. return StickValues;
  45258. }());
  45259. BABYLON.StickValues = StickValues;
  45260. var Gamepad = (function () {
  45261. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  45262. if (leftStickX === void 0) { leftStickX = 0; }
  45263. if (leftStickY === void 0) { leftStickY = 1; }
  45264. if (rightStickX === void 0) { rightStickX = 2; }
  45265. if (rightStickY === void 0) { rightStickY = 3; }
  45266. this.id = id;
  45267. this.index = index;
  45268. this.browserGamepad = browserGamepad;
  45269. this.type = Gamepad.GAMEPAD;
  45270. this._leftStickAxisX = leftStickX;
  45271. this._leftStickAxisY = leftStickY;
  45272. this._rightStickAxisX = rightStickX;
  45273. this._rightStickAxisY = rightStickY;
  45274. if (this.browserGamepad.axes.length >= 2) {
  45275. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  45276. }
  45277. if (this.browserGamepad.axes.length >= 4) {
  45278. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  45279. }
  45280. }
  45281. Gamepad.prototype.onleftstickchanged = function (callback) {
  45282. this._onleftstickchanged = callback;
  45283. };
  45284. Gamepad.prototype.onrightstickchanged = function (callback) {
  45285. this._onrightstickchanged = callback;
  45286. };
  45287. Object.defineProperty(Gamepad.prototype, "leftStick", {
  45288. get: function () {
  45289. return this._leftStick;
  45290. },
  45291. set: function (newValues) {
  45292. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  45293. this._onleftstickchanged(newValues);
  45294. }
  45295. this._leftStick = newValues;
  45296. },
  45297. enumerable: true,
  45298. configurable: true
  45299. });
  45300. Object.defineProperty(Gamepad.prototype, "rightStick", {
  45301. get: function () {
  45302. return this._rightStick;
  45303. },
  45304. set: function (newValues) {
  45305. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  45306. this._onrightstickchanged(newValues);
  45307. }
  45308. this._rightStick = newValues;
  45309. },
  45310. enumerable: true,
  45311. configurable: true
  45312. });
  45313. Gamepad.prototype.update = function () {
  45314. if (this._leftStick) {
  45315. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  45316. }
  45317. if (this._rightStick) {
  45318. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  45319. }
  45320. };
  45321. return Gamepad;
  45322. }());
  45323. Gamepad.GAMEPAD = 0;
  45324. Gamepad.GENERIC = 1;
  45325. Gamepad.XBOX = 2;
  45326. Gamepad.POSE_ENABLED = 3;
  45327. BABYLON.Gamepad = Gamepad;
  45328. var GenericPad = (function (_super) {
  45329. __extends(GenericPad, _super);
  45330. function GenericPad(id, index, gamepad) {
  45331. var _this = _super.call(this, id, index, gamepad) || this;
  45332. _this.id = id;
  45333. _this.index = index;
  45334. _this.gamepad = gamepad;
  45335. _this.type = Gamepad.GENERIC;
  45336. _this._buttons = new Array(gamepad.buttons.length);
  45337. return _this;
  45338. }
  45339. GenericPad.prototype.onbuttondown = function (callback) {
  45340. this._onbuttondown = callback;
  45341. };
  45342. GenericPad.prototype.onbuttonup = function (callback) {
  45343. this._onbuttonup = callback;
  45344. };
  45345. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  45346. if (newValue !== currentValue) {
  45347. if (this._onbuttondown && newValue === 1) {
  45348. this._onbuttondown(buttonIndex);
  45349. }
  45350. if (this._onbuttonup && newValue === 0) {
  45351. this._onbuttonup(buttonIndex);
  45352. }
  45353. }
  45354. return newValue;
  45355. };
  45356. GenericPad.prototype.update = function () {
  45357. _super.prototype.update.call(this);
  45358. for (var index = 0; index < this._buttons.length; index++) {
  45359. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  45360. }
  45361. };
  45362. return GenericPad;
  45363. }(Gamepad));
  45364. BABYLON.GenericPad = GenericPad;
  45365. var Xbox360Button;
  45366. (function (Xbox360Button) {
  45367. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  45368. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  45369. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  45370. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  45371. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  45372. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  45373. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  45374. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  45375. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  45376. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  45377. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  45378. var Xbox360Dpad;
  45379. (function (Xbox360Dpad) {
  45380. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  45381. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  45382. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  45383. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  45384. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  45385. var Xbox360Pad = (function (_super) {
  45386. __extends(Xbox360Pad, _super);
  45387. function Xbox360Pad(id, index, gamepad, xboxOne) {
  45388. if (xboxOne === void 0) { xboxOne = false; }
  45389. var _this = _super.call(this, id, index, gamepad, 0, 1, (xboxOne ? 3 : 2), (xboxOne ? 4 : 3)) || this;
  45390. _this._leftTrigger = 0;
  45391. _this._rightTrigger = 0;
  45392. _this._buttonA = 0;
  45393. _this._buttonB = 0;
  45394. _this._buttonX = 0;
  45395. _this._buttonY = 0;
  45396. _this._buttonBack = 0;
  45397. _this._buttonStart = 0;
  45398. _this._buttonLB = 0;
  45399. _this._buttonRB = 0;
  45400. _this._buttonLeftStick = 0;
  45401. _this._buttonRightStick = 0;
  45402. _this._dPadUp = 0;
  45403. _this._dPadDown = 0;
  45404. _this._dPadLeft = 0;
  45405. _this._dPadRight = 0;
  45406. _this._isXboxOnePad = false;
  45407. _this.type = Gamepad.XBOX;
  45408. _this._isXboxOnePad = xboxOne;
  45409. return _this;
  45410. }
  45411. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  45412. this._onlefttriggerchanged = callback;
  45413. };
  45414. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  45415. this._onrighttriggerchanged = callback;
  45416. };
  45417. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  45418. get: function () {
  45419. return this._leftTrigger;
  45420. },
  45421. set: function (newValue) {
  45422. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  45423. this._onlefttriggerchanged(newValue);
  45424. }
  45425. this._leftTrigger = newValue;
  45426. },
  45427. enumerable: true,
  45428. configurable: true
  45429. });
  45430. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  45431. get: function () {
  45432. return this._rightTrigger;
  45433. },
  45434. set: function (newValue) {
  45435. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  45436. this._onrighttriggerchanged(newValue);
  45437. }
  45438. this._rightTrigger = newValue;
  45439. },
  45440. enumerable: true,
  45441. configurable: true
  45442. });
  45443. Xbox360Pad.prototype.onbuttondown = function (callback) {
  45444. this._onbuttondown = callback;
  45445. };
  45446. Xbox360Pad.prototype.onbuttonup = function (callback) {
  45447. this._onbuttonup = callback;
  45448. };
  45449. Xbox360Pad.prototype.ondpaddown = function (callback) {
  45450. this._ondpaddown = callback;
  45451. };
  45452. Xbox360Pad.prototype.ondpadup = function (callback) {
  45453. this._ondpadup = callback;
  45454. };
  45455. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  45456. if (newValue !== currentValue) {
  45457. if (this._onbuttondown && newValue === 1) {
  45458. this._onbuttondown(buttonType);
  45459. }
  45460. if (this._onbuttonup && newValue === 0) {
  45461. this._onbuttonup(buttonType);
  45462. }
  45463. }
  45464. return newValue;
  45465. };
  45466. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  45467. if (newValue !== currentValue) {
  45468. if (this._ondpaddown && newValue === 1) {
  45469. this._ondpaddown(buttonType);
  45470. }
  45471. if (this._ondpadup && newValue === 0) {
  45472. this._ondpadup(buttonType);
  45473. }
  45474. }
  45475. return newValue;
  45476. };
  45477. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  45478. get: function () {
  45479. return this._buttonA;
  45480. },
  45481. set: function (value) {
  45482. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  45483. },
  45484. enumerable: true,
  45485. configurable: true
  45486. });
  45487. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  45488. get: function () {
  45489. return this._buttonB;
  45490. },
  45491. set: function (value) {
  45492. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  45493. },
  45494. enumerable: true,
  45495. configurable: true
  45496. });
  45497. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  45498. get: function () {
  45499. return this._buttonX;
  45500. },
  45501. set: function (value) {
  45502. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  45503. },
  45504. enumerable: true,
  45505. configurable: true
  45506. });
  45507. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  45508. get: function () {
  45509. return this._buttonY;
  45510. },
  45511. set: function (value) {
  45512. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  45513. },
  45514. enumerable: true,
  45515. configurable: true
  45516. });
  45517. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  45518. get: function () {
  45519. return this._buttonStart;
  45520. },
  45521. set: function (value) {
  45522. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  45523. },
  45524. enumerable: true,
  45525. configurable: true
  45526. });
  45527. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  45528. get: function () {
  45529. return this._buttonBack;
  45530. },
  45531. set: function (value) {
  45532. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  45533. },
  45534. enumerable: true,
  45535. configurable: true
  45536. });
  45537. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  45538. get: function () {
  45539. return this._buttonLB;
  45540. },
  45541. set: function (value) {
  45542. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  45543. },
  45544. enumerable: true,
  45545. configurable: true
  45546. });
  45547. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  45548. get: function () {
  45549. return this._buttonRB;
  45550. },
  45551. set: function (value) {
  45552. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  45553. },
  45554. enumerable: true,
  45555. configurable: true
  45556. });
  45557. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  45558. get: function () {
  45559. return this._buttonLeftStick;
  45560. },
  45561. set: function (value) {
  45562. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  45563. },
  45564. enumerable: true,
  45565. configurable: true
  45566. });
  45567. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  45568. get: function () {
  45569. return this._buttonRightStick;
  45570. },
  45571. set: function (value) {
  45572. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  45573. },
  45574. enumerable: true,
  45575. configurable: true
  45576. });
  45577. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  45578. get: function () {
  45579. return this._dPadUp;
  45580. },
  45581. set: function (value) {
  45582. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  45583. },
  45584. enumerable: true,
  45585. configurable: true
  45586. });
  45587. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  45588. get: function () {
  45589. return this._dPadDown;
  45590. },
  45591. set: function (value) {
  45592. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  45593. },
  45594. enumerable: true,
  45595. configurable: true
  45596. });
  45597. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  45598. get: function () {
  45599. return this._dPadLeft;
  45600. },
  45601. set: function (value) {
  45602. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  45603. },
  45604. enumerable: true,
  45605. configurable: true
  45606. });
  45607. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  45608. get: function () {
  45609. return this._dPadRight;
  45610. },
  45611. set: function (value) {
  45612. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  45613. },
  45614. enumerable: true,
  45615. configurable: true
  45616. });
  45617. Xbox360Pad.prototype.update = function () {
  45618. _super.prototype.update.call(this);
  45619. if (this._isXboxOnePad) {
  45620. this.buttonA = this.browserGamepad.buttons[0].value;
  45621. this.buttonB = this.browserGamepad.buttons[1].value;
  45622. this.buttonX = this.browserGamepad.buttons[2].value;
  45623. this.buttonY = this.browserGamepad.buttons[3].value;
  45624. this.buttonLB = this.browserGamepad.buttons[4].value;
  45625. this.buttonRB = this.browserGamepad.buttons[5].value;
  45626. this.leftTrigger = this.browserGamepad.axes[2];
  45627. this.rightTrigger = this.browserGamepad.axes[5];
  45628. this.buttonBack = this.browserGamepad.buttons[9].value;
  45629. this.buttonStart = this.browserGamepad.buttons[8].value;
  45630. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  45631. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  45632. this.dPadUp = this.browserGamepad.buttons[11].value;
  45633. this.dPadDown = this.browserGamepad.buttons[12].value;
  45634. this.dPadLeft = this.browserGamepad.buttons[13].value;
  45635. this.dPadRight = this.browserGamepad.buttons[14].value;
  45636. }
  45637. else {
  45638. this.buttonA = this.browserGamepad.buttons[0].value;
  45639. this.buttonB = this.browserGamepad.buttons[1].value;
  45640. this.buttonX = this.browserGamepad.buttons[2].value;
  45641. this.buttonY = this.browserGamepad.buttons[3].value;
  45642. this.buttonLB = this.browserGamepad.buttons[4].value;
  45643. this.buttonRB = this.browserGamepad.buttons[5].value;
  45644. this.leftTrigger = this.browserGamepad.buttons[6].value;
  45645. this.rightTrigger = this.browserGamepad.buttons[7].value;
  45646. this.buttonBack = this.browserGamepad.buttons[8].value;
  45647. this.buttonStart = this.browserGamepad.buttons[9].value;
  45648. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  45649. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  45650. this.dPadUp = this.browserGamepad.buttons[12].value;
  45651. this.dPadDown = this.browserGamepad.buttons[13].value;
  45652. this.dPadLeft = this.browserGamepad.buttons[14].value;
  45653. this.dPadRight = this.browserGamepad.buttons[15].value;
  45654. }
  45655. };
  45656. return Xbox360Pad;
  45657. }(Gamepad));
  45658. BABYLON.Xbox360Pad = Xbox360Pad;
  45659. })(BABYLON || (BABYLON = {}));
  45660. //# sourceMappingURL=babylon.gamepads.js.map
  45661. var BABYLON;
  45662. (function (BABYLON) {
  45663. var PoseEnabledControllerType;
  45664. (function (PoseEnabledControllerType) {
  45665. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  45666. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  45667. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 2] = "GENERIC";
  45668. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  45669. var PoseEnabledControllerHelper = (function () {
  45670. function PoseEnabledControllerHelper() {
  45671. }
  45672. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  45673. // for now, only Oculus and Vive are supported
  45674. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  45675. return new OculusTouchController(vrGamepad);
  45676. }
  45677. else {
  45678. return new ViveController(vrGamepad);
  45679. }
  45680. };
  45681. return PoseEnabledControllerHelper;
  45682. }());
  45683. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  45684. var PoseEnabledController = (function (_super) {
  45685. __extends(PoseEnabledController, _super);
  45686. function PoseEnabledController(vrGamepad) {
  45687. var _this = _super.call(this, vrGamepad.id, vrGamepad.index, vrGamepad) || this;
  45688. _this.vrGamepad = vrGamepad;
  45689. _this.deviceScaleFactor = 1;
  45690. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  45691. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  45692. _this.controllerType = PoseEnabledControllerType.GENERIC;
  45693. _this.position = BABYLON.Vector3.Zero();
  45694. _this.rotationQuaternion = new BABYLON.Quaternion();
  45695. _this.devicePosition = BABYLON.Vector3.Zero();
  45696. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  45697. _this._calculatedPosition = BABYLON.Vector3.Zero();
  45698. _this._calculatedRotation = new BABYLON.Quaternion();
  45699. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  45700. return _this;
  45701. }
  45702. PoseEnabledController.prototype.update = function () {
  45703. _super.prototype.update.call(this);
  45704. var pose = this.vrGamepad.pose;
  45705. this.updateFromDevice(pose);
  45706. if (this._mesh) {
  45707. this._mesh.position.copyFrom(this._calculatedPosition);
  45708. this._mesh.rotationQuaternion.copyFrom(this._calculatedRotation);
  45709. }
  45710. };
  45711. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  45712. if (poseData) {
  45713. this.rawPose = poseData;
  45714. if (poseData.position) {
  45715. this.devicePosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  45716. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  45717. this.devicePosition.z *= -1;
  45718. }
  45719. this.devicePosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  45720. this._calculatedPosition.addInPlace(this.position);
  45721. }
  45722. if (poseData.orientation) {
  45723. this.deviceRotationQuaternion.copyFromFloats(this.rawPose.orientation[0], this.rawPose.orientation[1], -this.rawPose.orientation[2], -this.rawPose.orientation[3]);
  45724. if (this._mesh) {
  45725. if (this._mesh.getScene().useRightHandedSystem) {
  45726. this.deviceRotationQuaternion.z *= -1;
  45727. this.deviceRotationQuaternion.w *= -1;
  45728. }
  45729. else {
  45730. this.deviceRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this.deviceRotationQuaternion);
  45731. }
  45732. }
  45733. // if the camera is set, rotate to the camera's rotation
  45734. this.deviceRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  45735. }
  45736. }
  45737. };
  45738. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  45739. if (this._mesh) {
  45740. this._mesh.parent = undefined;
  45741. }
  45742. this._mesh = mesh;
  45743. if (this._poseControlledCamera) {
  45744. this._mesh.parent = this._poseControlledCamera;
  45745. }
  45746. if (!this._mesh.rotationQuaternion) {
  45747. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  45748. }
  45749. };
  45750. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  45751. this._poseControlledCamera = camera;
  45752. if (this._mesh) {
  45753. this._mesh.parent = this._poseControlledCamera;
  45754. }
  45755. };
  45756. PoseEnabledController.prototype.detachMesh = function () {
  45757. this._mesh = undefined;
  45758. };
  45759. return PoseEnabledController;
  45760. }(BABYLON.Gamepad));
  45761. BABYLON.PoseEnabledController = PoseEnabledController;
  45762. var WebVRController = (function (_super) {
  45763. __extends(WebVRController, _super);
  45764. function WebVRController(vrGamepad) {
  45765. var _this = _super.call(this, vrGamepad) || this;
  45766. //public onTriggerStateChangedObservable = new Observable<{ state: ExtendedGamepadButton, changes: GamepadButtonChanges }>();
  45767. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  45768. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  45769. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  45770. _this.onPadStateChangedObservable = new BABYLON.Observable();
  45771. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  45772. _this.pad = { x: 0, y: 0 };
  45773. // avoid GC, store state in a tmp object
  45774. _this._changes = {
  45775. pressChanged: false,
  45776. touchChanged: false,
  45777. valueChanged: false,
  45778. changed: false
  45779. };
  45780. _this._buttons = new Array(vrGamepad.buttons.length);
  45781. _this.hand = vrGamepad.hand;
  45782. return _this;
  45783. }
  45784. WebVRController.prototype.onButtonStateChange = function (callback) {
  45785. this._onButtonStateChange = callback;
  45786. };
  45787. WebVRController.prototype.update = function () {
  45788. _super.prototype.update.call(this);
  45789. for (var index = 0; index < this._buttons.length; index++) {
  45790. this._setButtonValue(this.vrGamepad.buttons[index], this._buttons[index], index);
  45791. }
  45792. ;
  45793. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  45794. this.pad.x = this.leftStick.x;
  45795. this.pad.y = this.leftStick.y;
  45796. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  45797. }
  45798. };
  45799. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  45800. if (!currentState) {
  45801. this._buttons[buttonIndex] = {
  45802. pressed: newState.pressed,
  45803. touched: newState.touched,
  45804. value: newState.value
  45805. };
  45806. return;
  45807. }
  45808. this._checkChanges(newState, currentState);
  45809. if (this._changes.changed) {
  45810. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  45811. this.handleButtonChange(buttonIndex, newState, this._changes);
  45812. }
  45813. this._buttons[buttonIndex].pressed = newState.pressed;
  45814. this._buttons[buttonIndex].touched = newState.touched;
  45815. // oculus triggers are never 0, thou not touched.
  45816. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  45817. };
  45818. WebVRController.prototype._checkChanges = function (newState, currentState) {
  45819. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  45820. this._changes.touchChanged = newState.touched !== currentState.touched;
  45821. this._changes.valueChanged = newState.value !== currentState.value;
  45822. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  45823. return this._changes;
  45824. };
  45825. return WebVRController;
  45826. }(PoseEnabledController));
  45827. BABYLON.WebVRController = WebVRController;
  45828. var OculusTouchController = (function (_super) {
  45829. __extends(OculusTouchController, _super);
  45830. function OculusTouchController(vrGamepad) {
  45831. var _this = _super.call(this, vrGamepad) || this;
  45832. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  45833. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  45834. _this.controllerType = PoseEnabledControllerType.OCULUS;
  45835. return _this;
  45836. }
  45837. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  45838. var _this = this;
  45839. var meshName = this.hand === 'right' ? 'RightTouch.babylon' : 'LeftTouch.babylon';
  45840. BABYLON.SceneLoader.ImportMesh("", "http://yoda.blob.core.windows.net/models/", meshName, scene, function (newMeshes) {
  45841. /*
  45842. Parent Mesh name: oculus_touch_left
  45843. - body
  45844. - trigger
  45845. - thumbstick
  45846. - grip
  45847. - button_y
  45848. - button_x
  45849. - button_enter
  45850. */
  45851. _this._defaultModel = newMeshes[1];
  45852. if (meshLoaded) {
  45853. meshLoaded(_this._defaultModel);
  45854. }
  45855. _this.attachToMesh(_this._defaultModel);
  45856. });
  45857. };
  45858. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  45859. // helper getters for left and right hand.
  45860. get: function () {
  45861. if (this.hand === 'right') {
  45862. return this.onMainButtonStateChangedObservable;
  45863. }
  45864. else {
  45865. throw new Error('No A button on left hand');
  45866. }
  45867. },
  45868. enumerable: true,
  45869. configurable: true
  45870. });
  45871. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  45872. get: function () {
  45873. if (this.hand === 'right') {
  45874. return this.onSecondaryButtonStateChangedObservable;
  45875. }
  45876. else {
  45877. throw new Error('No B button on left hand');
  45878. }
  45879. },
  45880. enumerable: true,
  45881. configurable: true
  45882. });
  45883. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  45884. get: function () {
  45885. if (this.hand === 'left') {
  45886. return this.onMainButtonStateChangedObservable;
  45887. }
  45888. else {
  45889. throw new Error('No X button on right hand');
  45890. }
  45891. },
  45892. enumerable: true,
  45893. configurable: true
  45894. });
  45895. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  45896. get: function () {
  45897. if (this.hand === 'left') {
  45898. return this.onSecondaryButtonStateChangedObservable;
  45899. }
  45900. else {
  45901. throw new Error('No Y button on right hand');
  45902. }
  45903. },
  45904. enumerable: true,
  45905. configurable: true
  45906. });
  45907. /*
  45908. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  45909. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  45910. 2) secondary trigger (same)
  45911. 3) A (right) X (left), touch, pressed = value
  45912. 4) B / Y
  45913. 5) thumb rest
  45914. */
  45915. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  45916. var notifyObject = state; //{ state: state, changes: changes };
  45917. var triggerDirection = this.hand === 'right' ? -1 : 1;
  45918. switch (buttonIdx) {
  45919. case 0:
  45920. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  45921. return;
  45922. case 1:
  45923. if (this._defaultModel) {
  45924. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  45925. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  45926. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  45927. }
  45928. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  45929. return;
  45930. case 2:
  45931. if (this._defaultModel) {
  45932. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  45933. }
  45934. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  45935. return;
  45936. case 3:
  45937. if (this._defaultModel) {
  45938. if (notifyObject.pressed) {
  45939. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  45940. }
  45941. else {
  45942. (this._defaultModel.getChildren()[1]).position.y = 0;
  45943. }
  45944. }
  45945. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  45946. return;
  45947. case 4:
  45948. if (this._defaultModel) {
  45949. if (notifyObject.pressed) {
  45950. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  45951. }
  45952. else {
  45953. (this._defaultModel.getChildren()[2]).position.y = 0;
  45954. }
  45955. }
  45956. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  45957. return;
  45958. case 5:
  45959. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  45960. return;
  45961. }
  45962. };
  45963. return OculusTouchController;
  45964. }(WebVRController));
  45965. BABYLON.OculusTouchController = OculusTouchController;
  45966. var ViveController = (function (_super) {
  45967. __extends(ViveController, _super);
  45968. function ViveController(vrGamepad) {
  45969. var _this = _super.call(this, vrGamepad) || this;
  45970. _this.controllerType = PoseEnabledControllerType.VIVE;
  45971. return _this;
  45972. }
  45973. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  45974. var _this = this;
  45975. BABYLON.SceneLoader.ImportMesh("", "http://yoda.blob.core.windows.net/models/", "ViveWand.babylon", scene, function (newMeshes) {
  45976. /*
  45977. Parent Mesh name: ViveWand
  45978. - body
  45979. - r_gripper
  45980. - l_gripper
  45981. - menu_button
  45982. - system_button
  45983. - trackpad
  45984. - trigger
  45985. - LED
  45986. */
  45987. _this._defaultModel = newMeshes[1];
  45988. if (meshLoaded) {
  45989. meshLoaded(_this._defaultModel);
  45990. }
  45991. _this.attachToMesh(_this._defaultModel);
  45992. });
  45993. };
  45994. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  45995. get: function () {
  45996. return this.onMainButtonStateChangedObservable;
  45997. },
  45998. enumerable: true,
  45999. configurable: true
  46000. });
  46001. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  46002. get: function () {
  46003. return this.onMainButtonStateChangedObservable;
  46004. },
  46005. enumerable: true,
  46006. configurable: true
  46007. });
  46008. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  46009. get: function () {
  46010. return this.onSecondaryButtonStateChangedObservable;
  46011. },
  46012. enumerable: true,
  46013. configurable: true
  46014. });
  46015. /**
  46016. * Vive mapping:
  46017. * 0: touchpad
  46018. * 1: trigger
  46019. * 2: left AND right buttons
  46020. * 3: menu button
  46021. */
  46022. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  46023. var notifyObject = state; //{ state: state, changes: changes };
  46024. switch (buttonIdx) {
  46025. case 0:
  46026. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  46027. return;
  46028. case 1:
  46029. if (this._defaultModel) {
  46030. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  46031. }
  46032. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  46033. return;
  46034. case 2:
  46035. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  46036. return;
  46037. case 3:
  46038. if (this._defaultModel) {
  46039. if (notifyObject.pressed) {
  46040. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  46041. }
  46042. else {
  46043. (this._defaultModel.getChildren()[2]).position.y = 0;
  46044. }
  46045. }
  46046. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  46047. return;
  46048. }
  46049. };
  46050. return ViveController;
  46051. }(WebVRController));
  46052. BABYLON.ViveController = ViveController;
  46053. })(BABYLON || (BABYLON = {}));
  46054. //# sourceMappingURL=babylon.extendedGamepad.js.map
  46055. /// <reference path="babylon.targetCamera.ts" />
  46056. var BABYLON;
  46057. (function (BABYLON) {
  46058. var FollowCamera = (function (_super) {
  46059. __extends(FollowCamera, _super);
  46060. function FollowCamera(name, position, scene, lockedTarget) {
  46061. var _this = _super.call(this, name, position, scene) || this;
  46062. _this.radius = 12;
  46063. _this.rotationOffset = 0;
  46064. _this.heightOffset = 4;
  46065. _this.cameraAcceleration = 0.05;
  46066. _this.maxCameraSpeed = 20;
  46067. _this.lockedTarget = lockedTarget;
  46068. return _this;
  46069. }
  46070. FollowCamera.prototype.getRadians = function (degrees) {
  46071. return degrees * Math.PI / 180;
  46072. };
  46073. FollowCamera.prototype.follow = function (cameraTarget) {
  46074. if (!cameraTarget)
  46075. return;
  46076. var yRotation;
  46077. if (cameraTarget.rotationQuaternion) {
  46078. var rotMatrix = new BABYLON.Matrix();
  46079. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  46080. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  46081. }
  46082. else {
  46083. yRotation = cameraTarget.rotation.y;
  46084. }
  46085. var radians = this.getRadians(this.rotationOffset) + yRotation;
  46086. var targetPosition = cameraTarget.getAbsolutePosition();
  46087. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  46088. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  46089. var dx = targetX - this.position.x;
  46090. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  46091. var dz = (targetZ) - this.position.z;
  46092. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  46093. var vy = dy * this.cameraAcceleration;
  46094. var vz = dz * this.cameraAcceleration * 2;
  46095. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  46096. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  46097. }
  46098. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  46099. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  46100. }
  46101. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  46102. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  46103. }
  46104. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  46105. this.setTarget(targetPosition);
  46106. };
  46107. FollowCamera.prototype._checkInputs = function () {
  46108. _super.prototype._checkInputs.call(this);
  46109. this.follow(this.lockedTarget);
  46110. };
  46111. FollowCamera.prototype.getClassName = function () {
  46112. return "FollowCamera";
  46113. };
  46114. return FollowCamera;
  46115. }(BABYLON.TargetCamera));
  46116. __decorate([
  46117. BABYLON.serialize()
  46118. ], FollowCamera.prototype, "radius", void 0);
  46119. __decorate([
  46120. BABYLON.serialize()
  46121. ], FollowCamera.prototype, "rotationOffset", void 0);
  46122. __decorate([
  46123. BABYLON.serialize()
  46124. ], FollowCamera.prototype, "heightOffset", void 0);
  46125. __decorate([
  46126. BABYLON.serialize()
  46127. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  46128. __decorate([
  46129. BABYLON.serialize()
  46130. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  46131. __decorate([
  46132. BABYLON.serializeAsMeshReference("lockedTargetId")
  46133. ], FollowCamera.prototype, "lockedTarget", void 0);
  46134. BABYLON.FollowCamera = FollowCamera;
  46135. var ArcFollowCamera = (function (_super) {
  46136. __extends(ArcFollowCamera, _super);
  46137. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  46138. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  46139. _this.alpha = alpha;
  46140. _this.beta = beta;
  46141. _this.radius = radius;
  46142. _this.target = target;
  46143. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  46144. _this.follow();
  46145. return _this;
  46146. }
  46147. ArcFollowCamera.prototype.follow = function () {
  46148. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  46149. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  46150. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  46151. var targetPosition = this.target.getAbsolutePosition();
  46152. this.position = targetPosition.add(this._cartesianCoordinates);
  46153. this.setTarget(targetPosition);
  46154. };
  46155. ArcFollowCamera.prototype._checkInputs = function () {
  46156. _super.prototype._checkInputs.call(this);
  46157. this.follow();
  46158. };
  46159. ArcFollowCamera.prototype.getClassName = function () {
  46160. return "ArcFollowCamera";
  46161. };
  46162. return ArcFollowCamera;
  46163. }(BABYLON.TargetCamera));
  46164. BABYLON.ArcFollowCamera = ArcFollowCamera;
  46165. })(BABYLON || (BABYLON = {}));
  46166. //# sourceMappingURL=babylon.followCamera.js.map
  46167. /// <reference path="babylon.touchCamera.ts" />
  46168. var BABYLON;
  46169. (function (BABYLON) {
  46170. // We're mainly based on the logic defined into the FreeCamera code
  46171. var UniversalCamera = (function (_super) {
  46172. __extends(UniversalCamera, _super);
  46173. //-- end properties for backward compatibility for inputs
  46174. function UniversalCamera(name, position, scene) {
  46175. var _this = _super.call(this, name, position, scene) || this;
  46176. _this.inputs.addGamepad();
  46177. return _this;
  46178. }
  46179. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  46180. //-- Begin properties for backward compatibility for inputs
  46181. get: function () {
  46182. var gamepad = this.inputs.attached["gamepad"];
  46183. if (gamepad)
  46184. return gamepad.gamepadAngularSensibility;
  46185. },
  46186. set: function (value) {
  46187. var gamepad = this.inputs.attached["gamepad"];
  46188. if (gamepad)
  46189. gamepad.gamepadAngularSensibility = value;
  46190. },
  46191. enumerable: true,
  46192. configurable: true
  46193. });
  46194. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  46195. get: function () {
  46196. var gamepad = this.inputs.attached["gamepad"];
  46197. if (gamepad)
  46198. return gamepad.gamepadMoveSensibility;
  46199. },
  46200. set: function (value) {
  46201. var gamepad = this.inputs.attached["gamepad"];
  46202. if (gamepad)
  46203. gamepad.gamepadMoveSensibility = value;
  46204. },
  46205. enumerable: true,
  46206. configurable: true
  46207. });
  46208. UniversalCamera.prototype.getClassName = function () {
  46209. return "UniversalCamera";
  46210. };
  46211. return UniversalCamera;
  46212. }(BABYLON.TouchCamera));
  46213. BABYLON.UniversalCamera = UniversalCamera;
  46214. })(BABYLON || (BABYLON = {}));
  46215. //# sourceMappingURL=babylon.universalCamera.js.map
  46216. /// <reference path="babylon.universalCamera.ts" />
  46217. var BABYLON;
  46218. (function (BABYLON) {
  46219. // We're mainly based on the logic defined into the FreeCamera code
  46220. var GamepadCamera = (function (_super) {
  46221. __extends(GamepadCamera, _super);
  46222. //-- end properties for backward compatibility for inputs
  46223. function GamepadCamera(name, position, scene) {
  46224. return _super.call(this, name, position, scene) || this;
  46225. }
  46226. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  46227. //-- Begin properties for backward compatibility for inputs
  46228. get: function () {
  46229. var gamepad = this.inputs.attached["gamepad"];
  46230. if (gamepad)
  46231. return gamepad.gamepadAngularSensibility;
  46232. },
  46233. set: function (value) {
  46234. var gamepad = this.inputs.attached["gamepad"];
  46235. if (gamepad)
  46236. gamepad.gamepadAngularSensibility = value;
  46237. },
  46238. enumerable: true,
  46239. configurable: true
  46240. });
  46241. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  46242. get: function () {
  46243. var gamepad = this.inputs.attached["gamepad"];
  46244. if (gamepad)
  46245. return gamepad.gamepadMoveSensibility;
  46246. },
  46247. set: function (value) {
  46248. var gamepad = this.inputs.attached["gamepad"];
  46249. if (gamepad)
  46250. gamepad.gamepadMoveSensibility = value;
  46251. },
  46252. enumerable: true,
  46253. configurable: true
  46254. });
  46255. GamepadCamera.prototype.getClassName = function () {
  46256. return "GamepadCamera";
  46257. };
  46258. return GamepadCamera;
  46259. }(BABYLON.UniversalCamera));
  46260. BABYLON.GamepadCamera = GamepadCamera;
  46261. })(BABYLON || (BABYLON = {}));
  46262. //# sourceMappingURL=babylon.gamepadCamera.js.map
  46263. var BABYLON;
  46264. (function (BABYLON) {
  46265. var PostProcessRenderPipelineManager = (function () {
  46266. function PostProcessRenderPipelineManager() {
  46267. this._renderPipelines = {};
  46268. }
  46269. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  46270. this._renderPipelines[renderPipeline._name] = renderPipeline;
  46271. };
  46272. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  46273. var renderPipeline = this._renderPipelines[renderPipelineName];
  46274. if (!renderPipeline) {
  46275. return;
  46276. }
  46277. renderPipeline._attachCameras(cameras, unique);
  46278. };
  46279. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  46280. var renderPipeline = this._renderPipelines[renderPipelineName];
  46281. if (!renderPipeline) {
  46282. return;
  46283. }
  46284. renderPipeline._detachCameras(cameras);
  46285. };
  46286. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  46287. var renderPipeline = this._renderPipelines[renderPipelineName];
  46288. if (!renderPipeline) {
  46289. return;
  46290. }
  46291. renderPipeline._enableEffect(renderEffectName, cameras);
  46292. };
  46293. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  46294. var renderPipeline = this._renderPipelines[renderPipelineName];
  46295. if (!renderPipeline) {
  46296. return;
  46297. }
  46298. renderPipeline._disableEffect(renderEffectName, cameras);
  46299. };
  46300. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  46301. var renderPipeline = this._renderPipelines[renderPipelineName];
  46302. if (!renderPipeline) {
  46303. return;
  46304. }
  46305. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  46306. };
  46307. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  46308. var renderPipeline = this._renderPipelines[renderPipelineName];
  46309. if (!renderPipeline) {
  46310. return;
  46311. }
  46312. renderPipeline._disableDisplayOnlyPass(cameras);
  46313. };
  46314. PostProcessRenderPipelineManager.prototype.update = function () {
  46315. for (var renderPipelineName in this._renderPipelines) {
  46316. var pipeline = this._renderPipelines[renderPipelineName];
  46317. if (!pipeline.isSupported) {
  46318. pipeline.dispose();
  46319. delete this._renderPipelines[renderPipelineName];
  46320. }
  46321. else {
  46322. pipeline._update();
  46323. }
  46324. }
  46325. };
  46326. return PostProcessRenderPipelineManager;
  46327. }());
  46328. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  46329. })(BABYLON || (BABYLON = {}));
  46330. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  46331. var BABYLON;
  46332. (function (BABYLON) {
  46333. var PostProcessRenderPass = (function () {
  46334. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  46335. this._enabled = true;
  46336. this._refCount = 0;
  46337. this._name = name;
  46338. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  46339. this.setRenderList(renderList);
  46340. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  46341. this._renderTexture.onAfterRenderObservable.add(afterRender);
  46342. this._scene = scene;
  46343. this._renderList = renderList;
  46344. }
  46345. // private
  46346. PostProcessRenderPass.prototype._incRefCount = function () {
  46347. if (this._refCount === 0) {
  46348. this._scene.customRenderTargets.push(this._renderTexture);
  46349. }
  46350. return ++this._refCount;
  46351. };
  46352. PostProcessRenderPass.prototype._decRefCount = function () {
  46353. this._refCount--;
  46354. if (this._refCount <= 0) {
  46355. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  46356. }
  46357. return this._refCount;
  46358. };
  46359. PostProcessRenderPass.prototype._update = function () {
  46360. this.setRenderList(this._renderList);
  46361. };
  46362. // public
  46363. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  46364. this._renderTexture.renderList = renderList;
  46365. };
  46366. PostProcessRenderPass.prototype.getRenderTexture = function () {
  46367. return this._renderTexture;
  46368. };
  46369. return PostProcessRenderPass;
  46370. }());
  46371. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  46372. })(BABYLON || (BABYLON = {}));
  46373. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  46374. var BABYLON;
  46375. (function (BABYLON) {
  46376. var PostProcessRenderEffect = (function () {
  46377. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  46378. this._engine = engine;
  46379. this._name = name;
  46380. this._singleInstance = singleInstance || true;
  46381. this._getPostProcess = getPostProcess;
  46382. this._cameras = [];
  46383. this._indicesForCamera = [];
  46384. this._postProcesses = {};
  46385. this._renderPasses = {};
  46386. this._renderEffectAsPasses = {};
  46387. }
  46388. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  46389. get: function () {
  46390. for (var index in this._postProcesses) {
  46391. if (!this._postProcesses[index].isSupported) {
  46392. return false;
  46393. }
  46394. }
  46395. return true;
  46396. },
  46397. enumerable: true,
  46398. configurable: true
  46399. });
  46400. PostProcessRenderEffect.prototype._update = function () {
  46401. for (var renderPassName in this._renderPasses) {
  46402. this._renderPasses[renderPassName]._update();
  46403. }
  46404. };
  46405. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  46406. this._renderPasses[renderPass._name] = renderPass;
  46407. this._linkParameters();
  46408. };
  46409. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  46410. delete this._renderPasses[renderPass._name];
  46411. this._linkParameters();
  46412. };
  46413. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  46414. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  46415. this._linkParameters();
  46416. };
  46417. PostProcessRenderEffect.prototype.getPass = function (passName) {
  46418. for (var renderPassName in this._renderPasses) {
  46419. if (renderPassName === passName) {
  46420. return this._renderPasses[passName];
  46421. }
  46422. }
  46423. };
  46424. PostProcessRenderEffect.prototype.emptyPasses = function () {
  46425. this._renderPasses = {};
  46426. this._linkParameters();
  46427. };
  46428. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  46429. var cameraKey;
  46430. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  46431. for (var i = 0; i < _cam.length; i++) {
  46432. var camera = _cam[i];
  46433. var cameraName = camera.name;
  46434. if (this._singleInstance) {
  46435. cameraKey = 0;
  46436. }
  46437. else {
  46438. cameraKey = cameraName;
  46439. }
  46440. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  46441. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  46442. if (!this._indicesForCamera[cameraName]) {
  46443. this._indicesForCamera[cameraName] = [];
  46444. }
  46445. this._indicesForCamera[cameraName].push(index);
  46446. if (this._cameras.indexOf(camera) === -1) {
  46447. this._cameras[cameraName] = camera;
  46448. }
  46449. for (var passName in this._renderPasses) {
  46450. this._renderPasses[passName]._incRefCount();
  46451. }
  46452. }
  46453. this._linkParameters();
  46454. };
  46455. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  46456. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  46457. for (var i = 0; i < _cam.length; i++) {
  46458. var camera = _cam[i];
  46459. var cameraName = camera.name;
  46460. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  46461. var index = this._cameras.indexOf(cameraName);
  46462. this._indicesForCamera.splice(index, 1);
  46463. this._cameras.splice(index, 1);
  46464. for (var passName in this._renderPasses) {
  46465. this._renderPasses[passName]._decRefCount();
  46466. }
  46467. }
  46468. };
  46469. PostProcessRenderEffect.prototype._enable = function (cameras) {
  46470. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  46471. for (var i = 0; i < _cam.length; i++) {
  46472. var camera = _cam[i];
  46473. var cameraName = camera.name;
  46474. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  46475. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  46476. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  46477. }
  46478. }
  46479. for (var passName in this._renderPasses) {
  46480. this._renderPasses[passName]._incRefCount();
  46481. }
  46482. }
  46483. };
  46484. PostProcessRenderEffect.prototype._disable = function (cameras) {
  46485. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  46486. for (var i = 0; i < _cam.length; i++) {
  46487. var camera = _cam[i];
  46488. var cameraName = camera.Name;
  46489. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  46490. for (var passName in this._renderPasses) {
  46491. this._renderPasses[passName]._decRefCount();
  46492. }
  46493. }
  46494. };
  46495. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  46496. if (this._singleInstance) {
  46497. return this._postProcesses[0];
  46498. }
  46499. else {
  46500. return this._postProcesses[camera.name];
  46501. }
  46502. };
  46503. PostProcessRenderEffect.prototype._linkParameters = function () {
  46504. var _this = this;
  46505. for (var index in this._postProcesses) {
  46506. if (this.applyParameters) {
  46507. this.applyParameters(this._postProcesses[index]);
  46508. }
  46509. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  46510. _this._linkTextures(effect);
  46511. });
  46512. }
  46513. };
  46514. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  46515. for (var renderPassName in this._renderPasses) {
  46516. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  46517. }
  46518. for (var renderEffectName in this._renderEffectAsPasses) {
  46519. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  46520. }
  46521. };
  46522. return PostProcessRenderEffect;
  46523. }());
  46524. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  46525. })(BABYLON || (BABYLON = {}));
  46526. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  46527. var BABYLON;
  46528. (function (BABYLON) {
  46529. var PostProcessRenderPipeline = (function () {
  46530. function PostProcessRenderPipeline(engine, name) {
  46531. this._engine = engine;
  46532. this._name = name;
  46533. this._renderEffects = {};
  46534. this._renderEffectsForIsolatedPass = {};
  46535. this._cameras = [];
  46536. }
  46537. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  46538. get: function () {
  46539. for (var renderEffectName in this._renderEffects) {
  46540. if (!this._renderEffects[renderEffectName].isSupported) {
  46541. return false;
  46542. }
  46543. }
  46544. return true;
  46545. },
  46546. enumerable: true,
  46547. configurable: true
  46548. });
  46549. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  46550. this._renderEffects[renderEffect._name] = renderEffect;
  46551. };
  46552. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  46553. var renderEffects = this._renderEffects[renderEffectName];
  46554. if (!renderEffects) {
  46555. return;
  46556. }
  46557. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  46558. };
  46559. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  46560. var renderEffects = this._renderEffects[renderEffectName];
  46561. if (!renderEffects) {
  46562. return;
  46563. }
  46564. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  46565. };
  46566. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  46567. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  46568. var indicesToDelete = [];
  46569. var i;
  46570. for (i = 0; i < _cam.length; i++) {
  46571. var camera = _cam[i];
  46572. var cameraName = camera.name;
  46573. if (this._cameras.indexOf(camera) === -1) {
  46574. this._cameras[cameraName] = camera;
  46575. }
  46576. else if (unique) {
  46577. indicesToDelete.push(i);
  46578. }
  46579. }
  46580. for (i = 0; i < indicesToDelete.length; i++) {
  46581. cameras.splice(indicesToDelete[i], 1);
  46582. }
  46583. for (var renderEffectName in this._renderEffects) {
  46584. this._renderEffects[renderEffectName]._attachCameras(_cam);
  46585. }
  46586. };
  46587. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  46588. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  46589. for (var renderEffectName in this._renderEffects) {
  46590. this._renderEffects[renderEffectName]._detachCameras(_cam);
  46591. }
  46592. for (var i = 0; i < _cam.length; i++) {
  46593. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  46594. }
  46595. };
  46596. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  46597. var _this = this;
  46598. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  46599. var pass = null;
  46600. var renderEffectName;
  46601. for (renderEffectName in this._renderEffects) {
  46602. pass = this._renderEffects[renderEffectName].getPass(passName);
  46603. if (pass != null) {
  46604. break;
  46605. }
  46606. }
  46607. if (pass === null) {
  46608. return;
  46609. }
  46610. for (renderEffectName in this._renderEffects) {
  46611. this._renderEffects[renderEffectName]._disable(_cam);
  46612. }
  46613. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  46614. for (var i = 0; i < _cam.length; i++) {
  46615. var camera = _cam[i];
  46616. var cameraName = camera.name;
  46617. 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); });
  46618. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  46619. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  46620. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  46621. }
  46622. };
  46623. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  46624. var _this = this;
  46625. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  46626. for (var i = 0; i < _cam.length; i++) {
  46627. var camera = _cam[i];
  46628. var cameraName = camera.name;
  46629. 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); });
  46630. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  46631. }
  46632. for (var renderEffectName in this._renderEffects) {
  46633. this._renderEffects[renderEffectName]._enable(_cam);
  46634. }
  46635. };
  46636. PostProcessRenderPipeline.prototype._update = function () {
  46637. for (var renderEffectName in this._renderEffects) {
  46638. this._renderEffects[renderEffectName]._update();
  46639. }
  46640. for (var i = 0; i < this._cameras.length; i++) {
  46641. var cameraName = this._cameras[i].name;
  46642. if (this._renderEffectsForIsolatedPass[cameraName]) {
  46643. this._renderEffectsForIsolatedPass[cameraName]._update();
  46644. }
  46645. }
  46646. };
  46647. PostProcessRenderPipeline.prototype.dispose = function () {
  46648. // Must be implemented by children
  46649. };
  46650. return PostProcessRenderPipeline;
  46651. }());
  46652. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  46653. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  46654. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  46655. })(BABYLON || (BABYLON = {}));
  46656. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  46657. var BABYLON;
  46658. (function (BABYLON) {
  46659. var DepthRenderer = (function () {
  46660. function DepthRenderer(scene, type) {
  46661. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  46662. var _this = this;
  46663. this._viewMatrix = BABYLON.Matrix.Zero();
  46664. this._projectionMatrix = BABYLON.Matrix.Zero();
  46665. this._transformMatrix = BABYLON.Matrix.Zero();
  46666. this._worldViewProjection = BABYLON.Matrix.Zero();
  46667. this._scene = scene;
  46668. var engine = scene.getEngine();
  46669. // Render target
  46670. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  46671. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46672. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46673. this._depthMap.refreshRate = 1;
  46674. this._depthMap.renderParticles = false;
  46675. this._depthMap.renderList = null;
  46676. // set default depth value to 1.0 (far away)
  46677. this._depthMap.onClearObservable.add(function (engine) {
  46678. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  46679. });
  46680. // Custom render function
  46681. var renderSubMesh = function (subMesh) {
  46682. var mesh = subMesh.getRenderingMesh();
  46683. var scene = _this._scene;
  46684. var engine = scene.getEngine();
  46685. // Culling
  46686. engine.setState(subMesh.getMaterial().backFaceCulling);
  46687. // Managing instances
  46688. var batch = mesh._getInstancesRenderList(subMesh._id);
  46689. if (batch.mustReturn) {
  46690. return;
  46691. }
  46692. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  46693. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  46694. engine.enableEffect(_this._effect);
  46695. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  46696. var material = subMesh.getMaterial();
  46697. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  46698. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  46699. // Alpha test
  46700. if (material && material.needAlphaTesting()) {
  46701. var alphaTexture = material.getAlphaTestTexture();
  46702. _this._effect.setTexture("diffuseSampler", alphaTexture);
  46703. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  46704. }
  46705. // Bones
  46706. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  46707. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  46708. }
  46709. // Draw
  46710. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  46711. }
  46712. };
  46713. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  46714. var index;
  46715. for (index = 0; index < opaqueSubMeshes.length; index++) {
  46716. renderSubMesh(opaqueSubMeshes.data[index]);
  46717. }
  46718. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  46719. renderSubMesh(alphaTestSubMeshes.data[index]);
  46720. }
  46721. };
  46722. }
  46723. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  46724. var material = subMesh.getMaterial();
  46725. if (material.disableDepthWrite) {
  46726. return false;
  46727. }
  46728. var defines = [];
  46729. var attribs = [BABYLON.VertexBuffer.PositionKind];
  46730. var mesh = subMesh.getMesh();
  46731. var scene = mesh.getScene();
  46732. // Alpha test
  46733. if (material && material.needAlphaTesting()) {
  46734. defines.push("#define ALPHATEST");
  46735. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  46736. attribs.push(BABYLON.VertexBuffer.UVKind);
  46737. defines.push("#define UV1");
  46738. }
  46739. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  46740. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  46741. defines.push("#define UV2");
  46742. }
  46743. }
  46744. // Bones
  46745. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  46746. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  46747. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  46748. if (mesh.numBoneInfluencers > 4) {
  46749. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  46750. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  46751. }
  46752. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  46753. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  46754. }
  46755. else {
  46756. defines.push("#define NUM_BONE_INFLUENCERS 0");
  46757. }
  46758. // Instances
  46759. if (useInstances) {
  46760. defines.push("#define INSTANCES");
  46761. attribs.push("world0");
  46762. attribs.push("world1");
  46763. attribs.push("world2");
  46764. attribs.push("world3");
  46765. }
  46766. // Get correct effect
  46767. var join = defines.join("\n");
  46768. if (this._cachedDefines !== join) {
  46769. this._cachedDefines = join;
  46770. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  46771. }
  46772. return this._effect.isReady();
  46773. };
  46774. DepthRenderer.prototype.getDepthMap = function () {
  46775. return this._depthMap;
  46776. };
  46777. // Methods
  46778. DepthRenderer.prototype.dispose = function () {
  46779. this._depthMap.dispose();
  46780. };
  46781. return DepthRenderer;
  46782. }());
  46783. BABYLON.DepthRenderer = DepthRenderer;
  46784. })(BABYLON || (BABYLON = {}));
  46785. //# sourceMappingURL=babylon.depthRenderer.js.map
  46786. var BABYLON;
  46787. (function (BABYLON) {
  46788. var SSAORenderingPipeline = (function (_super) {
  46789. __extends(SSAORenderingPipeline, _super);
  46790. /**
  46791. * @constructor
  46792. * @param {string} name - The rendering pipeline name
  46793. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  46794. * @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 }
  46795. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  46796. */
  46797. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  46798. var _this = _super.call(this, scene.getEngine(), name) || this;
  46799. // Members
  46800. /**
  46801. * The PassPostProcess id in the pipeline that contains the original scene color
  46802. * @type {string}
  46803. */
  46804. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  46805. /**
  46806. * The SSAO PostProcess id in the pipeline
  46807. * @type {string}
  46808. */
  46809. _this.SSAORenderEffect = "SSAORenderEffect";
  46810. /**
  46811. * The horizontal blur PostProcess id in the pipeline
  46812. * @type {string}
  46813. */
  46814. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  46815. /**
  46816. * The vertical blur PostProcess id in the pipeline
  46817. * @type {string}
  46818. */
  46819. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  46820. /**
  46821. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  46822. * @type {string}
  46823. */
  46824. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  46825. /**
  46826. * The output strength of the SSAO post-process. Default value is 1.0.
  46827. * @type {number}
  46828. */
  46829. _this.totalStrength = 1.0;
  46830. /**
  46831. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  46832. * @type {number}
  46833. */
  46834. _this.radius = 0.0001;
  46835. /**
  46836. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  46837. * Must not be equal to fallOff and superior to fallOff.
  46838. * Default value is 0.975
  46839. * @type {number}
  46840. */
  46841. _this.area = 0.0075;
  46842. /**
  46843. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  46844. * Must not be equal to area and inferior to area.
  46845. * Default value is 0.0
  46846. * @type {number}
  46847. */
  46848. _this.fallOff = 0.000001;
  46849. /**
  46850. * The base color of the SSAO post-process
  46851. * The final result is "base + ssao" between [0, 1]
  46852. * @type {number}
  46853. */
  46854. _this.base = 0.5;
  46855. _this._firstUpdate = true;
  46856. _this._scene = scene;
  46857. // Set up assets
  46858. _this._createRandomTexture();
  46859. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  46860. var ssaoRatio = ratio.ssaoRatio || ratio;
  46861. var combineRatio = ratio.combineRatio || ratio;
  46862. _this._ratio = {
  46863. ssaoRatio: ssaoRatio,
  46864. combineRatio: combineRatio
  46865. };
  46866. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  46867. _this._createSSAOPostProcess(ssaoRatio);
  46868. _this._createBlurPostProcess(ssaoRatio);
  46869. _this._createSSAOCombinePostProcess(combineRatio);
  46870. // Set up pipeline
  46871. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  46872. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  46873. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  46874. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  46875. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  46876. // Finish
  46877. scene.postProcessRenderPipelineManager.addPipeline(_this);
  46878. if (cameras)
  46879. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  46880. return _this;
  46881. }
  46882. // Public Methods
  46883. /**
  46884. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  46885. */
  46886. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  46887. if (disableDepthRender === void 0) { disableDepthRender = false; }
  46888. for (var i = 0; i < this._scene.cameras.length; i++) {
  46889. var camera = this._scene.cameras[i];
  46890. this._originalColorPostProcess.dispose(camera);
  46891. this._ssaoPostProcess.dispose(camera);
  46892. this._blurHPostProcess.dispose(camera);
  46893. this._blurVPostProcess.dispose(camera);
  46894. this._ssaoCombinePostProcess.dispose(camera);
  46895. }
  46896. this._randomTexture.dispose();
  46897. if (disableDepthRender)
  46898. this._scene.disableDepthRenderer();
  46899. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  46900. _super.prototype.dispose.call(this);
  46901. };
  46902. // Private Methods
  46903. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  46904. var _this = this;
  46905. /*
  46906. var samplerOffsets = [
  46907. -8.0, -6.0, -4.0, -2.0,
  46908. 0.0,
  46909. 2.0, 4.0, 6.0, 8.0
  46910. ];
  46911. */
  46912. var samples = 16;
  46913. var samplerOffsets = [];
  46914. for (var i = -8; i < 8; i++) {
  46915. samplerOffsets.push(i * 2);
  46916. }
  46917. 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");
  46918. this._blurHPostProcess.onApply = function (effect) {
  46919. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  46920. effect.setTexture("depthSampler", _this._depthTexture);
  46921. if (_this._firstUpdate) {
  46922. effect.setArray("samplerOffsets", samplerOffsets);
  46923. }
  46924. };
  46925. 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");
  46926. this._blurVPostProcess.onApply = function (effect) {
  46927. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  46928. effect.setTexture("depthSampler", _this._depthTexture);
  46929. if (_this._firstUpdate) {
  46930. effect.setArray("samplerOffsets", samplerOffsets);
  46931. _this._firstUpdate = false;
  46932. }
  46933. };
  46934. };
  46935. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  46936. var _this = this;
  46937. var numSamples = 16;
  46938. var sampleSphere = [
  46939. 0.5381, 0.1856, -0.4319,
  46940. 0.1379, 0.2486, 0.4430,
  46941. 0.3371, 0.5679, -0.0057,
  46942. -0.6999, -0.0451, -0.0019,
  46943. 0.0689, -0.1598, -0.8547,
  46944. 0.0560, 0.0069, -0.1843,
  46945. -0.0146, 0.1402, 0.0762,
  46946. 0.0100, -0.1924, -0.0344,
  46947. -0.3577, -0.5301, -0.4358,
  46948. -0.3169, 0.1063, 0.0158,
  46949. 0.0103, -0.5869, 0.0046,
  46950. -0.0897, -0.4940, 0.3287,
  46951. 0.7119, -0.0154, -0.0918,
  46952. -0.0533, 0.0596, -0.5411,
  46953. 0.0352, -0.0631, 0.5460,
  46954. -0.4776, 0.2847, -0.0271
  46955. ];
  46956. var samplesFactor = 1.0 / numSamples;
  46957. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  46958. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  46959. "area", "fallOff", "base", "range", "viewport"
  46960. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  46961. var viewport = new BABYLON.Vector2(0, 0);
  46962. this._ssaoPostProcess.onApply = function (effect) {
  46963. if (_this._firstUpdate) {
  46964. effect.setArray3("sampleSphere", sampleSphere);
  46965. effect.setFloat("samplesFactor", samplesFactor);
  46966. effect.setFloat("randTextureTiles", 4.0);
  46967. }
  46968. effect.setFloat("totalStrength", _this.totalStrength);
  46969. effect.setFloat("radius", _this.radius);
  46970. effect.setFloat("area", _this.area);
  46971. effect.setFloat("fallOff", _this.fallOff);
  46972. effect.setFloat("base", _this.base);
  46973. effect.setTexture("textureSampler", _this._depthTexture);
  46974. effect.setTexture("randomSampler", _this._randomTexture);
  46975. };
  46976. };
  46977. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  46978. var _this = this;
  46979. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  46980. this._ssaoCombinePostProcess.onApply = function (effect) {
  46981. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  46982. };
  46983. };
  46984. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  46985. var size = 512;
  46986. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  46987. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  46988. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  46989. var context = this._randomTexture.getContext();
  46990. var rand = function (min, max) {
  46991. return Math.random() * (max - min) + min;
  46992. };
  46993. var randVector = BABYLON.Vector3.Zero();
  46994. for (var x = 0; x < size; x++) {
  46995. for (var y = 0; y < size; y++) {
  46996. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  46997. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  46998. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  46999. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  47000. context.fillRect(x, y, 1, 1);
  47001. }
  47002. }
  47003. this._randomTexture.update(false);
  47004. };
  47005. return SSAORenderingPipeline;
  47006. }(BABYLON.PostProcessRenderPipeline));
  47007. __decorate([
  47008. BABYLON.serialize()
  47009. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  47010. __decorate([
  47011. BABYLON.serialize()
  47012. ], SSAORenderingPipeline.prototype, "radius", void 0);
  47013. __decorate([
  47014. BABYLON.serialize()
  47015. ], SSAORenderingPipeline.prototype, "area", void 0);
  47016. __decorate([
  47017. BABYLON.serialize()
  47018. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  47019. __decorate([
  47020. BABYLON.serialize()
  47021. ], SSAORenderingPipeline.prototype, "base", void 0);
  47022. __decorate([
  47023. BABYLON.serialize()
  47024. ], SSAORenderingPipeline.prototype, "_ratio", void 0);
  47025. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  47026. })(BABYLON || (BABYLON = {}));
  47027. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  47028. // BABYLON.JS Chromatic Aberration GLSL Shader
  47029. // Author: Olivier Guyot
  47030. // Separates very slightly R, G and B colors on the edges of the screen
  47031. // Inspired by Francois Tarlier & Martins Upitis
  47032. var BABYLON;
  47033. (function (BABYLON) {
  47034. var LensRenderingPipeline = (function (_super) {
  47035. __extends(LensRenderingPipeline, _super);
  47036. /**
  47037. * @constructor
  47038. *
  47039. * Effect parameters are as follow:
  47040. * {
  47041. * chromatic_aberration: number; // from 0 to x (1 for realism)
  47042. * edge_blur: number; // from 0 to x (1 for realism)
  47043. * distortion: number; // from 0 to x (1 for realism)
  47044. * grain_amount: number; // from 0 to 1
  47045. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  47046. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  47047. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  47048. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  47049. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  47050. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  47051. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  47052. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  47053. * }
  47054. * Note: if an effect parameter is unset, effect is disabled
  47055. *
  47056. * @param {string} name - The rendering pipeline name
  47057. * @param {object} parameters - An object containing all parameters (see above)
  47058. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  47059. * @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)
  47060. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  47061. */
  47062. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  47063. if (ratio === void 0) { ratio = 1.0; }
  47064. var _this = _super.call(this, scene.getEngine(), name) || this;
  47065. // Lens effects can be of the following:
  47066. // - chromatic aberration (slight shift of RGB colors)
  47067. // - blur on the edge of the lens
  47068. // - lens distortion
  47069. // - depth-of-field blur & highlights enhancing
  47070. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  47071. // - grain effect (noise or custom texture)
  47072. // Two additional texture samplers are needed:
  47073. // - depth map (for depth-of-field)
  47074. // - grain texture
  47075. /**
  47076. * The chromatic aberration PostProcess id in the pipeline
  47077. * @type {string}
  47078. */
  47079. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  47080. /**
  47081. * The highlights enhancing PostProcess id in the pipeline
  47082. * @type {string}
  47083. */
  47084. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  47085. /**
  47086. * The depth-of-field PostProcess id in the pipeline
  47087. * @type {string}
  47088. */
  47089. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  47090. _this._scene = scene;
  47091. // Fetch texture samplers
  47092. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  47093. if (parameters.grain_texture) {
  47094. _this._grainTexture = parameters.grain_texture;
  47095. }
  47096. else {
  47097. _this._createGrainTexture();
  47098. }
  47099. // save parameters
  47100. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  47101. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  47102. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  47103. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  47104. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  47105. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  47106. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  47107. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  47108. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  47109. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  47110. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  47111. // Create effects
  47112. _this._createChromaticAberrationPostProcess(ratio);
  47113. _this._createHighlightsPostProcess(ratio);
  47114. _this._createDepthOfFieldPostProcess(ratio / 4);
  47115. // Set up pipeline
  47116. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  47117. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  47118. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  47119. if (_this._highlightsGain === -1) {
  47120. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  47121. }
  47122. // Finish
  47123. scene.postProcessRenderPipelineManager.addPipeline(_this);
  47124. if (cameras) {
  47125. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  47126. }
  47127. return _this;
  47128. }
  47129. // public methods (self explanatory)
  47130. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  47131. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  47132. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  47133. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  47134. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  47135. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  47136. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  47137. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  47138. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  47139. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  47140. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  47141. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  47142. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  47143. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  47144. };
  47145. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  47146. this._highlightsPostProcess.updateEffect();
  47147. };
  47148. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  47149. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  47150. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  47151. this._highlightsGain = amount;
  47152. };
  47153. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  47154. if (this._highlightsGain === -1) {
  47155. this._highlightsGain = 1.0;
  47156. }
  47157. this._highlightsThreshold = amount;
  47158. };
  47159. LensRenderingPipeline.prototype.disableHighlights = function () {
  47160. this._highlightsGain = -1;
  47161. };
  47162. /**
  47163. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  47164. */
  47165. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  47166. if (disableDepthRender === void 0) { disableDepthRender = false; }
  47167. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  47168. this._chromaticAberrationPostProcess = undefined;
  47169. this._highlightsPostProcess = undefined;
  47170. this._depthOfFieldPostProcess = undefined;
  47171. this._grainTexture.dispose();
  47172. if (disableDepthRender)
  47173. this._scene.disableDepthRenderer();
  47174. };
  47175. // colors shifting and distortion
  47176. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  47177. var _this = this;
  47178. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  47179. [], // samplers
  47180. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  47181. this._chromaticAberrationPostProcess.onApply = function (effect) {
  47182. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  47183. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  47184. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  47185. };
  47186. };
  47187. // highlights enhancing
  47188. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  47189. var _this = this;
  47190. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  47191. [], // samplers
  47192. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  47193. this._highlightsPostProcess.onApply = function (effect) {
  47194. effect.setFloat('gain', _this._highlightsGain);
  47195. effect.setFloat('threshold', _this._highlightsThreshold);
  47196. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  47197. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  47198. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  47199. };
  47200. };
  47201. // colors shifting and distortion
  47202. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  47203. var _this = this;
  47204. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  47205. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  47206. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  47207. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  47208. this._depthOfFieldPostProcess.onApply = function (effect) {
  47209. effect.setTexture("depthSampler", _this._depthTexture);
  47210. effect.setTexture("grainSampler", _this._grainTexture);
  47211. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  47212. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  47213. effect.setFloat('grain_amount', _this._grainAmount);
  47214. effect.setBool('blur_noise', _this._blurNoise);
  47215. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  47216. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  47217. effect.setFloat('distortion', _this._distortion);
  47218. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  47219. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  47220. effect.setFloat('aperture', _this._dofAperture);
  47221. effect.setFloat('darken', _this._dofDarken);
  47222. effect.setFloat('edge_blur', _this._edgeBlur);
  47223. effect.setBool('highlights', (_this._highlightsGain !== -1));
  47224. effect.setFloat('near', _this._scene.activeCamera.minZ);
  47225. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  47226. };
  47227. };
  47228. // creates a black and white random noise texture, 512x512
  47229. LensRenderingPipeline.prototype._createGrainTexture = function () {
  47230. var size = 512;
  47231. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  47232. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  47233. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  47234. var context = this._grainTexture.getContext();
  47235. var rand = function (min, max) {
  47236. return Math.random() * (max - min) + min;
  47237. };
  47238. var value;
  47239. for (var x = 0; x < size; x++) {
  47240. for (var y = 0; y < size; y++) {
  47241. value = Math.floor(rand(0.42, 0.58) * 255);
  47242. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  47243. context.fillRect(x, y, 1, 1);
  47244. }
  47245. }
  47246. this._grainTexture.update(false);
  47247. };
  47248. return LensRenderingPipeline;
  47249. }(BABYLON.PostProcessRenderPipeline));
  47250. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  47251. })(BABYLON || (BABYLON = {}));
  47252. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  47253. /// <reference path="RenderPipeline\babylon.postProcessRenderPipeline.ts" />
  47254. var BABYLON;
  47255. (function (BABYLON) {
  47256. var HDRRenderingPipeline = (function (_super) {
  47257. __extends(HDRRenderingPipeline, _super);
  47258. /**
  47259. * @constructor
  47260. * @param {string} name - The rendering pipeline name
  47261. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  47262. * @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)
  47263. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  47264. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  47265. */
  47266. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  47267. if (originalPostProcess === void 0) { originalPostProcess = null; }
  47268. var _this = _super.call(this, scene.getEngine(), name) || this;
  47269. /**
  47270. * Public members
  47271. */
  47272. // Gaussian Blur
  47273. /**
  47274. * Gaussian blur coefficient
  47275. * @type {number}
  47276. */
  47277. _this.gaussCoeff = 0.3;
  47278. /**
  47279. * Gaussian blur mean
  47280. * @type {number}
  47281. */
  47282. _this.gaussMean = 1.0;
  47283. /**
  47284. * Gaussian blur standard deviation
  47285. * @type {number}
  47286. */
  47287. _this.gaussStandDev = 0.8;
  47288. /**
  47289. * Gaussian blur multiplier. Multiplies the blur effect
  47290. * @type {number}
  47291. */
  47292. _this.gaussMultiplier = 4.0;
  47293. // HDR
  47294. /**
  47295. * Exposure, controls the overall intensity of the pipeline
  47296. * @type {number}
  47297. */
  47298. _this.exposure = 1.0;
  47299. /**
  47300. * Minimum luminance that the post-process can output. Luminance is >= 0
  47301. * @type {number}
  47302. */
  47303. _this.minimumLuminance = 1.0;
  47304. /**
  47305. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  47306. * @type {number}
  47307. */
  47308. _this.maximumLuminance = 1e20;
  47309. /**
  47310. * Increase rate for luminance: eye adaptation speed to dark
  47311. * @type {number}
  47312. */
  47313. _this.luminanceIncreaserate = 0.5;
  47314. /**
  47315. * Decrease rate for luminance: eye adaptation speed to bright
  47316. * @type {number}
  47317. */
  47318. _this.luminanceDecreaseRate = 0.5;
  47319. // Bright pass
  47320. /**
  47321. * Minimum luminance needed to compute HDR
  47322. * @type {number}
  47323. */
  47324. _this.brightThreshold = 0.8;
  47325. _this._needUpdate = true;
  47326. _this._scene = scene;
  47327. // Bright pass
  47328. _this._createBrightPassPostProcess(scene, ratio);
  47329. // Down sample X4
  47330. _this._createDownSampleX4PostProcess(scene, ratio);
  47331. // Create gaussian blur post-processes
  47332. _this._createGaussianBlurPostProcess(scene, ratio);
  47333. // Texture adder
  47334. _this._createTextureAdderPostProcess(scene, ratio);
  47335. // Luminance generator
  47336. _this._createLuminanceGeneratorPostProcess(scene);
  47337. // HDR
  47338. _this._createHDRPostProcess(scene, ratio);
  47339. // Pass postprocess
  47340. if (originalPostProcess === null) {
  47341. _this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  47342. }
  47343. else {
  47344. _this._originalPostProcess = originalPostProcess;
  47345. }
  47346. // Configure pipeline
  47347. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  47348. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  47349. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  47350. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  47351. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  47352. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  47353. var addDownSamplerPostProcess = function (id) {
  47354. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  47355. };
  47356. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  47357. addDownSamplerPostProcess(i);
  47358. }
  47359. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  47360. // Finish
  47361. scene.postProcessRenderPipelineManager.addPipeline(_this);
  47362. if (cameras !== null) {
  47363. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  47364. }
  47365. _this.update();
  47366. return _this;
  47367. }
  47368. /**
  47369. * Tells the pipeline to update its post-processes
  47370. */
  47371. HDRRenderingPipeline.prototype.update = function () {
  47372. this._needUpdate = true;
  47373. };
  47374. /**
  47375. * Returns the current calculated luminance
  47376. */
  47377. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  47378. return this._hdrCurrentLuminance;
  47379. };
  47380. /**
  47381. * Returns the currently drawn luminance
  47382. */
  47383. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  47384. return this._hdrOutputLuminance;
  47385. };
  47386. /**
  47387. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  47388. */
  47389. HDRRenderingPipeline.prototype.dispose = function () {
  47390. for (var i = 0; i < this._scene.cameras.length; i++) {
  47391. var camera = this._scene.cameras[i];
  47392. this._originalPostProcess.dispose(camera);
  47393. this._brightPassPostProcess.dispose(camera);
  47394. this._downSampleX4PostProcess.dispose(camera);
  47395. this._guassianBlurHPostProcess.dispose(camera);
  47396. this._guassianBlurVPostProcess.dispose(camera);
  47397. this._textureAdderPostProcess.dispose(camera);
  47398. for (var j = HDRRenderingPipeline.LUM_STEPS - 1; j >= 0; j--) {
  47399. this._downSamplePostProcesses[j].dispose(camera);
  47400. }
  47401. this._hdrPostProcess.dispose(camera);
  47402. }
  47403. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  47404. _super.prototype.dispose.call(this);
  47405. };
  47406. /**
  47407. * Creates the HDR post-process and computes the luminance adaptation
  47408. */
  47409. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  47410. var _this = this;
  47411. var hdrLastLuminance = 0.0;
  47412. this._hdrOutputLuminance = -1.0;
  47413. this._hdrCurrentLuminance = 1.0;
  47414. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  47415. this._hdrPostProcess.onApply = function (effect) {
  47416. if (_this._hdrOutputLuminance < 0.0) {
  47417. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  47418. }
  47419. else {
  47420. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  47421. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  47422. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  47423. }
  47424. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  47425. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  47426. }
  47427. else {
  47428. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  47429. }
  47430. }
  47431. _this._hdrOutputLuminance = BABYLON.MathTools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  47432. hdrLastLuminance += scene.getEngine().getDeltaTime();
  47433. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  47434. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  47435. effect.setFloat("exposure", _this.exposure);
  47436. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  47437. _this._needUpdate = false;
  47438. };
  47439. };
  47440. /**
  47441. * Texture Adder post-process
  47442. */
  47443. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  47444. var _this = this;
  47445. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  47446. this._textureAdderPostProcess.onApply = function (effect) {
  47447. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  47448. };
  47449. };
  47450. /**
  47451. * Down sample X4 post-process
  47452. */
  47453. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  47454. var _this = this;
  47455. var downSampleX4Offsets = new Array(32);
  47456. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  47457. this._downSampleX4PostProcess.onApply = function (effect) {
  47458. if (_this._needUpdate) {
  47459. var id = 0;
  47460. for (var i = -2; i < 2; i++) {
  47461. for (var j = -2; j < 2; j++) {
  47462. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  47463. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  47464. id += 2;
  47465. }
  47466. }
  47467. }
  47468. effect.setArray2("dsOffsets", downSampleX4Offsets);
  47469. };
  47470. };
  47471. /**
  47472. * Bright pass post-process
  47473. */
  47474. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  47475. var _this = this;
  47476. var brightOffsets = new Array(8);
  47477. var brightPassCallback = function (effect) {
  47478. if (_this._needUpdate) {
  47479. var sU = (1.0 / _this._brightPassPostProcess.width);
  47480. var sV = (1.0 / _this._brightPassPostProcess.height);
  47481. brightOffsets[0] = -0.5 * sU;
  47482. brightOffsets[1] = 0.5 * sV;
  47483. brightOffsets[2] = 0.5 * sU;
  47484. brightOffsets[3] = 0.5 * sV;
  47485. brightOffsets[4] = -0.5 * sU;
  47486. brightOffsets[5] = -0.5 * sV;
  47487. brightOffsets[6] = 0.5 * sU;
  47488. brightOffsets[7] = -0.5 * sV;
  47489. }
  47490. effect.setArray2("dsOffsets", brightOffsets);
  47491. effect.setFloat("brightThreshold", _this.brightThreshold);
  47492. };
  47493. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  47494. this._brightPassPostProcess.onApply = brightPassCallback;
  47495. };
  47496. /**
  47497. * Luminance generator. Creates the luminance post-process and down sample post-processes
  47498. */
  47499. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  47500. var _this = this;
  47501. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  47502. var luminanceOffsets = new Array(8);
  47503. var downSampleOffsets = new Array(18);
  47504. var halfDestPixelSize;
  47505. this._downSamplePostProcesses = new Array(lumSteps);
  47506. // Utils for luminance
  47507. var luminanceUpdateSourceOffsets = function (width, height) {
  47508. var sU = (1.0 / width);
  47509. var sV = (1.0 / height);
  47510. luminanceOffsets[0] = -0.5 * sU;
  47511. luminanceOffsets[1] = 0.5 * sV;
  47512. luminanceOffsets[2] = 0.5 * sU;
  47513. luminanceOffsets[3] = 0.5 * sV;
  47514. luminanceOffsets[4] = -0.5 * sU;
  47515. luminanceOffsets[5] = -0.5 * sV;
  47516. luminanceOffsets[6] = 0.5 * sU;
  47517. luminanceOffsets[7] = -0.5 * sV;
  47518. };
  47519. var luminanceUpdateDestOffsets = function (width, height) {
  47520. var id = 0;
  47521. for (var x = -1; x < 2; x++) {
  47522. for (var y = -1; y < 2; y++) {
  47523. downSampleOffsets[id] = (x) / width;
  47524. downSampleOffsets[id + 1] = (y) / height;
  47525. id += 2;
  47526. }
  47527. }
  47528. };
  47529. // Luminance callback
  47530. var luminanceCallback = function (effect) {
  47531. if (_this._needUpdate) {
  47532. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  47533. }
  47534. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  47535. effect.setArray2("lumOffsets", luminanceOffsets);
  47536. };
  47537. // Down sample callbacks
  47538. var downSampleCallback = function (indice) {
  47539. var i = indice;
  47540. return function (effect) {
  47541. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  47542. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  47543. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  47544. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  47545. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  47546. effect.setArray2("dsOffsets", downSampleOffsets);
  47547. };
  47548. };
  47549. var downSampleAfterRenderCallback = function (effect) {
  47550. // Unpack result
  47551. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  47552. 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);
  47553. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  47554. };
  47555. // Create luminance post-process
  47556. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  47557. 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);
  47558. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  47559. // Create down sample post-processes
  47560. for (var i = lumSteps - 2; i >= 0; i--) {
  47561. var length = Math.pow(3, i);
  47562. ratio = { width: length, height: length };
  47563. var defines = "#define DOWN_SAMPLE\n";
  47564. if (i === 0) {
  47565. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  47566. }
  47567. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  47568. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  47569. if (i === 0) {
  47570. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  47571. }
  47572. }
  47573. };
  47574. /**
  47575. * Gaussian blur post-processes. Horizontal and Vertical
  47576. */
  47577. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  47578. var _this = this;
  47579. var blurOffsetsW = new Array(9);
  47580. var blurOffsetsH = new Array(9);
  47581. var blurWeights = new Array(9);
  47582. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  47583. // Utils for gaussian blur
  47584. var calculateBlurOffsets = function (height) {
  47585. var lastOutputDimensions = {
  47586. width: scene.getEngine().getRenderWidth(),
  47587. height: scene.getEngine().getRenderHeight()
  47588. };
  47589. for (var i = 0; i < 9; i++) {
  47590. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  47591. if (height) {
  47592. blurOffsetsH[i] = value;
  47593. }
  47594. else {
  47595. blurOffsetsW[i] = value;
  47596. }
  47597. }
  47598. };
  47599. var calculateWeights = function () {
  47600. var x = 0.0;
  47601. for (var i = 0; i < 9; i++) {
  47602. x = (i - 4.0) / 4.0;
  47603. 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));
  47604. }
  47605. };
  47606. // Callback
  47607. var gaussianBlurCallback = function (height) {
  47608. return function (effect) {
  47609. if (_this._needUpdate) {
  47610. calculateWeights();
  47611. calculateBlurOffsets(height);
  47612. }
  47613. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  47614. effect.setArray("blurWeights", blurWeights);
  47615. effect.setFloat("multiplier", _this.gaussMultiplier);
  47616. };
  47617. };
  47618. // Create horizontal gaussian blur post-processes
  47619. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  47620. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  47621. // Create vertical gaussian blur post-process
  47622. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  47623. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  47624. };
  47625. return HDRRenderingPipeline;
  47626. }(BABYLON.PostProcessRenderPipeline));
  47627. // Luminance generator
  47628. HDRRenderingPipeline.LUM_STEPS = 6;
  47629. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  47630. })(BABYLON || (BABYLON = {}));
  47631. //# sourceMappingURL=babylon.hdrRenderingPipeline.js.map
  47632. /// <reference path="RenderPipeline\babylon.postProcessRenderPipeline.ts" />
  47633. var BABYLON;
  47634. (function (BABYLON) {
  47635. var StandardRenderingPipeline = (function (_super) {
  47636. __extends(StandardRenderingPipeline, _super);
  47637. /**
  47638. * @constructor
  47639. * @param {string} name - The rendering pipeline name
  47640. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  47641. * @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)
  47642. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  47643. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  47644. */
  47645. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  47646. if (originalPostProcess === void 0) { originalPostProcess = null; }
  47647. var _this = _super.call(this, scene.getEngine(), name) || this;
  47648. _this.downSampleX4PostProcess = null;
  47649. _this.brightPassPostProcess = null;
  47650. _this.gaussianBlurHPostProcesses = [];
  47651. _this.gaussianBlurVPostProcesses = [];
  47652. _this.textureAdderPostProcess = null;
  47653. _this.textureAdderFinalPostProcess = null;
  47654. _this.lensFlareFinalPostProcess = null;
  47655. _this.lensFlarePostProcess = null;
  47656. _this.lensFlareComposePostProcess = null;
  47657. _this.depthOfFieldPostProcess = null;
  47658. // Values
  47659. _this.brightThreshold = 1.0;
  47660. _this.blurWidth = 2.0;
  47661. _this.horizontalBlur = false;
  47662. _this.gaussianCoefficient = 0.25;
  47663. _this.gaussianMean = 1.0;
  47664. _this.gaussianStandardDeviation = 1.0;
  47665. _this.exposure = 1.0;
  47666. _this.lensTexture = null;
  47667. _this.lensColorTexture = null;
  47668. _this.lensFlareStrength = 20.0;
  47669. _this.lensFlareGhostDispersal = 1.4;
  47670. _this.lensFlareHaloWidth = 0.7;
  47671. _this.lensFlareDistortionStrength = 16.0;
  47672. _this.lensStarTexture = null;
  47673. _this.lensFlareDirtTexture = null;
  47674. _this.depthOfFieldDistance = 10.0;
  47675. _this.depthOfFieldBlurWidth = 2.0;
  47676. // IAnimatable
  47677. _this.animations = [];
  47678. _this._depthRenderer = null;
  47679. _this._currentDepthOfFieldSource = null;
  47680. // Getters and setters
  47681. _this._depthOfFieldEnabled = true;
  47682. _this._lensFlareEnabled = true;
  47683. _this._cameras = cameras || [];
  47684. // Initialize
  47685. _this._scene = scene;
  47686. // Create pass post-processe
  47687. if (!originalPostProcess) {
  47688. _this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_FLOAT);
  47689. }
  47690. else {
  47691. _this.originalPostProcess = originalPostProcess;
  47692. }
  47693. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  47694. // Create down sample X4 post-process
  47695. _this._createDownSampleX4PostProcess(scene, ratio / 2);
  47696. // Create bright pass post-process
  47697. _this._createBrightPassPostProcess(scene, ratio / 2);
  47698. // Create gaussian blur post-processes (down sampling blurs)
  47699. _this._createGaussianBlurPostProcesses(scene, ratio / 2, 0);
  47700. _this._createGaussianBlurPostProcesses(scene, ratio / 4, 1);
  47701. _this._createGaussianBlurPostProcesses(scene, ratio / 8, 2);
  47702. _this._createGaussianBlurPostProcesses(scene, ratio / 16, 3);
  47703. // Create texture adder post-process
  47704. _this._createTextureAdderPostProcess(scene, ratio);
  47705. // Create depth-of-field source post-process
  47706. _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);
  47707. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  47708. // Create lens flare post-process
  47709. _this._createLensFlarePostProcess(scene, ratio);
  47710. // Create depth-of-field source post-process post lens-flare and disable it now
  47711. _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);
  47712. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  47713. // Create gaussian blur used by depth-of-field
  47714. _this._createGaussianBlurPostProcesses(scene, ratio / 2, 5, "depthOfFieldBlurWidth");
  47715. // Create depth-of-field post-process
  47716. _this._createDepthOfFieldPostProcess(scene, ratio);
  47717. // Finish
  47718. scene.postProcessRenderPipelineManager.addPipeline(_this);
  47719. if (cameras !== null) {
  47720. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  47721. }
  47722. // Deactivate
  47723. _this.LensFlareEnabled = false;
  47724. _this.DepthOfFieldEnabled = false;
  47725. return _this;
  47726. }
  47727. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  47728. get: function () {
  47729. return this._depthOfFieldEnabled;
  47730. },
  47731. set: function (enabled) {
  47732. var blurIndex = this.gaussianBlurHPostProcesses.length - 1;
  47733. if (enabled && !this._depthOfFieldEnabled) {
  47734. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._cameras);
  47735. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._cameras);
  47736. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRDepthOfField", this._cameras);
  47737. this._depthRenderer = this._scene.enableDepthRenderer();
  47738. }
  47739. else if (!enabled && this._depthOfFieldEnabled) {
  47740. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._cameras);
  47741. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._cameras);
  47742. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRDepthOfField", this._cameras);
  47743. }
  47744. this._depthOfFieldEnabled = enabled;
  47745. },
  47746. enumerable: true,
  47747. configurable: true
  47748. });
  47749. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  47750. get: function () {
  47751. return this._lensFlareEnabled;
  47752. },
  47753. set: function (enabled) {
  47754. var blurIndex = this.gaussianBlurHPostProcesses.length - 2;
  47755. if (enabled && !this._lensFlareEnabled) {
  47756. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlare", this._cameras);
  47757. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlareShift", this._cameras);
  47758. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._cameras);
  47759. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._cameras);
  47760. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlareCompose", this._cameras);
  47761. this._setDepthOfFieldSavePostProcess("HDRPostLensFlareDepthOfFieldSource");
  47762. }
  47763. else if (!enabled && this._lensFlareEnabled) {
  47764. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlare", this._cameras);
  47765. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlareShift", this._cameras);
  47766. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._cameras);
  47767. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._cameras);
  47768. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlareCompose", this._cameras);
  47769. this._setDepthOfFieldSavePostProcess("HDRBaseDepthOfFieldSource");
  47770. }
  47771. this._lensFlareEnabled = enabled;
  47772. },
  47773. enumerable: true,
  47774. configurable: true
  47775. });
  47776. // Sets depth-of-field save post-process
  47777. StandardRenderingPipeline.prototype._setDepthOfFieldSavePostProcess = function (name) {
  47778. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRPostLensFlareDepthOfFieldSource", this._cameras);
  47779. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, name, this._cameras);
  47780. switch (name) {
  47781. case "HDRBaseDepthOfFieldSource":
  47782. this._currentDepthOfFieldSource = this.textureAdderFinalPostProcess;
  47783. break;
  47784. case "HDRPostLensFlareDepthOfFieldSource":
  47785. this._currentDepthOfFieldSource = this.lensFlareFinalPostProcess;
  47786. break;
  47787. default: break;
  47788. }
  47789. };
  47790. // Down Sample X4 Post-Processs
  47791. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  47792. var _this = this;
  47793. var downSampleX4Offsets = new Array(32);
  47794. 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);
  47795. this.downSampleX4PostProcess.onApply = function (effect) {
  47796. var id = 0;
  47797. for (var i = -2; i < 2; i++) {
  47798. for (var j = -2; j < 2; j++) {
  47799. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this.downSampleX4PostProcess.width);
  47800. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this.downSampleX4PostProcess.height);
  47801. id += 2;
  47802. }
  47803. }
  47804. effect.setArray2("dsOffsets", downSampleX4Offsets);
  47805. };
  47806. // Add to pipeline
  47807. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  47808. };
  47809. // Brightpass Post-Process
  47810. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  47811. var _this = this;
  47812. var brightOffsets = new Array(8);
  47813. 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);
  47814. this.brightPassPostProcess.onApply = function (effect) {
  47815. var sU = (1.0 / _this.brightPassPostProcess.width);
  47816. var sV = (1.0 / _this.brightPassPostProcess.height);
  47817. brightOffsets[0] = -0.5 * sU;
  47818. brightOffsets[1] = 0.5 * sV;
  47819. brightOffsets[2] = 0.5 * sU;
  47820. brightOffsets[3] = 0.5 * sV;
  47821. brightOffsets[4] = -0.5 * sU;
  47822. brightOffsets[5] = -0.5 * sV;
  47823. brightOffsets[6] = 0.5 * sU;
  47824. brightOffsets[7] = -0.5 * sV;
  47825. effect.setArray2("dsOffsets", brightOffsets);
  47826. effect.setFloat("brightThreshold", _this.brightThreshold);
  47827. };
  47828. // Add to pipeline
  47829. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  47830. };
  47831. // Create gaussian blur H&V post-processes
  47832. StandardRenderingPipeline.prototype._createGaussianBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  47833. var _this = this;
  47834. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  47835. var blurOffsets = new Array(9);
  47836. var blurWeights = new Array(9);
  47837. var uniforms = ["blurOffsets", "blurWeights", "blurWidth"];
  47838. var callback = function (height) {
  47839. return function (effect) {
  47840. // Weights
  47841. var x = 0.0;
  47842. for (var i = 0; i < 9; i++) {
  47843. x = (i - 4.0) / 4.0;
  47844. blurWeights[i] =
  47845. _this.gaussianCoefficient
  47846. * (1.0 / Math.sqrt(2.0 * Math.PI * _this.gaussianStandardDeviation))
  47847. * Math.exp((-((x - _this.gaussianMean) * (x - _this.gaussianMean))) / (2.0 * _this.gaussianStandardDeviation * _this.gaussianStandardDeviation));
  47848. }
  47849. var lastOutputDimensions = {
  47850. width: scene.getEngine().getRenderWidth(),
  47851. height: scene.getEngine().getRenderHeight()
  47852. };
  47853. for (var i = 0; i < 9; i++) {
  47854. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  47855. blurOffsets[i] = value;
  47856. }
  47857. effect.setArray("blurOffsets", blurOffsets);
  47858. effect.setArray("blurWeights", blurWeights);
  47859. if (height) {
  47860. effect.setFloat("blurWidth", _this.horizontalBlur ? 1.0 : _this[blurWidthKey]);
  47861. }
  47862. else {
  47863. effect.setFloat("blurWidth", _this[blurWidthKey]);
  47864. }
  47865. };
  47866. };
  47867. // Create horizontal gaussian blur post-processes
  47868. 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);
  47869. gaussianBlurHPostProcess.onApply = callback(false);
  47870. // Create vertical gaussian blur post-process
  47871. 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);
  47872. gaussianBlurVPostProcess.onApply = callback(true);
  47873. // Add to pipeline
  47874. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH" + indice, function () { return gaussianBlurHPostProcess; }, true));
  47875. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV" + indice, function () { return gaussianBlurVPostProcess; }, true));
  47876. // Finish
  47877. this.gaussianBlurHPostProcesses.push(gaussianBlurHPostProcess);
  47878. this.gaussianBlurVPostProcesses.push(gaussianBlurVPostProcess);
  47879. };
  47880. // Create texture adder post-process
  47881. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  47882. var _this = this;
  47883. 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);
  47884. this.textureAdderPostProcess.onApply = function (effect) {
  47885. effect.setTextureFromPostProcess("otherSampler", _this.originalPostProcess);
  47886. effect.setTexture("lensSampler", _this.lensTexture);
  47887. effect.setFloat("exposure", _this.exposure);
  47888. };
  47889. // Add to pipeline
  47890. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  47891. };
  47892. // Create lens flare post-process
  47893. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  47894. var _this = this;
  47895. 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);
  47896. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  47897. this._createGaussianBlurPostProcesses(scene, ratio / 4, 4);
  47898. 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);
  47899. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  47900. var resolution = new BABYLON.Vector2(0, 0);
  47901. // Lens flare
  47902. this.lensFlarePostProcess.onApply = function (effect) {
  47903. effect.setTextureFromPostProcess("textureSampler", _this.gaussianBlurHPostProcesses[0]);
  47904. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  47905. effect.setFloat("strength", _this.lensFlareStrength);
  47906. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  47907. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  47908. // Shift
  47909. resolution.x = _this.lensFlarePostProcess.width;
  47910. resolution.y = _this.lensFlarePostProcess.height;
  47911. effect.setVector2("resolution", resolution);
  47912. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  47913. };
  47914. // Compose
  47915. 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);
  47916. 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);
  47917. this.lensFlareComposePostProcess.onApply = function (effect) {
  47918. effect.setTextureFromPostProcess("otherSampler", _this.textureAdderFinalPostProcess);
  47919. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  47920. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  47921. // Lens start rotation matrix
  47922. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  47923. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  47924. 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));
  47925. camRot *= 4.0;
  47926. 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);
  47927. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  47928. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  47929. };
  47930. };
  47931. // Create depth-of-field post-process
  47932. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  47933. var _this = this;
  47934. 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);
  47935. this.depthOfFieldPostProcess.onApply = function (effect) {
  47936. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  47937. effect.setTexture("depthSampler", _this._depthRenderer.getDepthMap());
  47938. effect.setFloat("distance", _this.depthOfFieldDistance);
  47939. };
  47940. // Add to pipeline
  47941. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  47942. };
  47943. // Dispose
  47944. StandardRenderingPipeline.prototype.dispose = function () {
  47945. for (var i = 0; i < this._cameras.length; i++) {
  47946. var camera = this._cameras[i];
  47947. this.originalPostProcess.dispose(camera);
  47948. this.downSampleX4PostProcess.dispose(camera);
  47949. this.brightPassPostProcess.dispose(camera);
  47950. this.textureAdderPostProcess.dispose(camera);
  47951. for (var j = 0; j < this.gaussianBlurHPostProcesses.length; j++) {
  47952. this.gaussianBlurHPostProcesses[j].dispose(camera);
  47953. }
  47954. for (var j = 0; j < this.gaussianBlurVPostProcesses.length; j++) {
  47955. this.gaussianBlurVPostProcesses[j].dispose(camera);
  47956. }
  47957. this.textureAdderFinalPostProcess.dispose(camera);
  47958. this.lensFlarePostProcess.dispose(camera);
  47959. this.lensFlareComposePostProcess.dispose(camera);
  47960. this.depthOfFieldPostProcess.dispose(camera);
  47961. }
  47962. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  47963. _super.prototype.dispose.call(this);
  47964. };
  47965. // Serialize rendering pipeline
  47966. StandardRenderingPipeline.prototype.serialize = function () {
  47967. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  47968. serializationObject.customType = "StandardRenderingPipeline";
  47969. return serializationObject;
  47970. };
  47971. // Parse serialized pipeline
  47972. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  47973. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  47974. };
  47975. return StandardRenderingPipeline;
  47976. }(BABYLON.PostProcessRenderPipeline));
  47977. __decorate([
  47978. BABYLON.serialize()
  47979. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  47980. __decorate([
  47981. BABYLON.serialize()
  47982. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  47983. __decorate([
  47984. BABYLON.serialize()
  47985. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  47986. __decorate([
  47987. BABYLON.serialize()
  47988. ], StandardRenderingPipeline.prototype, "gaussianCoefficient", void 0);
  47989. __decorate([
  47990. BABYLON.serialize()
  47991. ], StandardRenderingPipeline.prototype, "gaussianMean", void 0);
  47992. __decorate([
  47993. BABYLON.serialize()
  47994. ], StandardRenderingPipeline.prototype, "gaussianStandardDeviation", void 0);
  47995. __decorate([
  47996. BABYLON.serialize()
  47997. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  47998. __decorate([
  47999. BABYLON.serializeAsTexture("lensTexture")
  48000. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  48001. __decorate([
  48002. BABYLON.serializeAsTexture("lensColorTexture")
  48003. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  48004. __decorate([
  48005. BABYLON.serialize()
  48006. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  48007. __decorate([
  48008. BABYLON.serialize()
  48009. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  48010. __decorate([
  48011. BABYLON.serialize()
  48012. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  48013. __decorate([
  48014. BABYLON.serialize()
  48015. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  48016. __decorate([
  48017. BABYLON.serializeAsTexture("lensStarTexture")
  48018. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  48019. __decorate([
  48020. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  48021. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  48022. __decorate([
  48023. BABYLON.serialize()
  48024. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  48025. __decorate([
  48026. BABYLON.serialize()
  48027. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  48028. __decorate([
  48029. BABYLON.serialize()
  48030. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  48031. __decorate([
  48032. BABYLON.serialize()
  48033. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  48034. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  48035. })(BABYLON || (BABYLON = {}));
  48036. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  48037. var BABYLON;
  48038. (function (BABYLON) {
  48039. var BlurPostProcess = (function (_super) {
  48040. __extends(BlurPostProcess, _super);
  48041. function BlurPostProcess(name, direction, blurWidth, options, camera, samplingMode, engine, reusable) {
  48042. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  48043. var _this = _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  48044. _this.direction = direction;
  48045. _this.blurWidth = blurWidth;
  48046. _this.onApplyObservable.add(function (effect) {
  48047. effect.setFloat2("screenSize", _this.width, _this.height);
  48048. effect.setVector2("direction", _this.direction);
  48049. effect.setFloat("blurWidth", _this.blurWidth);
  48050. });
  48051. return _this;
  48052. }
  48053. return BlurPostProcess;
  48054. }(BABYLON.PostProcess));
  48055. BABYLON.BlurPostProcess = BlurPostProcess;
  48056. })(BABYLON || (BABYLON = {}));
  48057. //# sourceMappingURL=babylon.blurPostProcess.js.map
  48058. var BABYLON;
  48059. (function (BABYLON) {
  48060. var RefractionPostProcess = (function (_super) {
  48061. __extends(RefractionPostProcess, _super);
  48062. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  48063. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  48064. _this.color = color;
  48065. _this.depth = depth;
  48066. _this.colorLevel = colorLevel;
  48067. _this.onActivateObservable.add(function (cam) {
  48068. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  48069. });
  48070. _this.onApplyObservable.add(function (effect) {
  48071. effect.setColor3("baseColor", _this.color);
  48072. effect.setFloat("depth", _this.depth);
  48073. effect.setFloat("colorLevel", _this.colorLevel);
  48074. effect.setTexture("refractionSampler", _this._refRexture);
  48075. });
  48076. return _this;
  48077. }
  48078. // Methods
  48079. RefractionPostProcess.prototype.dispose = function (camera) {
  48080. if (this._refRexture) {
  48081. this._refRexture.dispose();
  48082. }
  48083. _super.prototype.dispose.call(this, camera);
  48084. };
  48085. return RefractionPostProcess;
  48086. }(BABYLON.PostProcess));
  48087. BABYLON.RefractionPostProcess = RefractionPostProcess;
  48088. })(BABYLON || (BABYLON = {}));
  48089. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  48090. var BABYLON;
  48091. (function (BABYLON) {
  48092. var BlackAndWhitePostProcess = (function (_super) {
  48093. __extends(BlackAndWhitePostProcess, _super);
  48094. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  48095. return _super.call(this, name, "blackAndWhite", null, null, options, camera, samplingMode, engine, reusable) || this;
  48096. }
  48097. return BlackAndWhitePostProcess;
  48098. }(BABYLON.PostProcess));
  48099. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  48100. })(BABYLON || (BABYLON = {}));
  48101. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  48102. var BABYLON;
  48103. (function (BABYLON) {
  48104. var ConvolutionPostProcess = (function (_super) {
  48105. __extends(ConvolutionPostProcess, _super);
  48106. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  48107. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  48108. _this.kernel = kernel;
  48109. _this.onApply = function (effect) {
  48110. effect.setFloat2("screenSize", _this.width, _this.height);
  48111. effect.setArray("kernel", _this.kernel);
  48112. };
  48113. return _this;
  48114. }
  48115. return ConvolutionPostProcess;
  48116. }(BABYLON.PostProcess));
  48117. // Statics
  48118. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  48119. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  48120. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  48121. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  48122. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  48123. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  48124. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  48125. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  48126. })(BABYLON || (BABYLON = {}));
  48127. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  48128. var BABYLON;
  48129. (function (BABYLON) {
  48130. var FilterPostProcess = (function (_super) {
  48131. __extends(FilterPostProcess, _super);
  48132. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  48133. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  48134. _this.kernelMatrix = kernelMatrix;
  48135. _this.onApply = function (effect) {
  48136. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  48137. };
  48138. return _this;
  48139. }
  48140. return FilterPostProcess;
  48141. }(BABYLON.PostProcess));
  48142. BABYLON.FilterPostProcess = FilterPostProcess;
  48143. })(BABYLON || (BABYLON = {}));
  48144. //# sourceMappingURL=babylon.filterPostProcess.js.map
  48145. var BABYLON;
  48146. (function (BABYLON) {
  48147. var FxaaPostProcess = (function (_super) {
  48148. __extends(FxaaPostProcess, _super);
  48149. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable) {
  48150. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable) || this;
  48151. _this.onSizeChangedObservable.add(function () {
  48152. _this.texelWidth = 1.0 / _this.width;
  48153. _this.texelHeight = 1.0 / _this.height;
  48154. });
  48155. _this.onApplyObservable.add(function (effect) {
  48156. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  48157. });
  48158. return _this;
  48159. }
  48160. return FxaaPostProcess;
  48161. }(BABYLON.PostProcess));
  48162. BABYLON.FxaaPostProcess = FxaaPostProcess;
  48163. })(BABYLON || (BABYLON = {}));
  48164. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  48165. var BABYLON;
  48166. (function (BABYLON) {
  48167. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  48168. var VolumetricLightScatteringPostProcess = (function (_super) {
  48169. __extends(VolumetricLightScatteringPostProcess, _super);
  48170. /**
  48171. * @constructor
  48172. * @param {string} name - The post-process name
  48173. * @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)
  48174. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  48175. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  48176. * @param {number} samples - The post-process quality, default 100
  48177. * @param {number} samplingMode - The post-process filtering mode
  48178. * @param {BABYLON.Engine} engine - The babylon engine
  48179. * @param {boolean} reusable - If the post-process is reusable
  48180. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  48181. */
  48182. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  48183. if (samples === void 0) { samples = 100; }
  48184. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  48185. 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;
  48186. _this._screenCoordinates = BABYLON.Vector2.Zero();
  48187. /**
  48188. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  48189. * @type {Vector3}
  48190. */
  48191. _this.customMeshPosition = BABYLON.Vector3.Zero();
  48192. /**
  48193. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  48194. * @type {boolean}
  48195. */
  48196. _this.useCustomMeshPosition = false;
  48197. /**
  48198. * If the post-process should inverse the light scattering direction
  48199. * @type {boolean}
  48200. */
  48201. _this.invert = true;
  48202. /**
  48203. * Array containing the excluded meshes not rendered in the internal pass
  48204. */
  48205. _this.excludedMeshes = new Array();
  48206. /**
  48207. * Controls the overall intensity of the post-process
  48208. * @type {number}
  48209. */
  48210. _this.exposure = 0.3;
  48211. /**
  48212. * Dissipates each sample's contribution in range [0, 1]
  48213. * @type {number}
  48214. */
  48215. _this.decay = 0.96815;
  48216. /**
  48217. * Controls the overall intensity of each sample
  48218. * @type {number}
  48219. */
  48220. _this.weight = 0.58767;
  48221. /**
  48222. * Controls the density of each sample
  48223. * @type {number}
  48224. */
  48225. _this.density = 0.926;
  48226. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  48227. var engine = scene.getEngine();
  48228. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  48229. // Configure mesh
  48230. _this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  48231. // Configure
  48232. _this._createPass(scene, ratio.passRatio || ratio);
  48233. _this.onActivate = function (camera) {
  48234. if (!_this.isSupported) {
  48235. _this.dispose(camera);
  48236. }
  48237. _this.onActivate = null;
  48238. };
  48239. _this.onApplyObservable.add(function (effect) {
  48240. _this._updateMeshScreenCoordinates(scene);
  48241. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  48242. effect.setFloat("exposure", _this.exposure);
  48243. effect.setFloat("decay", _this.decay);
  48244. effect.setFloat("weight", _this.weight);
  48245. effect.setFloat("density", _this.density);
  48246. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  48247. });
  48248. return _this;
  48249. }
  48250. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  48251. get: function () {
  48252. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  48253. return false;
  48254. },
  48255. set: function (useDiffuseColor) {
  48256. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  48257. },
  48258. enumerable: true,
  48259. configurable: true
  48260. });
  48261. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  48262. var mesh = subMesh.getMesh();
  48263. // Render this.mesh as default
  48264. if (mesh === this.mesh) {
  48265. return mesh.material.isReady(mesh);
  48266. }
  48267. var defines = [];
  48268. var attribs = [BABYLON.VertexBuffer.PositionKind];
  48269. var material = subMesh.getMaterial();
  48270. var needUV = false;
  48271. // Alpha test
  48272. if (material) {
  48273. if (material.needAlphaTesting()) {
  48274. defines.push("#define ALPHATEST");
  48275. }
  48276. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  48277. attribs.push(BABYLON.VertexBuffer.UVKind);
  48278. defines.push("#define UV1");
  48279. }
  48280. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  48281. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  48282. defines.push("#define UV2");
  48283. }
  48284. }
  48285. // Bones
  48286. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  48287. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  48288. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  48289. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  48290. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  48291. }
  48292. else {
  48293. defines.push("#define NUM_BONE_INFLUENCERS 0");
  48294. }
  48295. // Instances
  48296. if (useInstances) {
  48297. defines.push("#define INSTANCES");
  48298. attribs.push("world0");
  48299. attribs.push("world1");
  48300. attribs.push("world2");
  48301. attribs.push("world3");
  48302. }
  48303. // Get correct effect
  48304. var join = defines.join("\n");
  48305. if (this._cachedDefines !== join) {
  48306. this._cachedDefines = join;
  48307. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  48308. }
  48309. return this._volumetricLightScatteringPass.isReady();
  48310. };
  48311. /**
  48312. * Sets the new light position for light scattering effect
  48313. * @param {BABYLON.Vector3} The new custom light position
  48314. */
  48315. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  48316. this.customMeshPosition = position;
  48317. };
  48318. /**
  48319. * Returns the light position for light scattering effect
  48320. * @return {BABYLON.Vector3} The custom light position
  48321. */
  48322. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  48323. return this.customMeshPosition;
  48324. };
  48325. /**
  48326. * Disposes the internal assets and detaches the post-process from the camera
  48327. */
  48328. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  48329. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  48330. if (rttIndex !== -1) {
  48331. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  48332. }
  48333. this._volumetricLightScatteringRTT.dispose();
  48334. _super.prototype.dispose.call(this, camera);
  48335. };
  48336. /**
  48337. * Returns the render target texture used by the post-process
  48338. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  48339. */
  48340. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  48341. return this._volumetricLightScatteringRTT;
  48342. };
  48343. // Private methods
  48344. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  48345. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  48346. return true;
  48347. }
  48348. return false;
  48349. };
  48350. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  48351. var _this = this;
  48352. var engine = scene.getEngine();
  48353. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  48354. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48355. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48356. this._volumetricLightScatteringRTT.renderList = null;
  48357. this._volumetricLightScatteringRTT.renderParticles = false;
  48358. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  48359. // Custom render function for submeshes
  48360. var renderSubMesh = function (subMesh) {
  48361. var mesh = subMesh.getRenderingMesh();
  48362. if (_this._meshExcluded(mesh)) {
  48363. return;
  48364. }
  48365. var scene = mesh.getScene();
  48366. var engine = scene.getEngine();
  48367. // Culling
  48368. engine.setState(subMesh.getMaterial().backFaceCulling);
  48369. // Managing instances
  48370. var batch = mesh._getInstancesRenderList(subMesh._id);
  48371. if (batch.mustReturn) {
  48372. return;
  48373. }
  48374. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  48375. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  48376. var effect = _this._volumetricLightScatteringPass;
  48377. if (mesh === _this.mesh) {
  48378. if (subMesh.effect) {
  48379. effect = subMesh.effect;
  48380. }
  48381. else {
  48382. effect = subMesh.getMaterial().getEffect();
  48383. }
  48384. }
  48385. engine.enableEffect(effect);
  48386. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  48387. if (mesh === _this.mesh) {
  48388. subMesh.getMaterial().bind(mesh.getWorldMatrix(), mesh);
  48389. }
  48390. else {
  48391. var material = subMesh.getMaterial();
  48392. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  48393. // Alpha test
  48394. if (material && material.needAlphaTesting()) {
  48395. var alphaTexture = material.getAlphaTestTexture();
  48396. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  48397. if (alphaTexture) {
  48398. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  48399. }
  48400. }
  48401. // Bones
  48402. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  48403. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  48404. }
  48405. }
  48406. // Draw
  48407. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  48408. }
  48409. };
  48410. // Render target texture callbacks
  48411. var savedSceneClearColor;
  48412. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  48413. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  48414. savedSceneClearColor = scene.clearColor;
  48415. scene.clearColor = sceneClearColor;
  48416. });
  48417. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  48418. scene.clearColor = savedSceneClearColor;
  48419. });
  48420. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  48421. var engine = scene.getEngine();
  48422. var index;
  48423. for (index = 0; index < opaqueSubMeshes.length; index++) {
  48424. renderSubMesh(opaqueSubMeshes.data[index]);
  48425. }
  48426. engine.setAlphaTesting(true);
  48427. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  48428. renderSubMesh(alphaTestSubMeshes.data[index]);
  48429. }
  48430. engine.setAlphaTesting(false);
  48431. if (transparentSubMeshes.length) {
  48432. // Sort sub meshes
  48433. for (index = 0; index < transparentSubMeshes.length; index++) {
  48434. var submesh = transparentSubMeshes.data[index];
  48435. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  48436. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  48437. }
  48438. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  48439. sortedArray.sort(function (a, b) {
  48440. // Alpha index first
  48441. if (a._alphaIndex > b._alphaIndex) {
  48442. return 1;
  48443. }
  48444. if (a._alphaIndex < b._alphaIndex) {
  48445. return -1;
  48446. }
  48447. // Then distance to camera
  48448. if (a._distanceToCamera < b._distanceToCamera) {
  48449. return 1;
  48450. }
  48451. if (a._distanceToCamera > b._distanceToCamera) {
  48452. return -1;
  48453. }
  48454. return 0;
  48455. });
  48456. // Render sub meshes
  48457. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  48458. for (index = 0; index < sortedArray.length; index++) {
  48459. renderSubMesh(sortedArray[index]);
  48460. }
  48461. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  48462. }
  48463. };
  48464. };
  48465. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  48466. var transform = scene.getTransformMatrix();
  48467. var meshPosition;
  48468. if (this.useCustomMeshPosition) {
  48469. meshPosition = this.customMeshPosition;
  48470. }
  48471. else if (this.attachedNode) {
  48472. meshPosition = this.attachedNode.position;
  48473. }
  48474. else {
  48475. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  48476. }
  48477. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  48478. this._screenCoordinates.x = pos.x / this._viewPort.width;
  48479. this._screenCoordinates.y = pos.y / this._viewPort.height;
  48480. if (this.invert)
  48481. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  48482. };
  48483. // Static methods
  48484. /**
  48485. * Creates a default mesh for the Volumeric Light Scattering post-process
  48486. * @param {string} The mesh name
  48487. * @param {BABYLON.Scene} The scene where to create the mesh
  48488. * @return {BABYLON.Mesh} the default mesh
  48489. */
  48490. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  48491. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  48492. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  48493. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  48494. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  48495. mesh.material = material;
  48496. return mesh;
  48497. };
  48498. return VolumetricLightScatteringPostProcess;
  48499. }(BABYLON.PostProcess));
  48500. __decorate([
  48501. BABYLON.serializeAsVector3()
  48502. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  48503. __decorate([
  48504. BABYLON.serialize()
  48505. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  48506. __decorate([
  48507. BABYLON.serialize()
  48508. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  48509. __decorate([
  48510. BABYLON.serializeAsMeshReference()
  48511. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  48512. __decorate([
  48513. BABYLON.serialize()
  48514. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  48515. __decorate([
  48516. BABYLON.serialize()
  48517. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  48518. __decorate([
  48519. BABYLON.serialize()
  48520. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  48521. __decorate([
  48522. BABYLON.serialize()
  48523. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  48524. __decorate([
  48525. BABYLON.serialize()
  48526. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  48527. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  48528. })(BABYLON || (BABYLON = {}));
  48529. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  48530. //
  48531. // This post-process allows the modification of rendered colors by using
  48532. // a 'look-up table' (LUT). This effect is also called Color Grading.
  48533. //
  48534. // The object needs to be provided an url to a texture containing the color
  48535. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  48536. // Use an image editing software to tweak the LUT to match your needs.
  48537. //
  48538. // For an example of a color LUT, see here:
  48539. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  48540. // For explanations on color grading, see here:
  48541. // http://udn.epicgames.com/Three/ColorGrading.html
  48542. //
  48543. var BABYLON;
  48544. (function (BABYLON) {
  48545. var ColorCorrectionPostProcess = (function (_super) {
  48546. __extends(ColorCorrectionPostProcess, _super);
  48547. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  48548. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  48549. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  48550. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  48551. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48552. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48553. _this.onApply = function (effect) {
  48554. effect.setTexture("colorTable", _this._colorTableTexture);
  48555. };
  48556. return _this;
  48557. }
  48558. return ColorCorrectionPostProcess;
  48559. }(BABYLON.PostProcess));
  48560. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  48561. })(BABYLON || (BABYLON = {}));
  48562. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  48563. var BABYLON;
  48564. (function (BABYLON) {
  48565. var TonemappingOperator;
  48566. (function (TonemappingOperator) {
  48567. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  48568. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  48569. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  48570. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  48571. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  48572. ;
  48573. var TonemapPostProcess = (function (_super) {
  48574. __extends(TonemapPostProcess, _super);
  48575. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  48576. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  48577. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  48578. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat) || this;
  48579. _this._operator = _operator;
  48580. _this.exposureAdjustment = exposureAdjustment;
  48581. var defines = "#define ";
  48582. if (_this._operator === TonemappingOperator.Hable)
  48583. defines += "HABLE_TONEMAPPING";
  48584. else if (_this._operator === TonemappingOperator.Reinhard)
  48585. defines += "REINHARD_TONEMAPPING";
  48586. else if (_this._operator === TonemappingOperator.HejiDawson)
  48587. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  48588. else if (_this._operator === TonemappingOperator.Photographic)
  48589. defines += "PHOTOGRAPHIC_TONEMAPPING";
  48590. //sadly a second call to create the effect.
  48591. _this.updateEffect(defines);
  48592. _this.onApply = function (effect) {
  48593. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  48594. };
  48595. return _this;
  48596. }
  48597. return TonemapPostProcess;
  48598. }(BABYLON.PostProcess));
  48599. BABYLON.TonemapPostProcess = TonemapPostProcess;
  48600. })(BABYLON || (BABYLON = {}));
  48601. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  48602. var BABYLON;
  48603. (function (BABYLON) {
  48604. var DisplayPassPostProcess = (function (_super) {
  48605. __extends(DisplayPassPostProcess, _super);
  48606. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  48607. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  48608. }
  48609. return DisplayPassPostProcess;
  48610. }(BABYLON.PostProcess));
  48611. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  48612. })(BABYLON || (BABYLON = {}));
  48613. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  48614. /// <reference path="..\babylon.node.ts" />
  48615. var BABYLON;
  48616. (function (BABYLON) {
  48617. var Bone = (function (_super) {
  48618. __extends(Bone, _super);
  48619. function Bone(name, skeleton, parentBone, matrix, restPose) {
  48620. var _this = _super.call(this, name, skeleton.getScene()) || this;
  48621. _this.name = name;
  48622. _this.children = new Array();
  48623. _this.animations = new Array();
  48624. _this._worldTransform = new BABYLON.Matrix();
  48625. _this._absoluteTransform = new BABYLON.Matrix();
  48626. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  48627. _this._scaleMatrix = BABYLON.Matrix.Identity();
  48628. _this._scaleVector = new BABYLON.Vector3(1, 1, 1);
  48629. _this._negateScaleChildren = new BABYLON.Vector3(1, 1, 1);
  48630. _this._scalingDeterminant = 1;
  48631. _this._skeleton = skeleton;
  48632. _this._localMatrix = matrix;
  48633. _this._baseMatrix = matrix.clone();
  48634. _this._restPose = restPose ? restPose : matrix.clone();
  48635. skeleton.bones.push(_this);
  48636. if (parentBone) {
  48637. _this._parent = parentBone;
  48638. parentBone.children.push(_this);
  48639. }
  48640. else {
  48641. _this._parent = null;
  48642. }
  48643. _this._updateDifferenceMatrix();
  48644. if (_this.getAbsoluteTransform().determinant() < 0) {
  48645. _this._scalingDeterminant *= -1;
  48646. }
  48647. return _this;
  48648. }
  48649. Object.defineProperty(Bone.prototype, "_matrix", {
  48650. get: function () {
  48651. return this._localMatrix;
  48652. },
  48653. set: function (val) {
  48654. if (this._localMatrix) {
  48655. this._localMatrix.copyFrom(val);
  48656. }
  48657. else {
  48658. this._localMatrix = val;
  48659. }
  48660. },
  48661. enumerable: true,
  48662. configurable: true
  48663. });
  48664. // Members
  48665. Bone.prototype.getParent = function () {
  48666. return this._parent;
  48667. };
  48668. Bone.prototype.getLocalMatrix = function () {
  48669. return this._localMatrix;
  48670. };
  48671. Bone.prototype.getBaseMatrix = function () {
  48672. return this._baseMatrix;
  48673. };
  48674. Bone.prototype.getRestPose = function () {
  48675. return this._restPose;
  48676. };
  48677. Bone.prototype.returnToRest = function () {
  48678. this.updateMatrix(this._restPose.clone());
  48679. };
  48680. Bone.prototype.getWorldMatrix = function () {
  48681. return this._worldTransform;
  48682. };
  48683. Bone.prototype.getInvertedAbsoluteTransform = function () {
  48684. return this._invertedAbsoluteTransform;
  48685. };
  48686. Bone.prototype.getAbsoluteTransform = function () {
  48687. return this._absoluteTransform;
  48688. };
  48689. // Methods
  48690. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  48691. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  48692. this._baseMatrix = matrix.clone();
  48693. this._localMatrix = matrix.clone();
  48694. this._skeleton._markAsDirty();
  48695. if (updateDifferenceMatrix) {
  48696. this._updateDifferenceMatrix();
  48697. }
  48698. };
  48699. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  48700. if (!rootMatrix) {
  48701. rootMatrix = this._baseMatrix;
  48702. }
  48703. if (this._parent) {
  48704. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  48705. }
  48706. else {
  48707. this._absoluteTransform.copyFrom(rootMatrix);
  48708. }
  48709. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  48710. for (var index = 0; index < this.children.length; index++) {
  48711. this.children[index]._updateDifferenceMatrix();
  48712. }
  48713. };
  48714. Bone.prototype.markAsDirty = function () {
  48715. this._currentRenderId++;
  48716. this._skeleton._markAsDirty();
  48717. };
  48718. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  48719. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  48720. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  48721. // all animation may be coming from a library skeleton, so may need to create animation
  48722. if (this.animations.length === 0) {
  48723. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  48724. this.animations[0].setKeys([]);
  48725. }
  48726. // get animation info / verify there is such a range from the source bone
  48727. var sourceRange = source.animations[0].getRange(rangeName);
  48728. if (!sourceRange) {
  48729. return false;
  48730. }
  48731. var from = sourceRange.from;
  48732. var to = sourceRange.to;
  48733. var sourceKeys = source.animations[0].getKeys();
  48734. // rescaling prep
  48735. var sourceBoneLength = source.length;
  48736. var sourceParent = source.getParent();
  48737. var parent = this.getParent();
  48738. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  48739. var parentRatio = parentScalingReqd ? parent.length / sourceParent.length : null;
  48740. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  48741. var destKeys = this.animations[0].getKeys();
  48742. // loop vars declaration
  48743. var orig;
  48744. var origTranslation;
  48745. var mat;
  48746. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  48747. orig = sourceKeys[key];
  48748. if (orig.frame >= from && orig.frame <= to) {
  48749. if (rescaleAsRequired) {
  48750. mat = orig.value.clone();
  48751. // scale based on parent ratio, when bone has parent
  48752. if (parentScalingReqd) {
  48753. origTranslation = mat.getTranslation();
  48754. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  48755. // scale based on skeleton dimension ratio when root bone, and value is passed
  48756. }
  48757. else if (dimensionsScalingReqd) {
  48758. origTranslation = mat.getTranslation();
  48759. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  48760. // use original when root bone, and no data for skelDimensionsRatio
  48761. }
  48762. else {
  48763. mat = orig.value;
  48764. }
  48765. }
  48766. else {
  48767. mat = orig.value;
  48768. }
  48769. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  48770. }
  48771. }
  48772. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  48773. return true;
  48774. };
  48775. /**
  48776. * Translate the bone in local or world space.
  48777. * @param vec The amount to translate the bone.
  48778. * @param space The space that the translation is in.
  48779. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  48780. */
  48781. Bone.prototype.translate = function (vec, space, mesh) {
  48782. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  48783. var lm = this.getLocalMatrix();
  48784. if (space == BABYLON.Space.LOCAL) {
  48785. lm.m[12] += vec.x;
  48786. lm.m[13] += vec.y;
  48787. lm.m[14] += vec.z;
  48788. }
  48789. else {
  48790. var wm;
  48791. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  48792. if (mesh) {
  48793. wm = mesh.getWorldMatrix();
  48794. }
  48795. this._skeleton.computeAbsoluteTransforms();
  48796. var tmat = Bone._tmpMats[0];
  48797. var tvec = Bone._tmpVecs[0];
  48798. if (mesh) {
  48799. tmat.copyFrom(this._parent.getAbsoluteTransform());
  48800. tmat.multiplyToRef(wm, tmat);
  48801. }
  48802. else {
  48803. tmat.copyFrom(this._parent.getAbsoluteTransform());
  48804. }
  48805. tmat.m[12] = 0;
  48806. tmat.m[13] = 0;
  48807. tmat.m[14] = 0;
  48808. tmat.invert();
  48809. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  48810. lm.m[12] += tvec.x;
  48811. lm.m[13] += tvec.y;
  48812. lm.m[14] += tvec.z;
  48813. }
  48814. this.markAsDirty();
  48815. };
  48816. /**
  48817. * Set the postion of the bone in local or world space.
  48818. * @param position The position to set the bone.
  48819. * @param space The space that the position is in.
  48820. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  48821. */
  48822. Bone.prototype.setPosition = function (position, space, mesh) {
  48823. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  48824. var lm = this.getLocalMatrix();
  48825. if (space == BABYLON.Space.LOCAL) {
  48826. lm.m[12] = position.x;
  48827. lm.m[13] = position.y;
  48828. lm.m[14] = position.z;
  48829. }
  48830. else {
  48831. var wm;
  48832. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  48833. if (mesh) {
  48834. wm = mesh.getWorldMatrix();
  48835. }
  48836. this._skeleton.computeAbsoluteTransforms();
  48837. var tmat = Bone._tmpMats[0];
  48838. var vec = Bone._tmpVecs[0];
  48839. if (mesh) {
  48840. tmat.copyFrom(this._parent.getAbsoluteTransform());
  48841. tmat.multiplyToRef(wm, tmat);
  48842. }
  48843. else {
  48844. tmat.copyFrom(this._parent.getAbsoluteTransform());
  48845. }
  48846. tmat.invert();
  48847. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  48848. lm.m[12] = vec.x;
  48849. lm.m[13] = vec.y;
  48850. lm.m[14] = vec.z;
  48851. }
  48852. this.markAsDirty();
  48853. };
  48854. /**
  48855. * Set the absolute postion of the bone (world space).
  48856. * @param position The position to set the bone.
  48857. * @param mesh The mesh that this bone is attached to.
  48858. */
  48859. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  48860. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  48861. };
  48862. /**
  48863. * Set the scale of the bone on the x, y and z axes.
  48864. * @param x The scale of the bone on the x axis.
  48865. * @param x The scale of the bone on the y axis.
  48866. * @param z The scale of the bone on the z axis.
  48867. * @param scaleChildren Set this to true if children of the bone should be scaled.
  48868. */
  48869. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  48870. if (scaleChildren === void 0) { scaleChildren = false; }
  48871. if (this.animations[0] && !this.animations[0].isStopped()) {
  48872. if (!scaleChildren) {
  48873. this._negateScaleChildren.x = 1 / x;
  48874. this._negateScaleChildren.y = 1 / y;
  48875. this._negateScaleChildren.z = 1 / z;
  48876. }
  48877. this._syncScaleVector();
  48878. }
  48879. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  48880. };
  48881. /**
  48882. * Scale the bone on the x, y and z axes.
  48883. * @param x The amount to scale the bone on the x axis.
  48884. * @param x The amount to scale the bone on the y axis.
  48885. * @param z The amount to scale the bone on the z axis.
  48886. * @param scaleChildren Set this to true if children of the bone should be scaled.
  48887. */
  48888. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  48889. if (scaleChildren === void 0) { scaleChildren = false; }
  48890. var locMat = this.getLocalMatrix();
  48891. var origLocMat = Bone._tmpMats[0];
  48892. origLocMat.copyFrom(locMat);
  48893. var origLocMatInv = Bone._tmpMats[1];
  48894. origLocMatInv.copyFrom(origLocMat);
  48895. origLocMatInv.invert();
  48896. var scaleMat = Bone._tmpMats[2];
  48897. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  48898. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  48899. this._scaleVector.x *= x;
  48900. this._scaleVector.y *= y;
  48901. this._scaleVector.z *= z;
  48902. locMat.multiplyToRef(origLocMatInv, locMat);
  48903. locMat.multiplyToRef(scaleMat, locMat);
  48904. locMat.multiplyToRef(origLocMat, locMat);
  48905. var parent = this.getParent();
  48906. if (parent) {
  48907. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  48908. }
  48909. else {
  48910. this.getAbsoluteTransform().copyFrom(locMat);
  48911. }
  48912. var len = this.children.length;
  48913. scaleMat.invert();
  48914. for (var i = 0; i < len; i++) {
  48915. var child = this.children[i];
  48916. var cm = child.getLocalMatrix();
  48917. cm.multiplyToRef(scaleMat, cm);
  48918. var lm = child.getLocalMatrix();
  48919. lm.m[12] *= x;
  48920. lm.m[13] *= y;
  48921. lm.m[14] *= z;
  48922. }
  48923. this.computeAbsoluteTransforms();
  48924. if (scaleChildren) {
  48925. for (var i = 0; i < len; i++) {
  48926. this.children[i].scale(x, y, z, scaleChildren);
  48927. }
  48928. }
  48929. this.markAsDirty();
  48930. };
  48931. /**
  48932. * Set the yaw, pitch, and roll of the bone in local or world space.
  48933. * @param yaw The rotation of the bone on the y axis.
  48934. * @param pitch The rotation of the bone on the x axis.
  48935. * @param roll The rotation of the bone on the z axis.
  48936. * @param space The space that the axes of rotation are in.
  48937. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  48938. */
  48939. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  48940. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  48941. var rotMat = Bone._tmpMats[0];
  48942. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  48943. var rotMatInv = Bone._tmpMats[1];
  48944. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  48945. rotMatInv.multiplyToRef(rotMat, rotMat);
  48946. this._rotateWithMatrix(rotMat, space, mesh);
  48947. };
  48948. /**
  48949. * Rotate the bone on an axis in local or world space.
  48950. * @param axis The axis to rotate the bone on.
  48951. * @param amount The amount to rotate the bone.
  48952. * @param space The space that the axis is in.
  48953. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  48954. */
  48955. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  48956. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  48957. var rmat = Bone._tmpMats[0];
  48958. rmat.m[12] = 0;
  48959. rmat.m[13] = 0;
  48960. rmat.m[14] = 0;
  48961. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  48962. this._rotateWithMatrix(rmat, space, mesh);
  48963. };
  48964. /**
  48965. * Set the rotation of the bone to a particular axis angle in local or world space.
  48966. * @param axis The axis to rotate the bone on.
  48967. * @param angle The angle that the bone should be rotated to.
  48968. * @param space The space that the axis is in.
  48969. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  48970. */
  48971. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  48972. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  48973. var rotMat = Bone._tmpMats[0];
  48974. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  48975. var rotMatInv = Bone._tmpMats[1];
  48976. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  48977. rotMatInv.multiplyToRef(rotMat, rotMat);
  48978. this._rotateWithMatrix(rotMat, space, mesh);
  48979. };
  48980. /**
  48981. * Set the euler rotation of the bone in local of world space.
  48982. * @param rotation The euler rotation that the bone should be set to.
  48983. * @param space The space that the rotation is in.
  48984. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  48985. */
  48986. Bone.prototype.setRotation = function (rotation, space, mesh) {
  48987. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  48988. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  48989. };
  48990. /**
  48991. * Set the quaternion rotation of the bone in local of world space.
  48992. * @param quat The quaternion rotation that the bone should be set to.
  48993. * @param space The space that the rotation is in.
  48994. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  48995. */
  48996. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  48997. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  48998. var rotMatInv = Bone._tmpMats[0];
  48999. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  49000. var rotMat = Bone._tmpMats[1];
  49001. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  49002. rotMatInv.multiplyToRef(rotMat, rotMat);
  49003. this._rotateWithMatrix(rotMat, space, mesh);
  49004. };
  49005. /**
  49006. * Set the rotation matrix of the bone in local of world space.
  49007. * @param rotMat The rotation matrix that the bone should be set to.
  49008. * @param space The space that the rotation is in.
  49009. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  49010. */
  49011. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  49012. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  49013. var rotMatInv = Bone._tmpMats[0];
  49014. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  49015. var rotMat2 = Bone._tmpMats[1];
  49016. rotMat2.copyFrom(rotMat);
  49017. rotMatInv.multiplyToRef(rotMat, rotMat2);
  49018. this._rotateWithMatrix(rotMat2, space, mesh);
  49019. };
  49020. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  49021. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  49022. var lmat = this.getLocalMatrix();
  49023. var lx = lmat.m[12];
  49024. var ly = lmat.m[13];
  49025. var lz = lmat.m[14];
  49026. var parent = this.getParent();
  49027. var parentScale = Bone._tmpMats[3];
  49028. var parentScaleInv = Bone._tmpMats[4];
  49029. if (parent) {
  49030. if (space == BABYLON.Space.WORLD) {
  49031. if (mesh) {
  49032. parentScale.copyFrom(mesh.getWorldMatrix());
  49033. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  49034. }
  49035. else {
  49036. parentScale.copyFrom(parent.getAbsoluteTransform());
  49037. }
  49038. }
  49039. else {
  49040. parentScale = parent._scaleMatrix;
  49041. }
  49042. parentScaleInv.copyFrom(parentScale);
  49043. parentScaleInv.invert();
  49044. lmat.multiplyToRef(parentScale, lmat);
  49045. lmat.multiplyToRef(rmat, lmat);
  49046. lmat.multiplyToRef(parentScaleInv, lmat);
  49047. }
  49048. else {
  49049. if (space == BABYLON.Space.WORLD && mesh) {
  49050. parentScale.copyFrom(mesh.getWorldMatrix());
  49051. parentScaleInv.copyFrom(parentScale);
  49052. parentScaleInv.invert();
  49053. lmat.multiplyToRef(parentScale, lmat);
  49054. lmat.multiplyToRef(rmat, lmat);
  49055. lmat.multiplyToRef(parentScaleInv, lmat);
  49056. }
  49057. else {
  49058. lmat.multiplyToRef(rmat, lmat);
  49059. }
  49060. }
  49061. lmat.m[12] = lx;
  49062. lmat.m[13] = ly;
  49063. lmat.m[14] = lz;
  49064. this.computeAbsoluteTransforms();
  49065. this.markAsDirty();
  49066. };
  49067. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  49068. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  49069. if (space == BABYLON.Space.WORLD) {
  49070. var scaleMatrix = Bone._tmpMats[2];
  49071. scaleMatrix.copyFrom(this._scaleMatrix);
  49072. rotMatInv.copyFrom(this.getAbsoluteTransform());
  49073. if (mesh) {
  49074. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  49075. var meshScale = Bone._tmpMats[3];
  49076. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  49077. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  49078. }
  49079. rotMatInv.invert();
  49080. scaleMatrix.m[0] *= this._scalingDeterminant;
  49081. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  49082. }
  49083. else {
  49084. rotMatInv.copyFrom(this.getLocalMatrix());
  49085. rotMatInv.invert();
  49086. var scaleMatrix = Bone._tmpMats[2];
  49087. scaleMatrix.copyFrom(this._scaleMatrix);
  49088. if (this._parent) {
  49089. var pscaleMatrix = Bone._tmpMats[3];
  49090. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  49091. pscaleMatrix.invert();
  49092. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  49093. }
  49094. else {
  49095. scaleMatrix.m[0] *= this._scalingDeterminant;
  49096. }
  49097. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  49098. }
  49099. };
  49100. /**
  49101. * Get the scale of the bone
  49102. * @returns the scale of the bone
  49103. */
  49104. Bone.prototype.getScale = function () {
  49105. return this._scaleVector.clone();
  49106. };
  49107. /**
  49108. * Copy the scale of the bone to a vector3.
  49109. * @param result The vector3 to copy the scale to
  49110. */
  49111. Bone.prototype.getScaleToRef = function (result) {
  49112. result.copyFrom(this._scaleVector);
  49113. };
  49114. /**
  49115. * Get the position of the bone in local or world space.
  49116. * @param space The space that the returned position is in.
  49117. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  49118. * @returns The position of the bone
  49119. */
  49120. Bone.prototype.getPosition = function (space, mesh) {
  49121. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  49122. var pos = BABYLON.Vector3.Zero();
  49123. this.getPositionToRef(space, mesh, pos);
  49124. return pos;
  49125. };
  49126. /**
  49127. * Copy the position of the bone to a vector3 in local or world space.
  49128. * @param space The space that the returned position is in.
  49129. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  49130. * @param result The vector3 to copy the position to.
  49131. */
  49132. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  49133. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  49134. if (space == BABYLON.Space.LOCAL) {
  49135. var lm = this.getLocalMatrix();
  49136. result.x = lm.m[12];
  49137. result.y = lm.m[13];
  49138. result.z = lm.m[14];
  49139. }
  49140. else {
  49141. var wm;
  49142. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  49143. if (mesh) {
  49144. wm = mesh.getWorldMatrix();
  49145. }
  49146. this._skeleton.computeAbsoluteTransforms();
  49147. var tmat = Bone._tmpMats[0];
  49148. if (mesh) {
  49149. tmat.copyFrom(this.getAbsoluteTransform());
  49150. tmat.multiplyToRef(wm, tmat);
  49151. }
  49152. else {
  49153. tmat = this.getAbsoluteTransform();
  49154. }
  49155. result.x = tmat.m[12];
  49156. result.y = tmat.m[13];
  49157. result.z = tmat.m[14];
  49158. }
  49159. };
  49160. /**
  49161. * Get the absolute position of the bone (world space).
  49162. * @param mesh The mesh that this bone is attached to.
  49163. * @returns The absolute position of the bone
  49164. */
  49165. Bone.prototype.getAbsolutePosition = function (mesh) {
  49166. var pos = BABYLON.Vector3.Zero();
  49167. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  49168. return pos;
  49169. };
  49170. /**
  49171. * Copy the absolute position of the bone (world space) to the result param.
  49172. * @param mesh The mesh that this bone is attached to.
  49173. * @param result The vector3 to copy the absolute position to.
  49174. */
  49175. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  49176. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  49177. };
  49178. /**
  49179. * Compute the absolute transforms of this bone and its children.
  49180. */
  49181. Bone.prototype.computeAbsoluteTransforms = function () {
  49182. if (this._parent) {
  49183. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  49184. }
  49185. else {
  49186. this._absoluteTransform.copyFrom(this._localMatrix);
  49187. var poseMatrix = this._skeleton.getPoseMatrix();
  49188. if (poseMatrix) {
  49189. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  49190. }
  49191. }
  49192. var children = this.children;
  49193. var len = children.length;
  49194. for (var i = 0; i < len; i++) {
  49195. children[i].computeAbsoluteTransforms();
  49196. }
  49197. };
  49198. Bone.prototype._syncScaleVector = function () {
  49199. var lm = this.getLocalMatrix();
  49200. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  49201. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  49202. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  49203. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  49204. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  49205. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  49206. this._scaleVector.x = xs * Math.sqrt(xsq);
  49207. this._scaleVector.y = ys * Math.sqrt(ysq);
  49208. this._scaleVector.z = zs * Math.sqrt(zsq);
  49209. if (this._parent) {
  49210. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  49211. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  49212. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  49213. }
  49214. 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);
  49215. };
  49216. /**
  49217. * Get the world direction from an axis that is in the local space of the bone.
  49218. * @param localAxis The local direction that is used to compute the world direction.
  49219. * @param mesh The mesh that this bone is attached to.
  49220. * @returns The world direction
  49221. */
  49222. Bone.prototype.getDirection = function (localAxis, mesh) {
  49223. var result = BABYLON.Vector3.Zero();
  49224. this.getDirectionToRef(localAxis, mesh, result);
  49225. return result;
  49226. };
  49227. /**
  49228. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  49229. * @param localAxis The local direction that is used to compute the world direction.
  49230. * @param mesh The mesh that this bone is attached to.
  49231. * @param result The vector3 that the world direction will be copied to.
  49232. */
  49233. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  49234. var wm;
  49235. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  49236. if (mesh) {
  49237. wm = mesh.getWorldMatrix();
  49238. }
  49239. this._skeleton.computeAbsoluteTransforms();
  49240. var mat = Bone._tmpMats[0];
  49241. mat.copyFrom(this.getAbsoluteTransform());
  49242. if (mesh) {
  49243. mat.multiplyToRef(wm, mat);
  49244. }
  49245. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  49246. result.normalize();
  49247. };
  49248. /**
  49249. * Get the euler rotation of the bone in local or world space.
  49250. * @param space The space that the rotation should be in.
  49251. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  49252. * @returns The euler rotation
  49253. */
  49254. Bone.prototype.getRotation = function (space, mesh) {
  49255. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  49256. var result = BABYLON.Vector3.Zero();
  49257. this.getRotationToRef(space, mesh, result);
  49258. return result;
  49259. };
  49260. /**
  49261. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  49262. * @param space The space that the rotation should be in.
  49263. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  49264. * @param result The vector3 that the rotation should be copied to.
  49265. */
  49266. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  49267. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  49268. var quat = Bone._tmpQuat;
  49269. this.getRotationQuaternionToRef(space, mesh, quat);
  49270. quat.toEulerAnglesToRef(result);
  49271. };
  49272. /**
  49273. * Get the quaternion rotation of the bone in either local or world space.
  49274. * @param space The space that the rotation should be in.
  49275. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  49276. * @returns The quaternion rotation
  49277. */
  49278. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  49279. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  49280. var result = BABYLON.Quaternion.Identity();
  49281. this.getRotationQuaternionToRef(space, mesh, result);
  49282. return result;
  49283. };
  49284. /**
  49285. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  49286. * @param space The space that the rotation should be in.
  49287. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  49288. * @param result The quaternion that the rotation should be copied to.
  49289. */
  49290. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  49291. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  49292. if (space == BABYLON.Space.LOCAL) {
  49293. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  49294. }
  49295. else {
  49296. var mat = Bone._tmpMats[0];
  49297. var amat = this.getAbsoluteTransform();
  49298. if (mesh) {
  49299. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  49300. }
  49301. else {
  49302. mat.copyFrom(amat);
  49303. }
  49304. mat.m[0] *= this._scalingDeterminant;
  49305. mat.m[1] *= this._scalingDeterminant;
  49306. mat.m[2] *= this._scalingDeterminant;
  49307. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  49308. }
  49309. };
  49310. /**
  49311. * Get the rotation matrix of the bone in local or world space.
  49312. * @param space The space that the rotation should be in.
  49313. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  49314. * @returns The rotation matrix
  49315. */
  49316. Bone.prototype.getRotationMatrix = function (space, mesh) {
  49317. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  49318. var result = BABYLON.Matrix.Identity();
  49319. this.getRotationMatrixToRef(space, mesh, result);
  49320. return result;
  49321. };
  49322. /**
  49323. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  49324. * @param space The space that the rotation should be in.
  49325. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  49326. * @param result The quaternion that the rotation should be copied to.
  49327. */
  49328. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  49329. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  49330. if (space == BABYLON.Space.LOCAL) {
  49331. this.getLocalMatrix().getRotationMatrixToRef(result);
  49332. }
  49333. else {
  49334. var mat = Bone._tmpMats[0];
  49335. var amat = this.getAbsoluteTransform();
  49336. if (mesh) {
  49337. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  49338. }
  49339. else {
  49340. mat.copyFrom(amat);
  49341. }
  49342. mat.m[0] *= this._scalingDeterminant;
  49343. mat.m[1] *= this._scalingDeterminant;
  49344. mat.m[2] *= this._scalingDeterminant;
  49345. mat.getRotationMatrixToRef(result);
  49346. }
  49347. };
  49348. /**
  49349. * Get the world position of a point that is in the local space of the bone.
  49350. * @param position The local position
  49351. * @param mesh The mesh that this bone is attached to.
  49352. * @returns The world position
  49353. */
  49354. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  49355. var result = BABYLON.Vector3.Zero();
  49356. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  49357. return result;
  49358. };
  49359. /**
  49360. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  49361. * @param position The local position
  49362. * @param mesh The mesh that this bone is attached to.
  49363. * @param result The vector3 that the world position should be copied to.
  49364. */
  49365. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  49366. var wm;
  49367. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  49368. if (mesh) {
  49369. wm = mesh.getWorldMatrix();
  49370. }
  49371. this._skeleton.computeAbsoluteTransforms();
  49372. var tmat = Bone._tmpMats[0];
  49373. if (mesh) {
  49374. tmat.copyFrom(this.getAbsoluteTransform());
  49375. tmat.multiplyToRef(wm, tmat);
  49376. }
  49377. else {
  49378. tmat = this.getAbsoluteTransform();
  49379. }
  49380. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  49381. };
  49382. /**
  49383. * Get the local position of a point that is in world space.
  49384. * @param position The world position
  49385. * @param mesh The mesh that this bone is attached to.
  49386. * @returns The local position
  49387. */
  49388. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  49389. var result = BABYLON.Vector3.Zero();
  49390. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  49391. return result;
  49392. };
  49393. /**
  49394. * Get the local position of a point that is in world space and copy it to the result param.
  49395. * @param position The world position
  49396. * @param mesh The mesh that this bone is attached to.
  49397. * @param result The vector3 that the local position should be copied to.
  49398. */
  49399. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  49400. var wm;
  49401. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  49402. if (mesh) {
  49403. wm = mesh.getWorldMatrix();
  49404. }
  49405. this._skeleton.computeAbsoluteTransforms();
  49406. var tmat = Bone._tmpMats[0];
  49407. tmat.copyFrom(this.getAbsoluteTransform());
  49408. if (mesh) {
  49409. tmat.multiplyToRef(wm, tmat);
  49410. }
  49411. tmat.invert();
  49412. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  49413. };
  49414. return Bone;
  49415. }(BABYLON.Node));
  49416. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  49417. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  49418. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  49419. BABYLON.Bone = Bone;
  49420. })(BABYLON || (BABYLON = {}));
  49421. //# sourceMappingURL=babylon.bone.js.map
  49422. var BABYLON;
  49423. (function (BABYLON) {
  49424. var BoneIKController = (function () {
  49425. function BoneIKController(mesh, bone, options) {
  49426. this.targetPosition = BABYLON.Vector3.Zero();
  49427. this.poleTargetPosition = BABYLON.Vector3.Zero();
  49428. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  49429. this.poleAngle = 0;
  49430. this.slerpAmount = 1;
  49431. this._bone1Quat = BABYLON.Quaternion.Identity();
  49432. this._bone1Mat = BABYLON.Matrix.Identity();
  49433. this._bone2Ang = Math.PI;
  49434. this._maxAngle = Math.PI;
  49435. this._rightHandedSystem = false;
  49436. this._bendAxis = BABYLON.Vector3.Right();
  49437. this._slerping = false;
  49438. this._adjustRoll = 0;
  49439. this._bone2 = bone;
  49440. this._bone1 = bone.getParent();
  49441. this.mesh = mesh;
  49442. var bonePos = bone.getPosition();
  49443. if (bone.getAbsoluteTransform().determinant() > 0) {
  49444. this._rightHandedSystem = true;
  49445. this._bendAxis.x = 0;
  49446. this._bendAxis.y = 0;
  49447. this._bendAxis.z = -1;
  49448. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  49449. this._adjustRoll = Math.PI * .5;
  49450. this._bendAxis.z = 1;
  49451. }
  49452. }
  49453. if (this._bone1.length) {
  49454. var boneScale1 = this._bone1.getScale();
  49455. var boneScale2 = this._bone2.getScale();
  49456. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  49457. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  49458. }
  49459. else if (this._bone1.children[0]) {
  49460. mesh.computeWorldMatrix(true);
  49461. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  49462. var pos2 = this._bone2.getAbsolutePosition(mesh);
  49463. var pos3 = this._bone1.getAbsolutePosition(mesh);
  49464. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  49465. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  49466. }
  49467. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  49468. this.maxAngle = Math.PI;
  49469. if (options) {
  49470. if (options.targetMesh) {
  49471. this.targetMesh = options.targetMesh;
  49472. this.targetMesh.computeWorldMatrix(true);
  49473. }
  49474. if (options.poleTargetMesh) {
  49475. this.poleTargetMesh = options.poleTargetMesh;
  49476. this.poleTargetMesh.computeWorldMatrix(true);
  49477. }
  49478. else if (options.poleTargetBone) {
  49479. this.poleTargetBone = options.poleTargetBone;
  49480. }
  49481. else if (this._bone1.getParent()) {
  49482. this.poleTargetBone = this._bone1.getParent();
  49483. }
  49484. if (options.poleTargetLocalOffset) {
  49485. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  49486. }
  49487. if (options.poleAngle) {
  49488. this.poleAngle = options.poleAngle;
  49489. }
  49490. if (options.bendAxis) {
  49491. this._bendAxis.copyFrom(options.bendAxis);
  49492. }
  49493. if (options.maxAngle) {
  49494. this.maxAngle = options.maxAngle;
  49495. }
  49496. if (options.slerpAmount) {
  49497. this.slerpAmount = options.slerpAmount;
  49498. }
  49499. }
  49500. }
  49501. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  49502. get: function () {
  49503. return this._maxAngle;
  49504. },
  49505. set: function (value) {
  49506. this._setMaxAngle(value);
  49507. },
  49508. enumerable: true,
  49509. configurable: true
  49510. });
  49511. BoneIKController.prototype._setMaxAngle = function (ang) {
  49512. if (ang < 0) {
  49513. ang = 0;
  49514. }
  49515. if (ang > Math.PI || ang == undefined) {
  49516. ang = Math.PI;
  49517. }
  49518. this._maxAngle = ang;
  49519. var a = this._bone1Length;
  49520. var b = this._bone2Length;
  49521. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  49522. };
  49523. BoneIKController.prototype.update = function () {
  49524. var bone1 = this._bone1;
  49525. var target = this.targetPosition;
  49526. var poleTarget = this.poleTargetPosition;
  49527. var mat1 = BoneIKController._tmpMats[0];
  49528. var mat2 = BoneIKController._tmpMats[1];
  49529. if (this.targetMesh) {
  49530. target.copyFrom(this.targetMesh.getAbsolutePosition());
  49531. }
  49532. if (this.poleTargetBone) {
  49533. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  49534. }
  49535. else if (this.poleTargetMesh) {
  49536. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  49537. }
  49538. var bonePos = BoneIKController._tmpVecs[0];
  49539. var zaxis = BoneIKController._tmpVecs[1];
  49540. var xaxis = BoneIKController._tmpVecs[2];
  49541. var yaxis = BoneIKController._tmpVecs[3];
  49542. var upAxis = BoneIKController._tmpVecs[4];
  49543. var _tmpQuat = BoneIKController._tmpQuat;
  49544. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  49545. poleTarget.subtractToRef(bonePos, upAxis);
  49546. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  49547. upAxis.y = 1;
  49548. }
  49549. else {
  49550. upAxis.normalize();
  49551. }
  49552. target.subtractToRef(bonePos, yaxis);
  49553. yaxis.normalize();
  49554. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  49555. zaxis.normalize();
  49556. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  49557. xaxis.normalize();
  49558. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  49559. var a = this._bone1Length;
  49560. var b = this._bone2Length;
  49561. var c = BABYLON.Vector3.Distance(bonePos, target);
  49562. if (this._maxReach > 0) {
  49563. c = Math.min(this._maxReach, c);
  49564. }
  49565. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  49566. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  49567. if (acosa > 1) {
  49568. acosa = 1;
  49569. }
  49570. if (acosb > 1) {
  49571. acosb = 1;
  49572. }
  49573. if (acosa < -1) {
  49574. acosa = -1;
  49575. }
  49576. if (acosb < -1) {
  49577. acosb = -1;
  49578. }
  49579. var angA = Math.acos(acosa);
  49580. var angB = Math.acos(acosb);
  49581. var angC = -angA - angB;
  49582. if (this._rightHandedSystem) {
  49583. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  49584. mat2.multiplyToRef(mat1, mat1);
  49585. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  49586. mat2.multiplyToRef(mat1, mat1);
  49587. }
  49588. else {
  49589. var _tmpVec = BoneIKController._tmpVecs[5];
  49590. _tmpVec.copyFrom(this._bendAxis);
  49591. _tmpVec.x *= -1;
  49592. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  49593. mat2.multiplyToRef(mat1, mat1);
  49594. }
  49595. if (this.poleAngle) {
  49596. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  49597. mat1.multiplyToRef(mat2, mat1);
  49598. }
  49599. if (this.slerpAmount < 1) {
  49600. if (!this._slerping) {
  49601. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  49602. }
  49603. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  49604. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  49605. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  49606. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  49607. this._slerping = true;
  49608. }
  49609. else {
  49610. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  49611. this._bone1Mat.copyFrom(mat1);
  49612. this._slerping = false;
  49613. }
  49614. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  49615. this._bone2Ang = angC;
  49616. };
  49617. return BoneIKController;
  49618. }());
  49619. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  49620. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  49621. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  49622. BABYLON.BoneIKController = BoneIKController;
  49623. })(BABYLON || (BABYLON = {}));
  49624. //# sourceMappingURL=babylon.boneIKController.js.map
  49625. var BABYLON;
  49626. (function (BABYLON) {
  49627. var BoneLookController = (function () {
  49628. /**
  49629. * Create a BoneLookController
  49630. * @param mesh the mesh that the bone belongs to
  49631. * @param bone the bone that will be looking to the target
  49632. * @param target the target Vector3 to look at
  49633. * @param settings optional settings:
  49634. * - maxYaw: the maximum angle the bone will yaw to
  49635. * - minYaw: the minimum angle the bone will yaw to
  49636. * - maxPitch: the maximum angle the bone will pitch to
  49637. * - minPitch: the minimum angle the bone will yaw to
  49638. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  49639. * - upAxis: the up axis of the coordinate system
  49640. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  49641. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  49642. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  49643. * - adjustYaw: used to make an adjustment to the yaw of the bone
  49644. * - adjustPitch: used to make an adjustment to the pitch of the bone
  49645. * - adjustRoll: used to make an adjustment to the roll of the bone
  49646. **/
  49647. function BoneLookController(mesh, bone, target, options) {
  49648. /**
  49649. * The up axis of the coordinate system that is used when the bone is rotated.
  49650. */
  49651. this.upAxis = BABYLON.Vector3.Up();
  49652. /**
  49653. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  49654. */
  49655. this.upAxisSpace = BABYLON.Space.LOCAL;
  49656. /**
  49657. * Used to make an adjustment to the yaw of the bone.
  49658. */
  49659. this.adjustYaw = 0;
  49660. /**
  49661. * Used to make an adjustment to the pitch of the bone.
  49662. */
  49663. this.adjustPitch = 0;
  49664. /**
  49665. * Used to make an adjustment to the roll of the bone.
  49666. */
  49667. this.adjustRoll = 0;
  49668. /**
  49669. * 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).
  49670. */
  49671. this.slerpAmount = 1;
  49672. this._boneQuat = BABYLON.Quaternion.Identity();
  49673. this._slerping = false;
  49674. this._firstFrameSkipped = false;
  49675. this._fowardAxis = BABYLON.Vector3.Forward();
  49676. this.mesh = mesh;
  49677. this.bone = bone;
  49678. this.target = target;
  49679. if (options) {
  49680. if (options.adjustYaw) {
  49681. this.adjustYaw = options.adjustYaw;
  49682. }
  49683. if (options.adjustPitch) {
  49684. this.adjustPitch = options.adjustPitch;
  49685. }
  49686. if (options.adjustRoll) {
  49687. this.adjustRoll = options.adjustRoll;
  49688. }
  49689. if (options.maxYaw != null) {
  49690. this.maxYaw = options.maxYaw;
  49691. }
  49692. else {
  49693. this.maxYaw = Math.PI;
  49694. }
  49695. if (options.minYaw != null) {
  49696. this.minYaw = options.minYaw;
  49697. }
  49698. else {
  49699. this.minYaw = -Math.PI;
  49700. }
  49701. if (options.maxPitch != null) {
  49702. this.maxPitch = options.maxPitch;
  49703. }
  49704. else {
  49705. this.maxPitch = Math.PI;
  49706. }
  49707. if (options.minPitch != null) {
  49708. this.minPitch = options.minPitch;
  49709. }
  49710. else {
  49711. this.minPitch = -Math.PI;
  49712. }
  49713. if (options.slerpAmount != null) {
  49714. this.slerpAmount = options.slerpAmount;
  49715. }
  49716. if (options.upAxis != null) {
  49717. this.upAxis = options.upAxis;
  49718. }
  49719. if (options.upAxisSpace != null) {
  49720. this.upAxisSpace = options.upAxisSpace;
  49721. }
  49722. if (options.yawAxis != null || options.pitchAxis != null) {
  49723. var newYawAxis = BABYLON.Axis.Y;
  49724. var newPitchAxis = BABYLON.Axis.X;
  49725. if (options.yawAxis != null) {
  49726. newYawAxis = options.yawAxis.clone();
  49727. newYawAxis.normalize();
  49728. }
  49729. if (options.pitchAxis != null) {
  49730. newPitchAxis = options.pitchAxis.clone();
  49731. newPitchAxis.normalize();
  49732. }
  49733. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  49734. this._transformYawPitch = BABYLON.Matrix.Identity();
  49735. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  49736. this._transformYawPitchInv = this._transformYawPitch.clone();
  49737. this._transformYawPitch.invert();
  49738. }
  49739. }
  49740. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  49741. this.upAxisSpace = BABYLON.Space.LOCAL;
  49742. }
  49743. }
  49744. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  49745. /**
  49746. * Get/set the minimum yaw angle that the bone can look to.
  49747. */
  49748. get: function () {
  49749. return this._minYaw;
  49750. },
  49751. set: function (value) {
  49752. this._minYaw = value;
  49753. this._minYawSin = Math.sin(value);
  49754. this._minYawCos = Math.cos(value);
  49755. if (this._maxYaw != null) {
  49756. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  49757. this._yawRange = this._maxYaw - this._minYaw;
  49758. }
  49759. },
  49760. enumerable: true,
  49761. configurable: true
  49762. });
  49763. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  49764. /**
  49765. * Get/set the maximum yaw angle that the bone can look to.
  49766. */
  49767. get: function () {
  49768. return this._maxYaw;
  49769. },
  49770. set: function (value) {
  49771. this._maxYaw = value;
  49772. this._maxYawSin = Math.sin(value);
  49773. this._maxYawCos = Math.cos(value);
  49774. if (this._minYaw != null) {
  49775. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  49776. this._yawRange = this._maxYaw - this._minYaw;
  49777. }
  49778. },
  49779. enumerable: true,
  49780. configurable: true
  49781. });
  49782. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  49783. /**
  49784. * Get/set the minimum pitch angle that the bone can look to.
  49785. */
  49786. get: function () {
  49787. return this._minPitch;
  49788. },
  49789. set: function (value) {
  49790. this._minPitch = value;
  49791. this._minPitchTan = Math.tan(value);
  49792. },
  49793. enumerable: true,
  49794. configurable: true
  49795. });
  49796. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  49797. /**
  49798. * Get/set the maximum pitch angle that the bone can look to.
  49799. */
  49800. get: function () {
  49801. return this._maxPitch;
  49802. },
  49803. set: function (value) {
  49804. this._maxPitch = value;
  49805. this._maxPitchTan = Math.tan(value);
  49806. },
  49807. enumerable: true,
  49808. configurable: true
  49809. });
  49810. /**
  49811. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  49812. */
  49813. BoneLookController.prototype.update = function () {
  49814. //skip the first frame when slerping so that the mesh rotation is correct
  49815. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  49816. this._firstFrameSkipped = true;
  49817. return;
  49818. }
  49819. var bone = this.bone;
  49820. var bonePos = BoneLookController._tmpVecs[0];
  49821. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  49822. var target = this.target;
  49823. var _tmpMat1 = BoneLookController._tmpMats[0];
  49824. var _tmpMat2 = BoneLookController._tmpMats[1];
  49825. var mesh = this.mesh;
  49826. var parentBone = bone.getParent();
  49827. var upAxis = BoneLookController._tmpVecs[1];
  49828. upAxis.copyFrom(this.upAxis);
  49829. if (this.upAxisSpace == BABYLON.Space.BONE) {
  49830. if (this._transformYawPitch) {
  49831. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  49832. }
  49833. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  49834. }
  49835. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  49836. mesh.getDirectionToRef(upAxis, upAxis);
  49837. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  49838. upAxis.normalize();
  49839. }
  49840. }
  49841. var checkYaw = false;
  49842. var checkPitch = false;
  49843. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  49844. checkYaw = true;
  49845. }
  49846. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  49847. checkPitch = true;
  49848. }
  49849. if (checkYaw || checkPitch) {
  49850. var spaceMat = BoneLookController._tmpMats[2];
  49851. var spaceMatInv = BoneLookController._tmpMats[3];
  49852. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1) {
  49853. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  49854. }
  49855. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  49856. spaceMat.copyFrom(mesh.getWorldMatrix());
  49857. }
  49858. else {
  49859. var forwardAxis = BoneLookController._tmpVecs[2];
  49860. forwardAxis.copyFrom(this._fowardAxis);
  49861. if (this._transformYawPitch) {
  49862. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  49863. }
  49864. if (parentBone) {
  49865. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  49866. }
  49867. else {
  49868. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  49869. }
  49870. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  49871. rightAxis.normalize();
  49872. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  49873. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  49874. }
  49875. spaceMat.invertToRef(spaceMatInv);
  49876. var xzlen;
  49877. if (checkPitch) {
  49878. var localTarget = BoneLookController._tmpVecs[3];
  49879. target.subtractToRef(bonePos, localTarget);
  49880. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  49881. var xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  49882. var pitch = Math.atan2(localTarget.y, xzlen);
  49883. var newPitch = pitch;
  49884. if (pitch > this._maxPitch) {
  49885. localTarget.y = this._maxPitchTan * xzlen;
  49886. newPitch = this._maxPitch;
  49887. }
  49888. else if (pitch < this._minPitch) {
  49889. localTarget.y = this._minPitchTan * xzlen;
  49890. newPitch = this._minPitch;
  49891. }
  49892. if (pitch != newPitch) {
  49893. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  49894. localTarget.addInPlace(bonePos);
  49895. target = localTarget;
  49896. }
  49897. }
  49898. if (checkYaw) {
  49899. var localTarget = BoneLookController._tmpVecs[4];
  49900. target.subtractToRef(bonePos, localTarget);
  49901. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  49902. var yaw = Math.atan2(localTarget.x, localTarget.z);
  49903. var newYaw = yaw;
  49904. if (yaw > this._maxYaw || yaw < this._minYaw) {
  49905. if (xzlen == null) {
  49906. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  49907. }
  49908. if (this._yawRange > Math.PI) {
  49909. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  49910. localTarget.z = this._maxYawCos * xzlen;
  49911. localTarget.x = this._maxYawSin * xzlen;
  49912. newYaw = this._maxYaw;
  49913. }
  49914. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  49915. localTarget.z = this._minYawCos * xzlen;
  49916. localTarget.x = this._minYawSin * xzlen;
  49917. newYaw = this._minYaw;
  49918. }
  49919. }
  49920. else {
  49921. if (yaw > this._maxYaw) {
  49922. localTarget.z = this._maxYawCos * xzlen;
  49923. localTarget.x = this._maxYawSin * xzlen;
  49924. newYaw = this._maxYaw;
  49925. }
  49926. else if (yaw < this._minYaw) {
  49927. localTarget.z = this._minYawCos * xzlen;
  49928. localTarget.x = this._minYawSin * xzlen;
  49929. newYaw = this._minYaw;
  49930. }
  49931. }
  49932. }
  49933. if (this._slerping && this._yawRange > Math.PI) {
  49934. //are we going to be crossing into the min/max region?
  49935. var boneFwd = BoneLookController._tmpVecs[8];
  49936. boneFwd.copyFrom(BABYLON.Axis.Z);
  49937. if (this._transformYawPitch) {
  49938. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  49939. }
  49940. var boneRotMat = BABYLON.BoneLookController._tmpMats[4];
  49941. this._boneQuat.toRotationMatrix(boneRotMat);
  49942. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  49943. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  49944. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  49945. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  49946. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  49947. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  49948. if (angBtwTar > angBtwMidYaw) {
  49949. if (xzlen == null) {
  49950. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  49951. }
  49952. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  49953. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  49954. if (angBtwMin < angBtwMax) {
  49955. newYaw = boneYaw + Math.PI * .75;
  49956. localTarget.z = Math.cos(newYaw) * xzlen;
  49957. localTarget.x = Math.sin(newYaw) * xzlen;
  49958. }
  49959. else {
  49960. newYaw = boneYaw - Math.PI * .75;
  49961. localTarget.z = Math.cos(newYaw) * xzlen;
  49962. localTarget.x = Math.sin(newYaw) * xzlen;
  49963. }
  49964. }
  49965. }
  49966. if (yaw != newYaw) {
  49967. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  49968. localTarget.addInPlace(bonePos);
  49969. target = localTarget;
  49970. }
  49971. }
  49972. }
  49973. var zaxis = BoneLookController._tmpVecs[5];
  49974. var xaxis = BoneLookController._tmpVecs[6];
  49975. var yaxis = BoneLookController._tmpVecs[7];
  49976. var _tmpQuat = BoneLookController._tmpQuat;
  49977. target.subtractToRef(bonePos, zaxis);
  49978. zaxis.normalize();
  49979. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  49980. xaxis.normalize();
  49981. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  49982. yaxis.normalize();
  49983. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  49984. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  49985. return;
  49986. }
  49987. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  49988. return;
  49989. }
  49990. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  49991. return;
  49992. }
  49993. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  49994. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  49995. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  49996. }
  49997. if (this.slerpAmount < 1) {
  49998. if (!this._slerping) {
  49999. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  50000. }
  50001. if (this._transformYawPitch) {
  50002. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  50003. }
  50004. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  50005. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  50006. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  50007. this._slerping = true;
  50008. }
  50009. else {
  50010. if (this._transformYawPitch) {
  50011. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  50012. }
  50013. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  50014. this._slerping = false;
  50015. }
  50016. };
  50017. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  50018. var angDiff = ang2 - ang1;
  50019. angDiff %= Math.PI * 2;
  50020. if (angDiff > Math.PI) {
  50021. angDiff -= Math.PI * 2;
  50022. }
  50023. else if (angDiff < -Math.PI) {
  50024. angDiff += Math.PI * 2;
  50025. }
  50026. return angDiff;
  50027. };
  50028. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  50029. ang1 %= (2 * Math.PI);
  50030. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  50031. ang2 %= (2 * Math.PI);
  50032. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  50033. var ab = 0;
  50034. if (ang1 < ang2) {
  50035. ab = ang2 - ang1;
  50036. }
  50037. else {
  50038. ab = ang1 - ang2;
  50039. }
  50040. if (ab > Math.PI) {
  50041. ab = Math.PI * 2 - ab;
  50042. }
  50043. return ab;
  50044. };
  50045. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  50046. ang %= (2 * Math.PI);
  50047. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  50048. ang1 %= (2 * Math.PI);
  50049. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  50050. ang2 %= (2 * Math.PI);
  50051. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  50052. if (ang1 < ang2) {
  50053. if (ang > ang1 && ang < ang2) {
  50054. return true;
  50055. }
  50056. }
  50057. else {
  50058. if (ang > ang2 && ang < ang1) {
  50059. return true;
  50060. }
  50061. }
  50062. return false;
  50063. };
  50064. return BoneLookController;
  50065. }());
  50066. 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()];
  50067. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  50068. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  50069. BABYLON.BoneLookController = BoneLookController;
  50070. })(BABYLON || (BABYLON = {}));
  50071. //# sourceMappingURL=babylon.boneLookController.js.map
  50072. var BABYLON;
  50073. (function (BABYLON) {
  50074. var Skeleton = (function () {
  50075. function Skeleton(name, id, scene) {
  50076. this.name = name;
  50077. this.id = id;
  50078. this.bones = new Array();
  50079. this.needInitialSkinMatrix = false;
  50080. this._isDirty = true;
  50081. this._meshesWithPoseMatrix = new Array();
  50082. this._identity = BABYLON.Matrix.Identity();
  50083. this._ranges = {};
  50084. this._lastAbsoluteTransformsUpdateId = -1;
  50085. // Events
  50086. /**
  50087. * An event triggered before computing the skeleton's matrices
  50088. * @type {BABYLON.Observable}
  50089. */
  50090. this.onBeforeComputeObservable = new BABYLON.Observable();
  50091. this.bones = [];
  50092. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  50093. scene.skeletons.push(this);
  50094. //make sure it will recalculate the matrix next time prepare is called.
  50095. this._isDirty = true;
  50096. }
  50097. // Members
  50098. Skeleton.prototype.getTransformMatrices = function (mesh) {
  50099. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  50100. return mesh._bonesTransformMatrices;
  50101. }
  50102. if (!this._transformMatrices) {
  50103. this.prepare();
  50104. }
  50105. return this._transformMatrices;
  50106. };
  50107. Skeleton.prototype.getScene = function () {
  50108. return this._scene;
  50109. };
  50110. // Methods
  50111. /**
  50112. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  50113. */
  50114. Skeleton.prototype.toString = function (fullDetails) {
  50115. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  50116. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  50117. if (fullDetails) {
  50118. ret += ", Ranges: {";
  50119. var first = true;
  50120. for (var name_1 in this._ranges) {
  50121. if (first) {
  50122. ret += ", ";
  50123. first = false;
  50124. }
  50125. ret += name_1;
  50126. }
  50127. ret += "}";
  50128. }
  50129. return ret;
  50130. };
  50131. /**
  50132. * Get bone's index searching by name
  50133. * @param {string} name is bone's name to search for
  50134. * @return {number} Indice of the bone. Returns -1 if not found
  50135. */
  50136. Skeleton.prototype.getBoneIndexByName = function (name) {
  50137. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  50138. if (this.bones[boneIndex].name === name) {
  50139. return boneIndex;
  50140. }
  50141. }
  50142. return -1;
  50143. };
  50144. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  50145. // check name not already in use
  50146. if (!this._ranges[name]) {
  50147. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  50148. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  50149. if (this.bones[i].animations[0]) {
  50150. this.bones[i].animations[0].createRange(name, from, to);
  50151. }
  50152. }
  50153. }
  50154. };
  50155. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  50156. if (deleteFrames === void 0) { deleteFrames = true; }
  50157. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  50158. if (this.bones[i].animations[0]) {
  50159. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  50160. }
  50161. }
  50162. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  50163. };
  50164. Skeleton.prototype.getAnimationRange = function (name) {
  50165. return this._ranges[name];
  50166. };
  50167. /**
  50168. * Returns as an Array, all AnimationRanges defined on this skeleton
  50169. */
  50170. Skeleton.prototype.getAnimationRanges = function () {
  50171. var animationRanges = [];
  50172. var name;
  50173. var i = 0;
  50174. for (name in this._ranges) {
  50175. animationRanges[i] = this._ranges[name];
  50176. i++;
  50177. }
  50178. return animationRanges;
  50179. };
  50180. /**
  50181. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  50182. */
  50183. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  50184. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  50185. if (this._ranges[name] || !source.getAnimationRange(name)) {
  50186. return false;
  50187. }
  50188. var ret = true;
  50189. var frameOffset = this._getHighestAnimationFrame() + 1;
  50190. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  50191. var boneDict = {};
  50192. var sourceBones = source.bones;
  50193. var nBones;
  50194. var i;
  50195. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  50196. boneDict[sourceBones[i].name] = sourceBones[i];
  50197. }
  50198. if (this.bones.length !== sourceBones.length) {
  50199. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  50200. ret = false;
  50201. }
  50202. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  50203. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  50204. var boneName = this.bones[i].name;
  50205. var sourceBone = boneDict[boneName];
  50206. if (sourceBone) {
  50207. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  50208. }
  50209. else {
  50210. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  50211. ret = false;
  50212. }
  50213. }
  50214. // do not call createAnimationRange(), since it also is done to bones, which was already done
  50215. var range = source.getAnimationRange(name);
  50216. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  50217. return ret;
  50218. };
  50219. Skeleton.prototype.returnToRest = function () {
  50220. for (var index = 0; index < this.bones.length; index++) {
  50221. this.bones[index].returnToRest();
  50222. }
  50223. };
  50224. Skeleton.prototype._getHighestAnimationFrame = function () {
  50225. var ret = 0;
  50226. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  50227. if (this.bones[i].animations[0]) {
  50228. var highest = this.bones[i].animations[0].getHighestFrame();
  50229. if (ret < highest) {
  50230. ret = highest;
  50231. }
  50232. }
  50233. }
  50234. return ret;
  50235. };
  50236. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  50237. var range = this.getAnimationRange(name);
  50238. if (!range) {
  50239. return null;
  50240. }
  50241. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  50242. };
  50243. Skeleton.prototype._markAsDirty = function () {
  50244. this._isDirty = true;
  50245. };
  50246. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  50247. this._meshesWithPoseMatrix.push(mesh);
  50248. };
  50249. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  50250. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  50251. if (index > -1) {
  50252. this._meshesWithPoseMatrix.splice(index, 1);
  50253. }
  50254. };
  50255. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  50256. this.onBeforeComputeObservable.notifyObservers(this);
  50257. for (var index = 0; index < this.bones.length; index++) {
  50258. var bone = this.bones[index];
  50259. var parentBone = bone.getParent();
  50260. if (parentBone) {
  50261. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  50262. }
  50263. else {
  50264. if (initialSkinMatrix) {
  50265. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  50266. }
  50267. else {
  50268. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  50269. }
  50270. }
  50271. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
  50272. }
  50273. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  50274. };
  50275. Skeleton.prototype.prepare = function () {
  50276. if (!this._isDirty) {
  50277. return;
  50278. }
  50279. if (this.needInitialSkinMatrix) {
  50280. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  50281. var mesh = this._meshesWithPoseMatrix[index];
  50282. var poseMatrix = mesh.getPoseMatrix();
  50283. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  50284. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  50285. }
  50286. if (this._synchronizedWithMesh !== mesh) {
  50287. this._synchronizedWithMesh = mesh;
  50288. // Prepare bones
  50289. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  50290. var bone = this.bones[boneIndex];
  50291. if (!bone.getParent()) {
  50292. var matrix = bone.getBaseMatrix();
  50293. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  50294. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  50295. }
  50296. }
  50297. }
  50298. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  50299. }
  50300. }
  50301. else {
  50302. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  50303. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  50304. }
  50305. this._computeTransformMatrices(this._transformMatrices, null);
  50306. }
  50307. this._isDirty = false;
  50308. this._scene._activeBones.addCount(this.bones.length, false);
  50309. };
  50310. Skeleton.prototype.getAnimatables = function () {
  50311. if (!this._animatables || this._animatables.length !== this.bones.length) {
  50312. this._animatables = [];
  50313. for (var index = 0; index < this.bones.length; index++) {
  50314. this._animatables.push(this.bones[index]);
  50315. }
  50316. }
  50317. return this._animatables;
  50318. };
  50319. Skeleton.prototype.clone = function (name, id) {
  50320. var result = new Skeleton(name, id || name, this._scene);
  50321. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  50322. for (var index = 0; index < this.bones.length; index++) {
  50323. var source = this.bones[index];
  50324. var parentBone = null;
  50325. if (source.getParent()) {
  50326. var parentIndex = this.bones.indexOf(source.getParent());
  50327. parentBone = result.bones[parentIndex];
  50328. }
  50329. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  50330. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  50331. }
  50332. if (this._ranges) {
  50333. result._ranges = {};
  50334. for (var rangeName in this._ranges) {
  50335. result._ranges[rangeName] = this._ranges[rangeName].clone();
  50336. }
  50337. }
  50338. this._isDirty = true;
  50339. return result;
  50340. };
  50341. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  50342. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  50343. this.bones.forEach(function (bone) {
  50344. bone.animations.forEach(function (animation) {
  50345. animation.enableBlending = true;
  50346. animation.blendingSpeed = blendingSpeed;
  50347. });
  50348. });
  50349. };
  50350. Skeleton.prototype.dispose = function () {
  50351. this._meshesWithPoseMatrix = [];
  50352. // Animations
  50353. this.getScene().stopAnimation(this);
  50354. // Remove from scene
  50355. this.getScene().removeSkeleton(this);
  50356. };
  50357. Skeleton.prototype.serialize = function () {
  50358. var serializationObject = {};
  50359. serializationObject.name = this.name;
  50360. serializationObject.id = this.id;
  50361. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  50362. serializationObject.bones = [];
  50363. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  50364. for (var index = 0; index < this.bones.length; index++) {
  50365. var bone = this.bones[index];
  50366. var serializedBone = {
  50367. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  50368. name: bone.name,
  50369. matrix: bone.getBaseMatrix().toArray(),
  50370. rest: bone.getRestPose().toArray()
  50371. };
  50372. serializationObject.bones.push(serializedBone);
  50373. if (bone.length) {
  50374. serializedBone.length = bone.length;
  50375. }
  50376. if (bone.animations && bone.animations.length > 0) {
  50377. serializedBone.animation = bone.animations[0].serialize();
  50378. }
  50379. serializationObject.ranges = [];
  50380. for (var name in this._ranges) {
  50381. var range = {};
  50382. range.name = name;
  50383. range.from = this._ranges[name].from;
  50384. range.to = this._ranges[name].to;
  50385. serializationObject.ranges.push(range);
  50386. }
  50387. }
  50388. return serializationObject;
  50389. };
  50390. Skeleton.Parse = function (parsedSkeleton, scene) {
  50391. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  50392. if (parsedSkeleton.dimensionsAtRest) {
  50393. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  50394. }
  50395. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  50396. var index;
  50397. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  50398. var parsedBone = parsedSkeleton.bones[index];
  50399. var parentBone = null;
  50400. if (parsedBone.parentBoneIndex > -1) {
  50401. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  50402. }
  50403. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  50404. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  50405. if (parsedBone.length) {
  50406. bone.length = parsedBone.length;
  50407. }
  50408. if (parsedBone.animation) {
  50409. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  50410. }
  50411. }
  50412. // placed after bones, so createAnimationRange can cascade down
  50413. if (parsedSkeleton.ranges) {
  50414. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  50415. var data = parsedSkeleton.ranges[index];
  50416. skeleton.createAnimationRange(data.name, data.from, data.to);
  50417. }
  50418. }
  50419. return skeleton;
  50420. };
  50421. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  50422. if (forceUpdate === void 0) { forceUpdate = false; }
  50423. var renderId = this._scene.getRenderId();
  50424. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  50425. this.bones[0].computeAbsoluteTransforms();
  50426. this._lastAbsoluteTransformsUpdateId = renderId;
  50427. }
  50428. };
  50429. Skeleton.prototype.getPoseMatrix = function () {
  50430. var poseMatrix;
  50431. if (this._meshesWithPoseMatrix.length > 0) {
  50432. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  50433. }
  50434. return poseMatrix;
  50435. };
  50436. return Skeleton;
  50437. }());
  50438. BABYLON.Skeleton = Skeleton;
  50439. })(BABYLON || (BABYLON = {}));
  50440. //# sourceMappingURL=babylon.skeleton.js.map
  50441. var BABYLON;
  50442. (function (BABYLON) {
  50443. var Internals;
  50444. (function (Internals) {
  50445. var FileFaceOrientation = (function () {
  50446. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  50447. this.name = name;
  50448. this.worldAxisForNormal = worldAxisForNormal;
  50449. this.worldAxisForFileX = worldAxisForFileX;
  50450. this.worldAxisForFileY = worldAxisForFileY;
  50451. }
  50452. return FileFaceOrientation;
  50453. }());
  50454. ;
  50455. /**
  50456. * Helper class dealing with the extraction of spherical polynomial dataArray
  50457. * from a cube map.
  50458. */
  50459. var CubeMapToSphericalPolynomialTools = (function () {
  50460. function CubeMapToSphericalPolynomialTools() {
  50461. }
  50462. /**
  50463. * Converts a cubemap to the according Spherical Polynomial data.
  50464. * This extracts the first 3 orders only as they are the only one used in the lighting.
  50465. *
  50466. * @param cubeInfo The Cube map to extract the information from.
  50467. * @return The Spherical Polynomial data.
  50468. */
  50469. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  50470. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  50471. var totalSolidAngle = 0.0;
  50472. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  50473. var du = 2.0 / cubeInfo.size;
  50474. var dv = du;
  50475. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  50476. var minUV = du * 0.5 - 1.0;
  50477. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  50478. var fileFace = this.FileFaces[faceIndex];
  50479. var dataArray = cubeInfo[fileFace.name];
  50480. var v = minUV;
  50481. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  50482. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  50483. // Because SP is still linear, so summation is fine in that basis.
  50484. for (var y = 0; y < cubeInfo.size; y++) {
  50485. var u = minUV;
  50486. for (var x = 0; x < cubeInfo.size; x++) {
  50487. // World direction (not normalised)
  50488. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  50489. worldDirection.normalize();
  50490. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  50491. if (1) {
  50492. var r = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0];
  50493. var g = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1];
  50494. var b = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2];
  50495. var color = new BABYLON.Color3(r, g, b);
  50496. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  50497. }
  50498. else {
  50499. if (faceIndex == 0) {
  50500. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  50501. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  50502. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  50503. }
  50504. else if (faceIndex == 1) {
  50505. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  50506. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  50507. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  50508. }
  50509. else if (faceIndex == 2) {
  50510. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  50511. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  50512. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  50513. }
  50514. else if (faceIndex == 3) {
  50515. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  50516. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  50517. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  50518. }
  50519. else if (faceIndex == 4) {
  50520. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  50521. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  50522. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  50523. }
  50524. else if (faceIndex == 5) {
  50525. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  50526. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  50527. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  50528. }
  50529. 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]);
  50530. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  50531. }
  50532. totalSolidAngle += deltaSolidAngle;
  50533. u += du;
  50534. }
  50535. v += dv;
  50536. }
  50537. }
  50538. var correctSolidAngle = 4.0 * Math.PI; // Solid angle for entire sphere is 4*pi
  50539. var correction = correctSolidAngle / totalSolidAngle;
  50540. sphericalHarmonics.scale(correction);
  50541. // Additionally scale by pi -- audit needed
  50542. sphericalHarmonics.scale(1.0 / Math.PI);
  50543. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  50544. };
  50545. return CubeMapToSphericalPolynomialTools;
  50546. }());
  50547. CubeMapToSphericalPolynomialTools.FileFaces = [
  50548. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  50549. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  50550. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  50551. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  50552. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  50553. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  50554. ];
  50555. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  50556. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  50557. })(BABYLON || (BABYLON = {}));
  50558. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  50559. var BABYLON;
  50560. (function (BABYLON) {
  50561. var Internals;
  50562. (function (Internals) {
  50563. /**
  50564. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  50565. */
  50566. var PanoramaToCubeMapTools = (function () {
  50567. function PanoramaToCubeMapTools() {
  50568. }
  50569. /**
  50570. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  50571. *
  50572. * @param float32Array The source data.
  50573. * @param inputWidth The width of the input panorama.
  50574. * @param inputhHeight The height of the input panorama.
  50575. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  50576. * @return The cubemap data
  50577. */
  50578. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  50579. if (!float32Array) {
  50580. throw "ConvertPanoramaToCubemap: input cannot be null";
  50581. }
  50582. if (float32Array.length != inputWidth * inputHeight * 3) {
  50583. throw "ConvertPanoramaToCubemap: input size is wrong";
  50584. }
  50585. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  50586. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  50587. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  50588. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  50589. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  50590. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  50591. return {
  50592. front: textureFront,
  50593. back: textureBack,
  50594. left: textureLeft,
  50595. right: textureRight,
  50596. up: textureUp,
  50597. down: textureDown,
  50598. size: size
  50599. };
  50600. };
  50601. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  50602. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  50603. var textureArray = new Float32Array(buffer);
  50604. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  50605. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  50606. var dy = 1 / texSize;
  50607. var fy = 0;
  50608. for (var y = 0; y < texSize; y++) {
  50609. var xv1 = faceData[0];
  50610. var xv2 = faceData[2];
  50611. for (var x = 0; x < texSize; x++) {
  50612. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  50613. v.normalize();
  50614. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  50615. // 3 channels per pixels
  50616. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  50617. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  50618. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  50619. xv1 = xv1.add(rotDX1);
  50620. xv2 = xv2.add(rotDX2);
  50621. }
  50622. fy += dy;
  50623. }
  50624. return textureArray;
  50625. };
  50626. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  50627. var theta = Math.atan2(vDir.z, vDir.x);
  50628. var phi = Math.acos(vDir.y);
  50629. while (theta < -Math.PI)
  50630. theta += 2 * Math.PI;
  50631. while (theta > Math.PI)
  50632. theta -= 2 * Math.PI;
  50633. var dx = theta / Math.PI;
  50634. var dy = phi / Math.PI;
  50635. // recenter.
  50636. dx = dx * 0.5 + 0.5;
  50637. var px = Math.round(dx * inputWidth);
  50638. if (px < 0)
  50639. px = 0;
  50640. else if (px >= inputWidth)
  50641. px = inputWidth - 1;
  50642. var py = Math.round(dy * inputHeight);
  50643. if (py < 0)
  50644. py = 0;
  50645. else if (py >= inputHeight)
  50646. py = inputHeight - 1;
  50647. var inputY = (inputHeight - py - 1);
  50648. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  50649. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  50650. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  50651. return {
  50652. r: r,
  50653. g: g,
  50654. b: b
  50655. };
  50656. };
  50657. return PanoramaToCubeMapTools;
  50658. }());
  50659. PanoramaToCubeMapTools.FACE_FRONT = [
  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_BACK = [
  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_RIGHT = [
  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_LEFT = [
  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_DOWN = [
  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. PanoramaToCubeMapTools.FACE_UP = [
  50690. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  50691. new BABYLON.Vector3(1.0, -1.0, 1.0),
  50692. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  50693. new BABYLON.Vector3(1.0, -1.0, -1.0)
  50694. ];
  50695. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  50696. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  50697. })(BABYLON || (BABYLON = {}));
  50698. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  50699. var BABYLON;
  50700. (function (BABYLON) {
  50701. var Internals;
  50702. (function (Internals) {
  50703. ;
  50704. /**
  50705. * This groups tools to convert HDR texture to native colors array.
  50706. */
  50707. var HDRTools = (function () {
  50708. function HDRTools() {
  50709. }
  50710. HDRTools.Ldexp = function (mantissa, exponent) {
  50711. if (exponent > 1023) {
  50712. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  50713. }
  50714. if (exponent < -1074) {
  50715. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  50716. }
  50717. return mantissa * Math.pow(2, exponent);
  50718. };
  50719. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  50720. if (exponent > 0) {
  50721. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  50722. float32array[index + 0] = red * exponent;
  50723. float32array[index + 1] = green * exponent;
  50724. float32array[index + 2] = blue * exponent;
  50725. }
  50726. else {
  50727. float32array[index + 0] = 0;
  50728. float32array[index + 1] = 0;
  50729. float32array[index + 2] = 0;
  50730. }
  50731. };
  50732. HDRTools.readStringLine = function (uint8array, startIndex) {
  50733. var line = "";
  50734. var character = "";
  50735. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  50736. character = String.fromCharCode(uint8array[i]);
  50737. if (character == "\n") {
  50738. break;
  50739. }
  50740. line += character;
  50741. }
  50742. return line;
  50743. };
  50744. /**
  50745. * Reads header information from an RGBE texture stored in a native array.
  50746. * More information on this format are available here:
  50747. * https://en.wikipedia.org/wiki/RGBE_image_format
  50748. *
  50749. * @param uint8array The binary file stored in native array.
  50750. * @return The header information.
  50751. */
  50752. HDRTools.RGBE_ReadHeader = function (uint8array) {
  50753. var height = 0;
  50754. var width = 0;
  50755. var line = this.readStringLine(uint8array, 0);
  50756. if (line[0] != '#' || line[1] != '?') {
  50757. throw "Bad HDR Format.";
  50758. }
  50759. var endOfHeader = false;
  50760. var findFormat = false;
  50761. var lineIndex = 0;
  50762. do {
  50763. lineIndex += (line.length + 1);
  50764. line = this.readStringLine(uint8array, lineIndex);
  50765. if (line == "FORMAT=32-bit_rle_rgbe") {
  50766. findFormat = true;
  50767. }
  50768. else if (line.length == 0) {
  50769. endOfHeader = true;
  50770. }
  50771. } while (!endOfHeader);
  50772. if (!findFormat) {
  50773. throw "HDR Bad header format, unsupported FORMAT";
  50774. }
  50775. lineIndex += (line.length + 1);
  50776. line = this.readStringLine(uint8array, lineIndex);
  50777. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  50778. var match = sizeRegexp.exec(line);
  50779. // TODO. Support +Y and -X if needed.
  50780. if (match.length < 3) {
  50781. throw "HDR Bad header format, no size";
  50782. }
  50783. width = parseInt(match[2]);
  50784. height = parseInt(match[1]);
  50785. if (width < 8 || width > 0x7fff) {
  50786. throw "HDR Bad header format, unsupported size";
  50787. }
  50788. lineIndex += (line.length + 1);
  50789. return {
  50790. height: height,
  50791. width: width,
  50792. dataPosition: lineIndex
  50793. };
  50794. };
  50795. /**
  50796. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  50797. * This RGBE texture needs to store the information as a panorama.
  50798. *
  50799. * More information on this format are available here:
  50800. * https://en.wikipedia.org/wiki/RGBE_image_format
  50801. *
  50802. * @param buffer The binary file stored in an array buffer.
  50803. * @param size The expected size of the extracted cubemap.
  50804. * @return The Cube Map information.
  50805. */
  50806. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  50807. var uint8array = new Uint8Array(buffer);
  50808. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  50809. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  50810. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  50811. return cubeMapData;
  50812. };
  50813. /**
  50814. * Returns the pixels data extracted from an RGBE texture.
  50815. * This pixels will be stored left to right up to down in the R G B order in one array.
  50816. *
  50817. * More information on this format are available here:
  50818. * https://en.wikipedia.org/wiki/RGBE_image_format
  50819. *
  50820. * @param uint8array The binary file stored in an array buffer.
  50821. * @param hdrInfo The header information of the file.
  50822. * @return The pixels data in RGB right to left up to down order.
  50823. */
  50824. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  50825. // Keep for multi format supports.
  50826. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  50827. };
  50828. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  50829. var num_scanlines = hdrInfo.height;
  50830. var scanline_width = hdrInfo.width;
  50831. var a, b, c, d, count;
  50832. var dataIndex = hdrInfo.dataPosition;
  50833. var index = 0, endIndex = 0, i = 0;
  50834. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  50835. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  50836. // 3 channels of 4 bytes per pixel in float.
  50837. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  50838. var resultArray = new Float32Array(resultBuffer);
  50839. // read in each successive scanline
  50840. while (num_scanlines > 0) {
  50841. a = uint8array[dataIndex++];
  50842. b = uint8array[dataIndex++];
  50843. c = uint8array[dataIndex++];
  50844. d = uint8array[dataIndex++];
  50845. if (a != 2 || b != 2 || (c & 0x80)) {
  50846. // this file is not run length encoded
  50847. throw "HDR Bad header format, not RLE";
  50848. }
  50849. if (((c << 8) | d) != scanline_width) {
  50850. throw "HDR Bad header format, wrong scan line width";
  50851. }
  50852. index = 0;
  50853. // read each of the four channels for the scanline into the buffer
  50854. for (i = 0; i < 4; i++) {
  50855. endIndex = (i + 1) * scanline_width;
  50856. while (index < endIndex) {
  50857. a = uint8array[dataIndex++];
  50858. b = uint8array[dataIndex++];
  50859. if (a > 128) {
  50860. // a run of the same value
  50861. count = a - 128;
  50862. if ((count == 0) || (count > endIndex - index)) {
  50863. throw "HDR Bad Format, bad scanline data (run)";
  50864. }
  50865. while (count-- > 0) {
  50866. scanLineArray[index++] = b;
  50867. }
  50868. }
  50869. else {
  50870. // a non-run
  50871. count = a;
  50872. if ((count == 0) || (count > endIndex - index)) {
  50873. throw "HDR Bad Format, bad scanline data (non-run)";
  50874. }
  50875. scanLineArray[index++] = b;
  50876. if (--count > 0) {
  50877. for (var j = 0; j < count; j++) {
  50878. scanLineArray[index++] = uint8array[dataIndex++];
  50879. }
  50880. }
  50881. }
  50882. }
  50883. }
  50884. // now convert data from buffer into floats
  50885. for (i = 0; i < scanline_width; i++) {
  50886. a = scanLineArray[i];
  50887. b = scanLineArray[i + scanline_width];
  50888. c = scanLineArray[i + 2 * scanline_width];
  50889. d = scanLineArray[i + 3 * scanline_width];
  50890. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  50891. }
  50892. num_scanlines--;
  50893. }
  50894. return resultArray;
  50895. };
  50896. return HDRTools;
  50897. }());
  50898. Internals.HDRTools = HDRTools;
  50899. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  50900. })(BABYLON || (BABYLON = {}));
  50901. //# sourceMappingURL=babylon.hdr.js.map
  50902. //_______________________________________________________________
  50903. // Extracted from CubeMapGen:
  50904. // https://code.google.com/archive/p/cubemapgen/
  50905. //
  50906. // Following https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  50907. //_______________________________________________________________
  50908. var BABYLON;
  50909. (function (BABYLON) {
  50910. var Internals;
  50911. (function (Internals) {
  50912. /**
  50913. * The bounding box information used during the conversion process.
  50914. */
  50915. var CMGBoundinBox = (function () {
  50916. function CMGBoundinBox() {
  50917. this.min = new BABYLON.Vector3(0, 0, 0);
  50918. this.max = new BABYLON.Vector3(0, 0, 0);
  50919. this.clear();
  50920. }
  50921. CMGBoundinBox.prototype.clear = function () {
  50922. this.min.x = CMGBoundinBox.MAX;
  50923. this.min.y = CMGBoundinBox.MAX;
  50924. this.min.z = CMGBoundinBox.MAX;
  50925. this.max.x = CMGBoundinBox.MIN;
  50926. this.max.y = CMGBoundinBox.MIN;
  50927. this.max.z = CMGBoundinBox.MIN;
  50928. };
  50929. CMGBoundinBox.prototype.augment = function (x, y, z) {
  50930. this.min.x = Math.min(this.min.x, x);
  50931. this.min.y = Math.min(this.min.y, y);
  50932. this.min.z = Math.min(this.min.z, z);
  50933. this.max.x = Math.max(this.max.x, x);
  50934. this.max.y = Math.max(this.max.y, y);
  50935. this.max.z = Math.max(this.max.z, z);
  50936. };
  50937. CMGBoundinBox.prototype.clampMin = function (x, y, z) {
  50938. this.min.x = Math.max(this.min.x, x);
  50939. this.min.y = Math.max(this.min.y, y);
  50940. this.min.z = Math.max(this.min.z, z);
  50941. };
  50942. CMGBoundinBox.prototype.clampMax = function (x, y, z) {
  50943. this.max.x = Math.min(this.max.x, x);
  50944. this.max.y = Math.min(this.max.y, y);
  50945. this.max.z = Math.min(this.max.z, z);
  50946. };
  50947. CMGBoundinBox.prototype.empty = function () {
  50948. if ((this.min.x > this.max.y) ||
  50949. (this.min.y > this.max.y) ||
  50950. (this.min.z > this.max.y)) {
  50951. return true;
  50952. }
  50953. else {
  50954. return false;
  50955. }
  50956. };
  50957. return CMGBoundinBox;
  50958. }());
  50959. CMGBoundinBox.MAX = Number.MAX_VALUE;
  50960. CMGBoundinBox.MIN = Number.MIN_VALUE;
  50961. /**
  50962. * Helper class to PreProcess a cubemap in order to generate mipmap according to the level of blur
  50963. * required by the glossinees of a material.
  50964. *
  50965. * This only supports the cosine drop power as well as Warp fixup generation method.
  50966. *
  50967. * This is using the process from CubeMapGen described here:
  50968. * https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  50969. */
  50970. var PMREMGenerator = (function () {
  50971. /**
  50972. * Constructor of the generator.
  50973. *
  50974. * @param input The different faces data from the original cubemap in the order X+ X- Y+ Y- Z+ Z-
  50975. * @param inputSize The size of the cubemap faces
  50976. * @param outputSize The size of the output cubemap faces
  50977. * @param maxNumMipLevels The max number of mip map to generate (0 means all)
  50978. * @param numChannels The number of channels stored in the cubemap (3 for RBGE for instance)
  50979. * @param isFloat Specifies if the input texture is in float or int (hdr is usually in float)
  50980. * @param specularPower The max specular level of the desired cubemap
  50981. * @param cosinePowerDropPerMip The amount of drop the specular power will follow on each mip
  50982. * @param excludeBase Specifies wether to process the level 0 (original level) or not
  50983. * @param fixup Specifies wether to apply the edge fixup algorythm or not
  50984. */
  50985. function PMREMGenerator(input, inputSize, outputSize, maxNumMipLevels, numChannels, isFloat, specularPower, cosinePowerDropPerMip, excludeBase, fixup) {
  50986. this.input = input;
  50987. this.inputSize = inputSize;
  50988. this.outputSize = outputSize;
  50989. this.maxNumMipLevels = maxNumMipLevels;
  50990. this.numChannels = numChannels;
  50991. this.isFloat = isFloat;
  50992. this.specularPower = specularPower;
  50993. this.cosinePowerDropPerMip = cosinePowerDropPerMip;
  50994. this.excludeBase = excludeBase;
  50995. this.fixup = fixup;
  50996. this._outputSurface = [];
  50997. this._numMipLevels = 0;
  50998. }
  50999. /**
  51000. * Launches the filter process and return the result.
  51001. *
  51002. * @return the filter cubemap in the form mip0 [faces1..6] .. mipN [faces1..6]
  51003. */
  51004. PMREMGenerator.prototype.filterCubeMap = function () {
  51005. // Init cubemap processor
  51006. this.init();
  51007. // Filters the cubemap
  51008. this.filterCubeMapMipChain();
  51009. // Returns the filtered mips.
  51010. return this._outputSurface;
  51011. };
  51012. PMREMGenerator.prototype.init = function () {
  51013. var i;
  51014. var j;
  51015. var mipLevelSize;
  51016. //if nax num mip levels is set to 0, set it to generate the entire mip chain
  51017. if (this.maxNumMipLevels == 0) {
  51018. this.maxNumMipLevels = PMREMGenerator.CP_MAX_MIPLEVELS;
  51019. }
  51020. //first miplevel size
  51021. mipLevelSize = this.outputSize;
  51022. //Iterate over mip chain, and init ArrayBufferView for mip-chain
  51023. for (j = 0; j < this.maxNumMipLevels; j++) {
  51024. this._outputSurface.length++;
  51025. this._outputSurface[j] = [];
  51026. //Iterate over faces for output images
  51027. for (i = 0; i < 6; i++) {
  51028. this._outputSurface[j].length++;
  51029. // Initializes a new array for the output.
  51030. if (this.isFloat) {
  51031. this._outputSurface[j][i] = new Float32Array(mipLevelSize * mipLevelSize * this.numChannels);
  51032. }
  51033. else {
  51034. this._outputSurface[j][i] = new Uint32Array(mipLevelSize * mipLevelSize * this.numChannels);
  51035. }
  51036. }
  51037. //next mip level is half size
  51038. mipLevelSize >>= 1;
  51039. this._numMipLevels++;
  51040. //terminate if mip chain becomes too small
  51041. if (mipLevelSize == 0) {
  51042. this.maxNumMipLevels = j;
  51043. return;
  51044. }
  51045. }
  51046. };
  51047. //--------------------------------------------------------------------------------------
  51048. //Cube map filtering and mip chain generation.
  51049. // the cube map filtereing is specified using a number of parameters:
  51050. // Filtering per miplevel is specified using 2D cone angle (in degrees) that
  51051. // indicates the region of the hemisphere to filter over for each tap.
  51052. //
  51053. // Note that the top mip level is also a filtered version of the original input images
  51054. // as well in order to create mip chains for diffuse environment illumination.
  51055. // The cone angle for the top level is specified by a_BaseAngle. This can be used to
  51056. // generate mipchains used to store the resutls of preintegration across the hemisphere.
  51057. //
  51058. // Then the mip angle used to genreate the next level of the mip chain from the first level
  51059. // is a_InitialMipAngle
  51060. //
  51061. // The angle for the subsequent levels of the mip chain are specified by their parents
  51062. // filtering angle and a per-level scale and bias
  51063. // newAngle = oldAngle * a_MipAnglePerLevelScale;
  51064. //
  51065. //--------------------------------------------------------------------------------------
  51066. PMREMGenerator.prototype.filterCubeMapMipChain = function () {
  51067. // First, take count of the lighting model to modify SpecularPower
  51068. // 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;
  51069. // var refSpecularPower = this.specularPower; // Only Phong BRDF yet. This explains the line below using this.specularpower.
  51070. //Cone angle start (for generating subsequent mip levels)
  51071. var currentSpecularPower = this.specularPower;
  51072. //Build filter lookup tables based on the source miplevel size
  51073. this.precomputeFilterLookupTables(this.inputSize);
  51074. // Note that we need to filter the first level before generating mipmap
  51075. // So LevelIndex == 0 is base filtering hen LevelIndex > 0 is mipmap generation
  51076. for (var levelIndex = 0; levelIndex < this._numMipLevels; levelIndex++) {
  51077. // TODO : Write a function to copy and scale the base mipmap in output
  51078. // I am just lazy here and just put a high specular power value, and do some if.
  51079. if (this.excludeBase && (levelIndex == 0)) {
  51080. // 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).
  51081. currentSpecularPower = 100000.0;
  51082. }
  51083. // Special case for cosine power mipmap chain. For quality requirement, we always process the current mipmap from the top mipmap
  51084. var srcCubeImage = this.input;
  51085. var dstCubeImage = this._outputSurface[levelIndex];
  51086. var dstSize = this.outputSize >> levelIndex;
  51087. // Compute required angle.
  51088. var angle = this.getBaseFilterAngle(currentSpecularPower);
  51089. // filter cube surfaces
  51090. this.filterCubeSurfaces(srcCubeImage, this.inputSize, dstCubeImage, dstSize, angle, currentSpecularPower);
  51091. // fix seams
  51092. if (this.fixup) {
  51093. this.fixupCubeEdges(dstCubeImage, dstSize);
  51094. }
  51095. // Decrease the specular power to generate the mipmap chain
  51096. // TODO : Use another method for Exclude (see first comment at start of the function
  51097. if (this.excludeBase && (levelIndex == 0)) {
  51098. currentSpecularPower = this.specularPower;
  51099. }
  51100. currentSpecularPower *= this.cosinePowerDropPerMip;
  51101. }
  51102. };
  51103. //--------------------------------------------------------------------------------------
  51104. // This function return the BaseFilterAngle require by PMREMGenerator to its FilterExtends
  51105. // It allow to optimize the texel to access base on the specular power.
  51106. //--------------------------------------------------------------------------------------
  51107. PMREMGenerator.prototype.getBaseFilterAngle = function (cosinePower) {
  51108. // We want to find the alpha such that:
  51109. // cos(alpha)^cosinePower = epsilon
  51110. // That's: acos(epsilon^(1/cosinePower))
  51111. var threshold = 0.000001; // Empirical threshold (Work perfectly, didn't check for a more big number, may get some performance and still god approximation)
  51112. var angle = 180.0;
  51113. angle = Math.acos(Math.pow(threshold, 1.0 / cosinePower));
  51114. angle *= 180.0 / Math.PI; // Convert to degree
  51115. angle *= 2.0; // * 2.0f because PMREMGenerator divide by 2 later
  51116. return angle;
  51117. };
  51118. //--------------------------------------------------------------------------------------
  51119. //Builds the following lookup tables prior to filtering:
  51120. // -normalizer cube map
  51121. // -tap weight lookup table
  51122. //
  51123. //--------------------------------------------------------------------------------------
  51124. PMREMGenerator.prototype.precomputeFilterLookupTables = function (srcCubeMapWidth) {
  51125. var srcTexelAngle;
  51126. var iCubeFace;
  51127. //clear pre-existing normalizer cube map
  51128. this._normCubeMap = [];
  51129. //Normalized vectors per cubeface and per-texel solid angle
  51130. this.buildNormalizerSolidAngleCubemap(srcCubeMapWidth);
  51131. };
  51132. //--------------------------------------------------------------------------------------
  51133. //Builds a normalizer cubemap, with the texels solid angle stored in the fourth component
  51134. //
  51135. //Takes in a cube face size, and an array of 6 surfaces to write the cube faces into
  51136. //
  51137. //Note that this normalizer cube map stores the vectors in unbiased -1 to 1 range.
  51138. // if _bx2 style scaled and biased vectors are needed, uncomment the SCALE and BIAS
  51139. // below
  51140. //--------------------------------------------------------------------------------------
  51141. PMREMGenerator.prototype.buildNormalizerSolidAngleCubemap = function (size) {
  51142. var iCubeFace;
  51143. var u;
  51144. var v;
  51145. //iterate over cube faces
  51146. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  51147. //First three channels for norm cube, and last channel for solid angle
  51148. this._normCubeMap.push(new Float32Array(size * size * 4));
  51149. //fast texture walk, build normalizer cube map
  51150. var facesData = this.input[iCubeFace];
  51151. for (v = 0; v < size; v++) {
  51152. for (u = 0; u < size; u++) {
  51153. var vect = this.texelCoordToVect(iCubeFace, u, v, size, this.fixup);
  51154. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 0] = vect.x;
  51155. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 1] = vect.y;
  51156. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 2] = vect.z;
  51157. var solidAngle = this.texelCoordSolidAngle(iCubeFace, u, v, size);
  51158. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 4] = solidAngle;
  51159. }
  51160. }
  51161. }
  51162. };
  51163. //--------------------------------------------------------------------------------------
  51164. // Convert cubemap face texel coordinates and face idx to 3D vector
  51165. // note the U and V coords are integer coords and range from 0 to size-1
  51166. // this routine can be used to generate a normalizer cube map
  51167. //--------------------------------------------------------------------------------------
  51168. // SL BEGIN
  51169. PMREMGenerator.prototype.texelCoordToVect = function (faceIdx, u, v, size, fixup) {
  51170. var nvcU;
  51171. var nvcV;
  51172. var tempVec;
  51173. // Change from original AMD code
  51174. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  51175. // + 0.5f is for texel center addressing
  51176. nvcU = (2.0 * (u + 0.5) / size) - 1.0;
  51177. nvcV = (2.0 * (v + 0.5) / size) - 1.0;
  51178. // warp fixup
  51179. if (fixup && size > 1) {
  51180. // Code from Nvtt : http://code.google.com/p/nvidia-texture-tools/source/browse/trunk/src/nvtt/CubeSurface.cpp
  51181. var a = Math.pow(size, 2.0) / Math.pow(size - 1, 3.0);
  51182. nvcU = a * Math.pow(nvcU, 3) + nvcU;
  51183. nvcV = a * Math.pow(nvcV, 3) + nvcV;
  51184. }
  51185. // Get current vector
  51186. // generate x,y,z vector (xform 2d NVC coord to 3D vector)
  51187. // U contribution
  51188. var UVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  51189. PMREMGenerator._vectorTemp.x = UVec[0] * nvcU;
  51190. PMREMGenerator._vectorTemp.y = UVec[1] * nvcU;
  51191. PMREMGenerator._vectorTemp.z = UVec[2] * nvcU;
  51192. // V contribution and Sum
  51193. var VVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  51194. PMREMGenerator._vectorTemp.x += VVec[0] * nvcV;
  51195. PMREMGenerator._vectorTemp.y += VVec[1] * nvcV;
  51196. PMREMGenerator._vectorTemp.z += VVec[2] * nvcV;
  51197. //add face axis
  51198. var faceAxis = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_FACEAXIS];
  51199. PMREMGenerator._vectorTemp.x += faceAxis[0];
  51200. PMREMGenerator._vectorTemp.y += faceAxis[1];
  51201. PMREMGenerator._vectorTemp.z += faceAxis[2];
  51202. //normalize vector
  51203. PMREMGenerator._vectorTemp.normalize();
  51204. return PMREMGenerator._vectorTemp;
  51205. };
  51206. //--------------------------------------------------------------------------------------
  51207. // Convert 3D vector to cubemap face texel coordinates and face idx
  51208. // note the U and V coords are integer coords and range from 0 to size-1
  51209. // this routine can be used to generate a normalizer cube map
  51210. //
  51211. // returns face IDX and texel coords
  51212. //--------------------------------------------------------------------------------------
  51213. // SL BEGIN
  51214. /*
  51215. Mapping Texture Coordinates to Cube Map Faces
  51216. Because there are multiple faces, the mapping of texture coordinates to positions on cube map faces
  51217. is more complicated than the other texturing targets. The EXT_texture_cube_map extension is purposefully
  51218. designed to be consistent with DirectX 7's cube map arrangement. This is also consistent with the cube
  51219. map arrangement in Pixar's RenderMan package.
  51220. For cube map texturing, the (s,t,r) texture coordinates are treated as a direction vector (rx,ry,rz)
  51221. emanating from the center of a cube. (The q coordinate can be ignored since it merely scales the vector
  51222. without affecting the direction.) At texture application time, the interpolated per-fragment (s,t,r)
  51223. selects one of the cube map face's 2D mipmap sets based on the largest magnitude coordinate direction
  51224. the major axis direction). The target column in the table below explains how the major axis direction
  51225. maps to the 2D image of a particular cube map target.
  51226. major axis
  51227. direction target sc tc ma
  51228. ---------- --------------------------------- --- --- ---
  51229. +rx GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT -rz -ry rx
  51230. -rx GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT +rz -ry rx
  51231. +ry GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT +rx +rz ry
  51232. -ry GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT +rx -rz ry
  51233. +rz GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT +rx -ry rz
  51234. -rz GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT -rx -ry rz
  51235. Using the sc, tc, and ma determined by the major axis direction as specified in the table above,
  51236. an updated (s,t) is calculated as follows
  51237. s = ( sc/|ma| + 1 ) / 2
  51238. t = ( tc/|ma| + 1 ) / 2
  51239. If |ma| is zero or very nearly zero, the results of the above two equations need not be defined
  51240. (though the result may not lead to GL interruption or termination). Once the cube map face's 2D mipmap
  51241. set and (s,t) is determined, texture fetching and filtering proceeds like standard OpenGL 2D texturing.
  51242. */
  51243. // Note this method return U and V in range from 0 to size-1
  51244. // SL END
  51245. // Store the information in vector3 for convenience (faceindex, u, v)
  51246. PMREMGenerator.prototype.vectToTexelCoord = function (x, y, z, size) {
  51247. var maxCoord;
  51248. var faceIdx;
  51249. //absolute value 3
  51250. var absX = Math.abs(x);
  51251. var absY = Math.abs(y);
  51252. var absZ = Math.abs(z);
  51253. if (absX >= absY && absX >= absZ) {
  51254. maxCoord = absX;
  51255. if (x >= 0) {
  51256. faceIdx = PMREMGenerator.CP_FACE_X_POS;
  51257. }
  51258. else {
  51259. faceIdx = PMREMGenerator.CP_FACE_X_NEG;
  51260. }
  51261. }
  51262. else if (absY >= absX && absY >= absZ) {
  51263. maxCoord = absY;
  51264. if (y >= 0) {
  51265. faceIdx = PMREMGenerator.CP_FACE_Y_POS;
  51266. }
  51267. else {
  51268. faceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  51269. }
  51270. }
  51271. else {
  51272. maxCoord = absZ;
  51273. if (z >= 0) {
  51274. faceIdx = PMREMGenerator.CP_FACE_Z_POS;
  51275. }
  51276. else {
  51277. faceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  51278. }
  51279. }
  51280. //divide through by max coord so face vector lies on cube face
  51281. var scale = 1 / maxCoord;
  51282. x *= scale;
  51283. y *= scale;
  51284. z *= scale;
  51285. var temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  51286. var nvcU = temp[0] * x + temp[1] * y + temp[2] * z;
  51287. temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  51288. var nvcV = temp[0] * x + temp[1] * y + temp[2] * z;
  51289. // Modify original AMD code to return value from 0 to Size - 1
  51290. var u = Math.floor((size - 1) * 0.5 * (nvcU + 1.0));
  51291. var v = Math.floor((size - 1) * 0.5 * (nvcV + 1.0));
  51292. PMREMGenerator._vectorTemp.x = faceIdx;
  51293. PMREMGenerator._vectorTemp.y = u;
  51294. PMREMGenerator._vectorTemp.z = v;
  51295. return PMREMGenerator._vectorTemp;
  51296. };
  51297. //--------------------------------------------------------------------------------------
  51298. //Original code from Ignacio CastaÒo
  51299. // This formula is from Manne ÷hrstrˆm's thesis.
  51300. // Take two coordiantes in the range [-1, 1] that define a portion of a
  51301. // cube face and return the area of the projection of that portion on the
  51302. // surface of the sphere.
  51303. //--------------------------------------------------------------------------------------
  51304. PMREMGenerator.prototype.areaElement = function (x, y) {
  51305. return Math.atan2(x * y, Math.sqrt(x * x + y * y + 1));
  51306. };
  51307. PMREMGenerator.prototype.texelCoordSolidAngle = function (faceIdx, u, v, size) {
  51308. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  51309. // (+ 0.5f is for texel center addressing)
  51310. u = (2.0 * (u + 0.5) / size) - 1.0;
  51311. v = (2.0 * (v + 0.5) / size) - 1.0;
  51312. // Shift from a demi texel, mean 1.0f / a_Size with U and V in [-1..1]
  51313. var invResolution = 1.0 / size;
  51314. // U and V are the -1..1 texture coordinate on the current face.
  51315. // Get projected area for this texel
  51316. var x0 = u - invResolution;
  51317. var y0 = v - invResolution;
  51318. var x1 = u + invResolution;
  51319. var y1 = v + invResolution;
  51320. var solidAngle = this.areaElement(x0, y0) - this.areaElement(x0, y1) - this.areaElement(x1, y0) + this.areaElement(x1, y1);
  51321. return solidAngle;
  51322. };
  51323. //--------------------------------------------------------------------------------------
  51324. //The key to the speed of these filtering routines is to quickly define a per-face
  51325. // bounding box of pixels which enclose all the taps in the filter kernel efficiently.
  51326. // Later these pixels are selectively processed based on their dot products to see if
  51327. // they reside within the filtering cone.
  51328. //
  51329. //This is done by computing the smallest per-texel angle to get a conservative estimate
  51330. // of the number of texels needed to be covered in width and height order to filter the
  51331. // region. the bounding box for the center taps face is defined first, and if the
  51332. // filtereing region bleeds onto the other faces, bounding boxes for the other faces are
  51333. // defined next
  51334. //--------------------------------------------------------------------------------------
  51335. PMREMGenerator.prototype.filterCubeSurfaces = function (srcCubeMap, srcSize, dstCubeMap, dstSize, filterConeAngle, specularPower) {
  51336. // note that pixels within these regions may be rejected
  51337. // based on the anlge
  51338. var iCubeFace;
  51339. var u;
  51340. var v;
  51341. // bounding box per face to specify region to process
  51342. var filterExtents = [];
  51343. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  51344. filterExtents.push(new CMGBoundinBox());
  51345. }
  51346. // min angle a src texel can cover (in degrees)
  51347. var srcTexelAngle = (180.0 / (Math.PI) * Math.atan2(1.0, srcSize));
  51348. // angle about center tap to define filter cone
  51349. // filter angle is 1/2 the cone angle
  51350. var filterAngle = filterConeAngle / 2.0;
  51351. //ensure filter angle is larger than a texel
  51352. if (filterAngle < srcTexelAngle) {
  51353. filterAngle = srcTexelAngle;
  51354. }
  51355. //ensure filter cone is always smaller than the hemisphere
  51356. if (filterAngle > 90.0) {
  51357. filterAngle = 90.0;
  51358. }
  51359. // the maximum number of texels in 1D the filter cone angle will cover
  51360. // used to determine bounding box size for filter extents
  51361. var filterSize = Math.ceil(filterAngle / srcTexelAngle);
  51362. // ensure conservative region always covers at least one texel
  51363. if (filterSize < 1) {
  51364. filterSize = 1;
  51365. }
  51366. // dotProdThresh threshold based on cone angle to determine whether or not taps
  51367. // reside within the cone angle
  51368. var dotProdThresh = Math.cos((Math.PI / 180.0) * filterAngle);
  51369. // process required faces
  51370. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  51371. //iterate over dst cube map face texel
  51372. for (v = 0; v < dstSize; v++) {
  51373. for (u = 0; u < dstSize; u++) {
  51374. //get center tap direction
  51375. var centerTapDir = this.texelCoordToVect(iCubeFace, u, v, dstSize, this.fixup).clone();
  51376. //clear old per-face filter extents
  51377. this.clearFilterExtents(filterExtents);
  51378. //define per-face filter extents
  51379. this.determineFilterExtents(centerTapDir, srcSize, filterSize, filterExtents);
  51380. //perform filtering of src faces using filter extents
  51381. var vect = this.processFilterExtents(centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower);
  51382. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 0] = vect.x;
  51383. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 1] = vect.y;
  51384. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 2] = vect.z;
  51385. }
  51386. }
  51387. }
  51388. };
  51389. //--------------------------------------------------------------------------------------
  51390. //Clear filter extents for the 6 cube map faces
  51391. //--------------------------------------------------------------------------------------
  51392. PMREMGenerator.prototype.clearFilterExtents = function (filterExtents) {
  51393. for (var iCubeFaces = 0; iCubeFaces < 6; iCubeFaces++) {
  51394. filterExtents[iCubeFaces].clear();
  51395. }
  51396. };
  51397. //--------------------------------------------------------------------------------------
  51398. //Define per-face bounding box filter extents
  51399. //
  51400. // These define conservative texel regions in each of the faces the filter can possibly
  51401. // process. When the pixels in the regions are actually processed, the dot product
  51402. // between the tap vector and the center tap vector is used to determine the weight of
  51403. // the tap and whether or not the tap is within the cone.
  51404. //
  51405. //--------------------------------------------------------------------------------------
  51406. PMREMGenerator.prototype.determineFilterExtents = function (centerTapDir, srcSize, bboxSize, filterExtents) {
  51407. //neighboring face and bleed over amount, and width of BBOX for
  51408. // left, right, top, and bottom edges of this face
  51409. var bleedOverAmount = [0, 0, 0, 0];
  51410. var bleedOverBBoxMin = [0, 0, 0, 0];
  51411. var bleedOverBBoxMax = [0, 0, 0, 0];
  51412. var neighborFace;
  51413. var neighborEdge;
  51414. var oppositeFaceIdx;
  51415. //get face idx, and u, v info from center tap dir
  51416. var result = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize);
  51417. var faceIdx = result.x;
  51418. var u = result.y;
  51419. var v = result.z;
  51420. //define bbox size within face
  51421. filterExtents[faceIdx].augment(u - bboxSize, v - bboxSize, 0);
  51422. filterExtents[faceIdx].augment(u + bboxSize, v + bboxSize, 0);
  51423. filterExtents[faceIdx].clampMin(0, 0, 0);
  51424. filterExtents[faceIdx].clampMax(srcSize - 1, srcSize - 1, 0);
  51425. //u and v extent in face corresponding to center tap
  51426. var minU = filterExtents[faceIdx].min.x;
  51427. var minV = filterExtents[faceIdx].min.y;
  51428. var maxU = filterExtents[faceIdx].max.x;
  51429. var maxV = filterExtents[faceIdx].max.y;
  51430. //bleed over amounts for face across u=0 edge (left)
  51431. bleedOverAmount[0] = (bboxSize - u);
  51432. bleedOverBBoxMin[0] = minV;
  51433. bleedOverBBoxMax[0] = maxV;
  51434. //bleed over amounts for face across u=1 edge (right)
  51435. bleedOverAmount[1] = (u + bboxSize) - (srcSize - 1);
  51436. bleedOverBBoxMin[1] = minV;
  51437. bleedOverBBoxMax[1] = maxV;
  51438. //bleed over to face across v=0 edge (up)
  51439. bleedOverAmount[2] = (bboxSize - v);
  51440. bleedOverBBoxMin[2] = minU;
  51441. bleedOverBBoxMax[2] = maxU;
  51442. //bleed over to face across v=1 edge (down)
  51443. bleedOverAmount[3] = (v + bboxSize) - (srcSize - 1);
  51444. bleedOverBBoxMin[3] = minU;
  51445. bleedOverBBoxMax[3] = maxU;
  51446. //compute bleed over regions in neighboring faces
  51447. for (var i = 0; i < 4; i++) {
  51448. if (bleedOverAmount[i] > 0) {
  51449. neighborFace = PMREMGenerator._sgCubeNgh[faceIdx][i][0];
  51450. neighborEdge = PMREMGenerator._sgCubeNgh[faceIdx][i][1];
  51451. //For certain types of edge abutments, the bleedOverBBoxMin, and bleedOverBBoxMax need to
  51452. // be flipped: the cases are
  51453. // if a left edge mates with a left or bottom edge on the neighbor
  51454. // if a top edge mates with a top or right edge on the neighbor
  51455. // if a right edge mates with a right or top edge on the neighbor
  51456. // if a bottom edge mates with a bottom or left edge on the neighbor
  51457. //Seeing as the edges are enumerated as follows
  51458. // left =0
  51459. // right =1
  51460. // top =2
  51461. // bottom =3
  51462. //
  51463. // so if the edge enums are the same, or the sum of the enums == 3,
  51464. // the bbox needs to be flipped
  51465. if ((i == neighborEdge) || ((i + neighborEdge) == 3)) {
  51466. bleedOverBBoxMin[i] = (srcSize - 1) - bleedOverBBoxMin[i];
  51467. bleedOverBBoxMax[i] = (srcSize - 1) - bleedOverBBoxMax[i];
  51468. }
  51469. //The way the bounding box is extended onto the neighboring face
  51470. // depends on which edge of neighboring face abuts with this one
  51471. switch (PMREMGenerator._sgCubeNgh[faceIdx][i][1]) {
  51472. case PMREMGenerator.CP_EDGE_LEFT:
  51473. filterExtents[neighborFace].augment(0, bleedOverBBoxMin[i], 0);
  51474. filterExtents[neighborFace].augment(bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  51475. break;
  51476. case PMREMGenerator.CP_EDGE_RIGHT:
  51477. filterExtents[neighborFace].augment((srcSize - 1), bleedOverBBoxMin[i], 0);
  51478. filterExtents[neighborFace].augment((srcSize - 1) - bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  51479. break;
  51480. case PMREMGenerator.CP_EDGE_TOP:
  51481. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], 0, 0);
  51482. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], bleedOverAmount[i], 0);
  51483. break;
  51484. case PMREMGenerator.CP_EDGE_BOTTOM:
  51485. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], (srcSize - 1), 0);
  51486. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], (srcSize - 1) - bleedOverAmount[i], 0);
  51487. break;
  51488. }
  51489. //clamp filter extents in non-center tap faces to remain within surface
  51490. filterExtents[neighborFace].clampMin(0, 0, 0);
  51491. filterExtents[neighborFace].clampMax(srcSize - 1, srcSize - 1, 0);
  51492. }
  51493. //If the bleed over amount bleeds past the adjacent face onto the opposite face
  51494. // from the center tap face, then process the opposite face entirely for now.
  51495. //Note that the cases in which this happens, what usually happens is that
  51496. // more than one edge bleeds onto the opposite face, and the bounding box
  51497. // encompasses the entire cube map face.
  51498. if (bleedOverAmount[i] > srcSize) {
  51499. //determine opposite face
  51500. switch (faceIdx) {
  51501. case PMREMGenerator.CP_FACE_X_POS:
  51502. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_NEG;
  51503. break;
  51504. case PMREMGenerator.CP_FACE_X_NEG:
  51505. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_POS;
  51506. break;
  51507. case PMREMGenerator.CP_FACE_Y_POS:
  51508. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  51509. break;
  51510. case PMREMGenerator.CP_FACE_Y_NEG:
  51511. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_POS;
  51512. break;
  51513. case PMREMGenerator.CP_FACE_Z_POS:
  51514. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  51515. break;
  51516. case PMREMGenerator.CP_FACE_Z_NEG:
  51517. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_POS;
  51518. break;
  51519. default:
  51520. break;
  51521. }
  51522. //just encompass entire face for now
  51523. filterExtents[oppositeFaceIdx].augment(0, 0, 0);
  51524. filterExtents[oppositeFaceIdx].augment((srcSize - 1), (srcSize - 1), 0);
  51525. }
  51526. }
  51527. };
  51528. //--------------------------------------------------------------------------------------
  51529. //ProcessFilterExtents
  51530. // Process bounding box in each cube face
  51531. //
  51532. //--------------------------------------------------------------------------------------
  51533. PMREMGenerator.prototype.processFilterExtents = function (centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower) {
  51534. //accumulators are 64-bit floats in order to have the precision needed
  51535. // over a summation of a large number of pixels
  51536. var dstAccum = [0, 0, 0, 0];
  51537. var weightAccum = 0;
  51538. var k = 0;
  51539. var nSrcChannels = this.numChannels;
  51540. // norm cube map and srcCubeMap have same face width
  51541. var faceWidth = srcSize;
  51542. //amount to add to pointer to move to next scanline in images
  51543. var normCubePitch = faceWidth * 4; // 4 channels in normCubeMap.
  51544. var srcCubePitch = faceWidth * this.numChannels; // numChannels correponds to the cubemap number of channel
  51545. var IsPhongBRDF = 1; // Only works in Phong BRDF yet.
  51546. //(a_LightingModel == CP_LIGHTINGMODEL_PHONG_BRDF || a_LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? 1 : 0; // This value will be added to the specular power
  51547. // iterate over cubefaces
  51548. for (var iFaceIdx = 0; iFaceIdx < 6; iFaceIdx++) {
  51549. //if bbox is non empty
  51550. if (!filterExtents[iFaceIdx].empty()) {
  51551. var uStart = filterExtents[iFaceIdx].min.x;
  51552. var vStart = filterExtents[iFaceIdx].min.y;
  51553. var uEnd = filterExtents[iFaceIdx].max.x;
  51554. var vEnd = filterExtents[iFaceIdx].max.y;
  51555. var startIndexNormCubeMap = (4 * ((vStart * faceWidth) + uStart));
  51556. var startIndexSrcCubeMap = (this.numChannels * ((vStart * faceWidth) + uStart));
  51557. //note that <= is used to ensure filter extents always encompass at least one pixel if bbox is non empty
  51558. for (var v = vStart; v <= vEnd; v++) {
  51559. var normCubeRowWalk = 0;
  51560. var srcCubeRowWalk = 0;
  51561. for (var u = uStart; u <= uEnd; u++) {
  51562. //pointer to direction in cube map associated with texel
  51563. var texelVectX = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 0];
  51564. var texelVectY = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 1];
  51565. var texelVectZ = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 2];
  51566. //check dot product to see if texel is within cone
  51567. var tapDotProd = texelVectX * centerTapDir.x +
  51568. texelVectY * centerTapDir.y +
  51569. texelVectZ * centerTapDir.z;
  51570. if (tapDotProd >= dotProdThresh && tapDotProd > 0.0) {
  51571. //solid angle stored in 4th channel of normalizer/solid angle cube map
  51572. var weight = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 3];
  51573. // Here we decide if we use a Phong/Blinn or a Phong/Blinn BRDF.
  51574. // Phong/Blinn BRDF is just the Phong/Blinn model multiply by the cosine of the lambert law
  51575. // so just adding one to specularpower do the trick.
  51576. weight *= Math.pow(tapDotProd, (specularPower + IsPhongBRDF));
  51577. //iterate over channels
  51578. for (k = 0; k < nSrcChannels; k++) {
  51579. dstAccum[k] += weight * srcCubeMap[iFaceIdx][startIndexSrcCubeMap + srcCubeRowWalk];
  51580. srcCubeRowWalk++;
  51581. }
  51582. weightAccum += weight; //accumulate weight
  51583. }
  51584. else {
  51585. //step across source pixel
  51586. srcCubeRowWalk += nSrcChannels;
  51587. }
  51588. normCubeRowWalk += 4; // 4 channels per norm cube map.
  51589. }
  51590. startIndexNormCubeMap += normCubePitch;
  51591. startIndexSrcCubeMap += srcCubePitch;
  51592. }
  51593. }
  51594. }
  51595. //divide through by weights if weight is non zero
  51596. if (weightAccum != 0.0) {
  51597. PMREMGenerator._vectorTemp.x = (dstAccum[0] / weightAccum);
  51598. PMREMGenerator._vectorTemp.y = (dstAccum[1] / weightAccum);
  51599. PMREMGenerator._vectorTemp.z = (dstAccum[2] / weightAccum);
  51600. if (this.numChannels > 3) {
  51601. PMREMGenerator._vectorTemp.w = (dstAccum[3] / weightAccum);
  51602. }
  51603. }
  51604. else {
  51605. // otherwise sample nearest
  51606. // get face idx and u, v texel coordinate in face
  51607. var coord = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize).clone();
  51608. PMREMGenerator._vectorTemp.x = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 0];
  51609. PMREMGenerator._vectorTemp.y = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 1];
  51610. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 2];
  51611. if (this.numChannels > 3) {
  51612. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 3];
  51613. }
  51614. }
  51615. return PMREMGenerator._vectorTemp;
  51616. };
  51617. //--------------------------------------------------------------------------------------
  51618. // Fixup cube edges
  51619. //
  51620. // average texels on cube map faces across the edges
  51621. // WARP/BENT Method Only.
  51622. //--------------------------------------------------------------------------------------
  51623. PMREMGenerator.prototype.fixupCubeEdges = function (cubeMap, cubeMapSize) {
  51624. var k;
  51625. var j;
  51626. var i;
  51627. var iFace;
  51628. var iCorner = 0;
  51629. var cornerNumPtrs = [0, 0, 0, 0, 0, 0, 0, 0]; //indexed by corner and face idx
  51630. var faceCornerStartIndicies = [[], [], [], []]; //corner pointers for face keeping track of the face they belong to.
  51631. // note that if functionality to filter across the three texels for each corner, then
  51632. //indexed by corner and face idx. the array contains the face the start points belongs to.
  51633. var cornerPtr = [
  51634. [[], [], []],
  51635. [[], [], []],
  51636. [[], [], []],
  51637. [[], [], []],
  51638. [[], [], []],
  51639. [[], [], []],
  51640. [[], [], []],
  51641. [[], [], []]
  51642. ];
  51643. //if there is no fixup, or fixup width = 0, do nothing
  51644. if (cubeMapSize < 1) {
  51645. return;
  51646. }
  51647. //special case 1x1 cubemap, average face colors
  51648. if (cubeMapSize == 1) {
  51649. //iterate over channels
  51650. for (k = 0; k < this.numChannels; k++) {
  51651. var accum = 0.0;
  51652. //iterate over faces to accumulate face colors
  51653. for (iFace = 0; iFace < 6; iFace++) {
  51654. accum += cubeMap[iFace][k];
  51655. }
  51656. //compute average over 6 face colors
  51657. accum /= 6.0;
  51658. //iterate over faces to distribute face colors
  51659. for (iFace = 0; iFace < 6; iFace++) {
  51660. cubeMap[iFace][k] = accum;
  51661. }
  51662. }
  51663. return;
  51664. }
  51665. //iterate over faces to collect list of corner texel pointers
  51666. for (iFace = 0; iFace < 6; iFace++) {
  51667. //the 4 corner pointers for this face
  51668. faceCornerStartIndicies[0] = [iFace, 0];
  51669. faceCornerStartIndicies[1] = [iFace, ((cubeMapSize - 1) * this.numChannels)];
  51670. faceCornerStartIndicies[2] = [iFace, ((cubeMapSize) * (cubeMapSize - 1) * this.numChannels)];
  51671. faceCornerStartIndicies[3] = [iFace, ((((cubeMapSize) * (cubeMapSize - 1)) + (cubeMapSize - 1)) * this.numChannels)];
  51672. //iterate over face corners to collect cube corner pointers
  51673. for (iCorner = 0; iCorner < 4; iCorner++) {
  51674. var corner = PMREMGenerator._sgCubeCornerList[iFace][iCorner];
  51675. cornerPtr[corner][cornerNumPtrs[corner]] = faceCornerStartIndicies[iCorner];
  51676. cornerNumPtrs[corner]++;
  51677. }
  51678. }
  51679. //iterate over corners to average across corner tap values
  51680. for (iCorner = 0; iCorner < 8; iCorner++) {
  51681. for (k = 0; k < this.numChannels; k++) {
  51682. var cornerTapAccum = 0.0;
  51683. //iterate over corner texels and average results
  51684. for (i = 0; i < 3; i++) {
  51685. cornerTapAccum += cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k]; // Get in the cube map face the start point + channel.
  51686. }
  51687. //divide by 3 to compute average of corner tap values
  51688. cornerTapAccum *= (1.0 / 3.0);
  51689. //iterate over corner texels and average results
  51690. for (i = 0; i < 3; i++) {
  51691. cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k] = cornerTapAccum;
  51692. }
  51693. }
  51694. }
  51695. //iterate over the twelve edges of the cube to average across edges
  51696. for (i = 0; i < 12; i++) {
  51697. var face = PMREMGenerator._sgCubeEdgeList[i][0];
  51698. var edge = PMREMGenerator._sgCubeEdgeList[i][1];
  51699. var neighborFace = PMREMGenerator._sgCubeNgh[face][edge][0];
  51700. var neighborEdge = PMREMGenerator._sgCubeNgh[face][edge][1];
  51701. var edgeStartIndex = 0; // a_CubeMap[face].m_ImgData;
  51702. var neighborEdgeStartIndex = 0; // a_CubeMap[neighborFace].m_ImgData;
  51703. var edgeWalk = 0;
  51704. var neighborEdgeWalk = 0;
  51705. //Determine walking pointers based on edge type
  51706. // e.g. CP_EDGE_LEFT, CP_EDGE_RIGHT, CP_EDGE_TOP, CP_EDGE_BOTTOM
  51707. switch (edge) {
  51708. case PMREMGenerator.CP_EDGE_LEFT:
  51709. // no change to faceEdgeStartPtr
  51710. edgeWalk = this.numChannels * cubeMapSize;
  51711. break;
  51712. case PMREMGenerator.CP_EDGE_RIGHT:
  51713. edgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  51714. edgeWalk = this.numChannels * cubeMapSize;
  51715. break;
  51716. case PMREMGenerator.CP_EDGE_TOP:
  51717. // no change to faceEdgeStartPtr
  51718. edgeWalk = this.numChannels;
  51719. break;
  51720. case PMREMGenerator.CP_EDGE_BOTTOM:
  51721. edgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  51722. edgeWalk = this.numChannels;
  51723. break;
  51724. }
  51725. //For certain types of edge abutments, the neighbor edge walk needs to
  51726. // be flipped: the cases are
  51727. // if a left edge mates with a left or bottom edge on the neighbor
  51728. // if a top edge mates with a top or right edge on the neighbor
  51729. // if a right edge mates with a right or top edge on the neighbor
  51730. // if a bottom edge mates with a bottom or left edge on the neighbor
  51731. //Seeing as the edges are enumerated as follows
  51732. // left =0
  51733. // right =1
  51734. // top =2
  51735. // bottom =3
  51736. //
  51737. //If the edge enums are the same, or the sum of the enums == 3,
  51738. // the neighbor edge walk needs to be flipped
  51739. if ((edge == neighborEdge) || ((edge + neighborEdge) == 3)) {
  51740. switch (neighborEdge) {
  51741. case PMREMGenerator.CP_EDGE_LEFT:
  51742. neighborEdgeStartIndex += (cubeMapSize - 1) * (cubeMapSize) * this.numChannels;
  51743. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  51744. break;
  51745. case PMREMGenerator.CP_EDGE_RIGHT:
  51746. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  51747. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  51748. break;
  51749. case PMREMGenerator.CP_EDGE_TOP:
  51750. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  51751. neighborEdgeWalk = -this.numChannels;
  51752. break;
  51753. case PMREMGenerator.CP_EDGE_BOTTOM:
  51754. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  51755. neighborEdgeWalk = -this.numChannels;
  51756. break;
  51757. }
  51758. }
  51759. else {
  51760. //swapped direction neighbor edge walk
  51761. switch (neighborEdge) {
  51762. case PMREMGenerator.CP_EDGE_LEFT:
  51763. //no change to neighborEdgeStartPtr for this case since it points
  51764. // to the upper left corner already
  51765. neighborEdgeWalk = this.numChannels * cubeMapSize;
  51766. break;
  51767. case PMREMGenerator.CP_EDGE_RIGHT:
  51768. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  51769. neighborEdgeWalk = this.numChannels * cubeMapSize;
  51770. break;
  51771. case PMREMGenerator.CP_EDGE_TOP:
  51772. //no change to neighborEdgeStartPtr for this case since it points
  51773. // to the upper left corner already
  51774. neighborEdgeWalk = this.numChannels;
  51775. break;
  51776. case PMREMGenerator.CP_EDGE_BOTTOM:
  51777. neighborEdgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  51778. neighborEdgeWalk = this.numChannels;
  51779. break;
  51780. }
  51781. }
  51782. //Perform edge walk, to average across the 12 edges and smoothly propagate change to
  51783. //nearby neighborhood
  51784. //step ahead one texel on edge
  51785. edgeStartIndex += edgeWalk;
  51786. neighborEdgeStartIndex += neighborEdgeWalk;
  51787. // note that this loop does not process the corner texels, since they have already been
  51788. // averaged across faces across earlier
  51789. for (j = 1; j < (cubeMapSize - 1); j++) {
  51790. //for each set of taps along edge, average them
  51791. // and rewrite the results into the edges
  51792. for (k = 0; k < this.numChannels; k++) {
  51793. var edgeTap = cubeMap[face][edgeStartIndex + k];
  51794. var neighborEdgeTap = cubeMap[neighborFace][neighborEdgeStartIndex + k];
  51795. //compute average of tap intensity values
  51796. var avgTap = 0.5 * (edgeTap + neighborEdgeTap);
  51797. //propagate average of taps to edge taps
  51798. cubeMap[face][edgeStartIndex + k] = avgTap;
  51799. cubeMap[neighborFace][neighborEdgeStartIndex + k] = avgTap;
  51800. }
  51801. edgeStartIndex += edgeWalk;
  51802. neighborEdgeStartIndex += neighborEdgeWalk;
  51803. }
  51804. }
  51805. };
  51806. return PMREMGenerator;
  51807. }());
  51808. PMREMGenerator.CP_MAX_MIPLEVELS = 16;
  51809. PMREMGenerator.CP_UDIR = 0;
  51810. PMREMGenerator.CP_VDIR = 1;
  51811. PMREMGenerator.CP_FACEAXIS = 2;
  51812. //used to index cube faces
  51813. PMREMGenerator.CP_FACE_X_POS = 0;
  51814. PMREMGenerator.CP_FACE_X_NEG = 1;
  51815. PMREMGenerator.CP_FACE_Y_POS = 2;
  51816. PMREMGenerator.CP_FACE_Y_NEG = 3;
  51817. PMREMGenerator.CP_FACE_Z_POS = 4;
  51818. PMREMGenerator.CP_FACE_Z_NEG = 5;
  51819. //used to index image edges
  51820. // NOTE.. the actual number corresponding to the edge is important
  51821. // do not change these, or the code will break
  51822. //
  51823. // CP_EDGE_LEFT is u = 0
  51824. // CP_EDGE_RIGHT is u = width-1
  51825. // CP_EDGE_TOP is v = 0
  51826. // CP_EDGE_BOTTOM is v = height-1
  51827. PMREMGenerator.CP_EDGE_LEFT = 0;
  51828. PMREMGenerator.CP_EDGE_RIGHT = 1;
  51829. PMREMGenerator.CP_EDGE_TOP = 2;
  51830. PMREMGenerator.CP_EDGE_BOTTOM = 3;
  51831. //corners of CUBE map (P or N specifys if it corresponds to the
  51832. // positive or negative direction each of X, Y, and Z
  51833. PMREMGenerator.CP_CORNER_NNN = 0;
  51834. PMREMGenerator.CP_CORNER_NNP = 1;
  51835. PMREMGenerator.CP_CORNER_NPN = 2;
  51836. PMREMGenerator.CP_CORNER_NPP = 3;
  51837. PMREMGenerator.CP_CORNER_PNN = 4;
  51838. PMREMGenerator.CP_CORNER_PNP = 5;
  51839. PMREMGenerator.CP_CORNER_PPN = 6;
  51840. PMREMGenerator.CP_CORNER_PPP = 7;
  51841. PMREMGenerator._vectorTemp = new BABYLON.Vector4(0, 0, 0, 0);
  51842. //3x2 matrices that map cube map indexing vectors in 3d
  51843. // (after face selection and divide through by the
  51844. // _ABSOLUTE VALUE_ of the max coord)
  51845. // into NVC space
  51846. //Note this currently assumes the D3D cube face ordering and orientation
  51847. PMREMGenerator._sgFace2DMapping = [
  51848. //XPOS face
  51849. [[0, 0, -1],
  51850. [0, -1, 0],
  51851. [1, 0, 0]],
  51852. //XNEG face
  51853. [[0, 0, 1],
  51854. [0, -1, 0],
  51855. [-1, 0, 0]],
  51856. //YPOS face
  51857. [[1, 0, 0],
  51858. [0, 0, 1],
  51859. [0, 1, 0]],
  51860. //YNEG face
  51861. [[1, 0, 0],
  51862. [0, 0, -1],
  51863. [0, -1, 0]],
  51864. //ZPOS face
  51865. [[1, 0, 0],
  51866. [0, -1, 0],
  51867. [0, 0, 1]],
  51868. //ZNEG face
  51869. [[-1, 0, 0],
  51870. [0, -1, 0],
  51871. [0, 0, -1]],
  51872. ];
  51873. //------------------------------------------------------------------------------
  51874. // D3D cube map face specification
  51875. // mapping from 3D x,y,z cube map lookup coordinates
  51876. // to 2D within face u,v coordinates
  51877. //
  51878. // --------------------> U direction
  51879. // | (within-face texture space)
  51880. // | _____
  51881. // | | |
  51882. // | | +Y |
  51883. // | _____|_____|_____ _____
  51884. // | | | | | |
  51885. // | | -X | +Z | +X | -Z |
  51886. // | |_____|_____|_____|_____|
  51887. // | | |
  51888. // | | -Y |
  51889. // | |_____|
  51890. // |
  51891. // v V direction
  51892. // (within-face texture space)
  51893. //------------------------------------------------------------------------------
  51894. //Information about neighbors and how texture coorrdinates change across faces
  51895. // in ORDER of left, right, top, bottom (e.g. edges corresponding to u=0,
  51896. // u=1, v=0, v=1 in the 2D coordinate system of the particular face.
  51897. //Note this currently assumes the D3D cube face ordering and orientation
  51898. PMREMGenerator._sgCubeNgh = [
  51899. //XPOS face
  51900. [[PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_RIGHT],
  51901. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_LEFT],
  51902. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_RIGHT],
  51903. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_RIGHT]],
  51904. //XNEG face
  51905. [[PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  51906. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_LEFT],
  51907. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_LEFT],
  51908. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_LEFT]],
  51909. //YPOS face
  51910. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  51911. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  51912. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  51913. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP]],
  51914. //YNEG face
  51915. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  51916. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  51917. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  51918. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]],
  51919. //ZPOS face
  51920. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  51921. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  51922. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  51923. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_TOP]],
  51924. //ZNEG face
  51925. [[PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  51926. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  51927. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_TOP],
  51928. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_BOTTOM]]
  51929. ];
  51930. //The 12 edges of the cubemap, (entries are used to index into the neighbor table)
  51931. // this table is used to average over the edges.
  51932. PMREMGenerator._sgCubeEdgeList = [
  51933. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  51934. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  51935. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  51936. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  51937. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  51938. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  51939. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  51940. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  51941. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP],
  51942. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  51943. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  51944. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]
  51945. ];
  51946. //Information about which of the 8 cube corners are correspond to the
  51947. // the 4 corners in each cube face
  51948. // the order is upper left, upper right, lower left, lower right
  51949. PMREMGenerator._sgCubeCornerList = [
  51950. [PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_PNN],
  51951. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_NNP],
  51952. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP],
  51953. [PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_PNN],
  51954. [PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP],
  51955. [PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PNN, PMREMGenerator.CP_CORNER_NNN] // ZNEG face
  51956. ];
  51957. Internals.PMREMGenerator = PMREMGenerator;
  51958. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  51959. })(BABYLON || (BABYLON = {}));
  51960. //# sourceMappingURL=babylon.pmremgenerator.js.map
  51961. var BABYLON;
  51962. (function (BABYLON) {
  51963. /**
  51964. * This represents a texture coming from an HDR input.
  51965. *
  51966. * The only supported format is currently panorama picture stored in RGBE format.
  51967. * Example of such files can be found on HDRLib: http://hdrlib.com/
  51968. */
  51969. var HDRCubeTexture = (function (_super) {
  51970. __extends(HDRCubeTexture, _super);
  51971. /**
  51972. * Instantiates an HDRTexture from the following parameters.
  51973. *
  51974. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  51975. * @param scene The scene the texture will be used in
  51976. * @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.
  51977. * @param noMipmap Forces to not generate the mipmap if true
  51978. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  51979. * @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)
  51980. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  51981. */
  51982. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  51983. if (noMipmap === void 0) { noMipmap = false; }
  51984. if (generateHarmonics === void 0) { generateHarmonics = true; }
  51985. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  51986. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  51987. if (onLoad === void 0) { onLoad = null; }
  51988. if (onError === void 0) { onError = null; }
  51989. var _this = _super.call(this, scene) || this;
  51990. _this._useInGammaSpace = false;
  51991. _this._generateHarmonics = true;
  51992. _this._isBABYLONPreprocessed = false;
  51993. _this._onLoad = null;
  51994. _this._onError = null;
  51995. /**
  51996. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  51997. */
  51998. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  51999. /**
  52000. * The spherical polynomial data extracted from the texture.
  52001. */
  52002. _this.sphericalPolynomial = null;
  52003. /**
  52004. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  52005. * This is usefull at run time to apply the good shader.
  52006. */
  52007. _this.isPMREM = false;
  52008. if (!url) {
  52009. return _this;
  52010. }
  52011. _this.name = url;
  52012. _this.url = url;
  52013. _this.hasAlpha = false;
  52014. _this.isCube = true;
  52015. _this._textureMatrix = BABYLON.Matrix.Identity();
  52016. _this._onLoad = onLoad;
  52017. _this._onError = onError;
  52018. if (size) {
  52019. _this._isBABYLONPreprocessed = false;
  52020. _this._noMipmap = noMipmap;
  52021. _this._size = size;
  52022. _this._useInGammaSpace = useInGammaSpace;
  52023. _this._usePMREMGenerator = usePMREMGenerator &&
  52024. scene.getEngine().getCaps().textureLOD &&
  52025. _this.getScene().getEngine().getCaps().textureFloat &&
  52026. !_this._useInGammaSpace;
  52027. }
  52028. else {
  52029. _this._isBABYLONPreprocessed = true;
  52030. _this._noMipmap = false;
  52031. _this._useInGammaSpace = false;
  52032. _this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD &&
  52033. _this.getScene().getEngine().getCaps().textureFloat &&
  52034. !_this._useInGammaSpace;
  52035. }
  52036. _this.isPMREM = _this._usePMREMGenerator;
  52037. _this._texture = _this._getFromCache(url, _this._noMipmap);
  52038. if (!_this._texture) {
  52039. if (!scene.useDelayedTextureLoading) {
  52040. _this.loadTexture();
  52041. }
  52042. else {
  52043. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  52044. }
  52045. }
  52046. return _this;
  52047. }
  52048. /**
  52049. * Occurs when the file is a preprocessed .babylon.hdr file.
  52050. */
  52051. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  52052. var _this = this;
  52053. var mipLevels = 0;
  52054. var floatArrayView = null;
  52055. var mipmapGenerator = (!this._useInGammaSpace && this.getScene().getEngine().getCaps().textureFloat) ? function (data) {
  52056. var mips = [];
  52057. var startIndex = 30;
  52058. for (var level = 0; level < mipLevels; level++) {
  52059. mips.push([]);
  52060. // Fill each pixel of the mip level.
  52061. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  52062. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  52063. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  52064. mips[level].push(faceData);
  52065. startIndex += faceSize;
  52066. }
  52067. }
  52068. return mips;
  52069. } : null;
  52070. var callback = function (buffer) {
  52071. // Create Native Array Views
  52072. var intArrayView = new Int32Array(buffer);
  52073. floatArrayView = new Float32Array(buffer);
  52074. // Fill header.
  52075. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  52076. _this._size = intArrayView[1]; // CubeMap max mip face size.
  52077. // Update Texture Information.
  52078. _this.getScene().getEngine().updateTextureSize(_this._texture, _this._size, _this._size);
  52079. // Fill polynomial information.
  52080. _this.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  52081. _this.sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  52082. _this.sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  52083. _this.sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  52084. _this.sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  52085. _this.sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  52086. _this.sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  52087. _this.sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  52088. _this.sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  52089. _this.sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  52090. // Fill pixel data.
  52091. mipLevels = intArrayView[29]; // Number of mip levels.
  52092. var startIndex = 30;
  52093. var data = [];
  52094. var faceSize = Math.pow(_this._size, 2) * 3;
  52095. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  52096. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  52097. startIndex += faceSize;
  52098. }
  52099. var results = [];
  52100. var byteArray = null;
  52101. // Push each faces.
  52102. for (var k = 0; k < 6; k++) {
  52103. var dataFace = null;
  52104. // If special cases.
  52105. if (!mipmapGenerator) {
  52106. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y... if no mipmapgenerator...
  52107. dataFace = data[j];
  52108. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  52109. // 3 channels of 1 bytes per pixel in bytes.
  52110. var byteBuffer = new ArrayBuffer(faceSize);
  52111. byteArray = new Uint8Array(byteBuffer);
  52112. }
  52113. for (var i = 0; i < _this._size * _this._size; i++) {
  52114. // Put in gamma space if requested.
  52115. if (_this._useInGammaSpace) {
  52116. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  52117. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  52118. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  52119. }
  52120. // Convert to int texture for fallback.
  52121. if (byteArray) {
  52122. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  52123. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  52124. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  52125. // May use luminance instead if the result is not accurate.
  52126. var max = Math.max(Math.max(r, g), b);
  52127. if (max > 255) {
  52128. var scale = 255 / max;
  52129. r *= scale;
  52130. g *= scale;
  52131. b *= scale;
  52132. }
  52133. byteArray[(i * 3) + 0] = r;
  52134. byteArray[(i * 3) + 1] = g;
  52135. byteArray[(i * 3) + 2] = b;
  52136. }
  52137. }
  52138. }
  52139. else {
  52140. dataFace = data[k];
  52141. }
  52142. // Fill the array accordingly.
  52143. if (byteArray) {
  52144. results.push(byteArray);
  52145. }
  52146. else {
  52147. results.push(dataFace);
  52148. }
  52149. }
  52150. return results;
  52151. };
  52152. 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);
  52153. };
  52154. /**
  52155. * Occurs when the file is raw .hdr file.
  52156. */
  52157. HDRCubeTexture.prototype.loadHDRTexture = function () {
  52158. var _this = this;
  52159. var callback = function (buffer) {
  52160. // Extract the raw linear data.
  52161. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  52162. // Generate harmonics if needed.
  52163. if (_this._generateHarmonics) {
  52164. _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  52165. }
  52166. var results = [];
  52167. var byteArray = null;
  52168. // Push each faces.
  52169. for (var j = 0; j < 6; j++) {
  52170. // Create uintarray fallback.
  52171. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  52172. // 3 channels of 1 bytes per pixel in bytes.
  52173. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  52174. byteArray = new Uint8Array(byteBuffer);
  52175. }
  52176. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  52177. // If special cases.
  52178. if (_this._useInGammaSpace || byteArray) {
  52179. for (var i = 0; i < _this._size * _this._size; i++) {
  52180. // Put in gamma space if requested.
  52181. if (_this._useInGammaSpace) {
  52182. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  52183. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  52184. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  52185. }
  52186. // Convert to int texture for fallback.
  52187. if (byteArray) {
  52188. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  52189. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  52190. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  52191. // May use luminance instead if the result is not accurate.
  52192. var max = Math.max(Math.max(r, g), b);
  52193. if (max > 255) {
  52194. var scale = 255 / max;
  52195. r *= scale;
  52196. g *= scale;
  52197. b *= scale;
  52198. }
  52199. byteArray[(i * 3) + 0] = r;
  52200. byteArray[(i * 3) + 1] = g;
  52201. byteArray[(i * 3) + 2] = b;
  52202. }
  52203. }
  52204. }
  52205. if (byteArray) {
  52206. results.push(byteArray);
  52207. }
  52208. else {
  52209. results.push(dataFace);
  52210. }
  52211. }
  52212. return results;
  52213. };
  52214. var mipmapGenerator = null;
  52215. if (!this._noMipmap &&
  52216. this._usePMREMGenerator) {
  52217. mipmapGenerator = function (data) {
  52218. // Custom setup of the generator matching with the PBR shader values.
  52219. var generator = new BABYLON.Internals.PMREMGenerator(data, _this._size, _this._size, 0, 3, _this.getScene().getEngine().getCaps().textureFloat, 2048, 0.25, false, true);
  52220. return generator.filterCubeMap();
  52221. };
  52222. }
  52223. 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);
  52224. };
  52225. /**
  52226. * Starts the loading process of the texture.
  52227. */
  52228. HDRCubeTexture.prototype.loadTexture = function () {
  52229. if (this._isBABYLONPreprocessed) {
  52230. this.loadBabylonTexture();
  52231. }
  52232. else {
  52233. this.loadHDRTexture();
  52234. }
  52235. };
  52236. HDRCubeTexture.prototype.clone = function () {
  52237. var size = this._isBABYLONPreprocessed ? null : this._size;
  52238. var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  52239. // Base texture
  52240. newTexture.level = this.level;
  52241. newTexture.wrapU = this.wrapU;
  52242. newTexture.wrapV = this.wrapV;
  52243. newTexture.coordinatesIndex = this.coordinatesIndex;
  52244. newTexture.coordinatesMode = this.coordinatesMode;
  52245. return newTexture;
  52246. };
  52247. // Methods
  52248. HDRCubeTexture.prototype.delayLoad = function () {
  52249. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  52250. return;
  52251. }
  52252. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  52253. this._texture = this._getFromCache(this.url, this._noMipmap);
  52254. if (!this._texture) {
  52255. this.loadTexture();
  52256. }
  52257. };
  52258. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  52259. return this._textureMatrix;
  52260. };
  52261. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  52262. var texture = null;
  52263. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  52264. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  52265. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  52266. texture.name = parsedTexture.name;
  52267. texture.hasAlpha = parsedTexture.hasAlpha;
  52268. texture.level = parsedTexture.level;
  52269. texture.coordinatesMode = parsedTexture.coordinatesMode;
  52270. }
  52271. return texture;
  52272. };
  52273. HDRCubeTexture.prototype.serialize = function () {
  52274. if (!this.name) {
  52275. return null;
  52276. }
  52277. var serializationObject = {};
  52278. serializationObject.name = this.name;
  52279. serializationObject.hasAlpha = this.hasAlpha;
  52280. serializationObject.isCube = true;
  52281. serializationObject.level = this.level;
  52282. serializationObject.size = this._size;
  52283. serializationObject.coordinatesMode = this.coordinatesMode;
  52284. serializationObject.useInGammaSpace = this._useInGammaSpace;
  52285. serializationObject.generateHarmonics = this._generateHarmonics;
  52286. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  52287. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  52288. serializationObject.customType = "BABYLON.HDRCubeTexture";
  52289. serializationObject.noMipmap = this._noMipmap;
  52290. return serializationObject;
  52291. };
  52292. /**
  52293. * Saves as a file the data contained in the texture in a binary format.
  52294. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  52295. * as the spherical used in the lighting.
  52296. * @param url The HDR file url.
  52297. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  52298. * @param onError Method called if any error happens during download.
  52299. * @return The packed binary data.
  52300. */
  52301. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  52302. if (onError === void 0) { onError = null; }
  52303. var callback = function (buffer) {
  52304. var data = new Blob([buffer], { type: 'application/octet-stream' });
  52305. // Returns a URL you can use as a href.
  52306. var objUrl = window.URL.createObjectURL(data);
  52307. // Simulates a link to it and click to dowload.
  52308. var a = document.createElement("a");
  52309. document.body.appendChild(a);
  52310. a.style.display = "none";
  52311. a.href = objUrl;
  52312. a.download = "envmap.babylon.hdr";
  52313. a.click();
  52314. };
  52315. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  52316. };
  52317. /**
  52318. * Serializes the data contained in the texture in a binary format.
  52319. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  52320. * as the spherical used in the lighting.
  52321. * @param url The HDR file url.
  52322. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  52323. * @param onError Method called if any error happens during download.
  52324. * @return The packed binary data.
  52325. */
  52326. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  52327. if (onError === void 0) { onError = null; }
  52328. // Needs the url tho create the texture.
  52329. if (!url) {
  52330. return null;
  52331. }
  52332. // Check Power of two size.
  52333. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  52334. return null;
  52335. }
  52336. var getDataCallback = function (dataBuffer) {
  52337. // Extract the raw linear data.
  52338. var cubeData = BABYLON.Internals.HDRTools.GetCubeMapTextureData(dataBuffer, size);
  52339. // Generate harmonics if needed.
  52340. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(cubeData);
  52341. // Generate seamless faces
  52342. var mipGeneratorArray = [];
  52343. // Data are known to be in +X +Y +Z -X -Y -Z
  52344. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  52345. mipGeneratorArray.push(cubeData.right); // +X
  52346. mipGeneratorArray.push(cubeData.left); // -X
  52347. mipGeneratorArray.push(cubeData.up); // +Y
  52348. mipGeneratorArray.push(cubeData.down); // -Y
  52349. mipGeneratorArray.push(cubeData.front); // +Z
  52350. mipGeneratorArray.push(cubeData.back); // -Z
  52351. // Custom setup of the generator matching with the PBR shader values.
  52352. var generator = new BABYLON.Internals.PMREMGenerator(mipGeneratorArray, size, size, 0, 3, true, 2048, 0.25, false, true);
  52353. var mippedData = generator.filterCubeMap();
  52354. // Compute required byte length.
  52355. var byteLength = 1 * 4; // Raw Data Version int32.
  52356. byteLength += 4; // CubeMap max mip face size int32.
  52357. byteLength += (9 * 3 * 4); // Spherical polynomial byte length 9 Vector 3 of floats.
  52358. // Add data size.
  52359. byteLength += 4; // Number of mip levels int32.
  52360. for (var level = 0; level < mippedData.length; level++) {
  52361. var mipSize = size >> level;
  52362. byteLength += (6 * mipSize * mipSize * 3 * 4); // 6 faces of size squared rgb float pixels.
  52363. }
  52364. // Prepare binary structure.
  52365. var buffer = new ArrayBuffer(byteLength);
  52366. var intArrayView = new Int32Array(buffer);
  52367. var floatArrayView = new Float32Array(buffer);
  52368. // Fill header.
  52369. intArrayView[0] = 1; // Version 1.
  52370. intArrayView[1] = size; // CubeMap max mip face size.
  52371. // Fill polynomial information.
  52372. sphericalPolynomial.x.toArray(floatArrayView, 2);
  52373. sphericalPolynomial.y.toArray(floatArrayView, 5);
  52374. sphericalPolynomial.z.toArray(floatArrayView, 8);
  52375. sphericalPolynomial.xx.toArray(floatArrayView, 11);
  52376. sphericalPolynomial.yy.toArray(floatArrayView, 14);
  52377. sphericalPolynomial.zz.toArray(floatArrayView, 17);
  52378. sphericalPolynomial.xy.toArray(floatArrayView, 20);
  52379. sphericalPolynomial.yz.toArray(floatArrayView, 23);
  52380. sphericalPolynomial.zx.toArray(floatArrayView, 26);
  52381. // Fill pixel data.
  52382. intArrayView[29] = mippedData.length; // Number of mip levels.
  52383. var startIndex = 30;
  52384. for (var level = 0; level < mippedData.length; level++) {
  52385. // Fill each pixel of the mip level.
  52386. var faceSize = Math.pow(size >> level, 2) * 3;
  52387. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  52388. floatArrayView.set(mippedData[level][faceIndex], startIndex);
  52389. startIndex += faceSize;
  52390. }
  52391. }
  52392. // Callback.
  52393. callback(buffer);
  52394. };
  52395. // Download and process.
  52396. BABYLON.Tools.LoadFile(url, function (data) {
  52397. getDataCallback(data);
  52398. }, null, null, true, onError);
  52399. };
  52400. return HDRCubeTexture;
  52401. }(BABYLON.BaseTexture));
  52402. HDRCubeTexture._facesMapping = [
  52403. "right",
  52404. "up",
  52405. "front",
  52406. "left",
  52407. "down",
  52408. "back"
  52409. ];
  52410. BABYLON.HDRCubeTexture = HDRCubeTexture;
  52411. })(BABYLON || (BABYLON = {}));
  52412. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  52413. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  52414. // Huge respect for a such great lib.
  52415. // Earcut license:
  52416. // Copyright (c) 2016, Mapbox
  52417. //
  52418. // Permission to use, copy, modify, and/or distribute this software for any purpose
  52419. // with or without fee is hereby granted, provided that the above copyright notice
  52420. // and this permission notice appear in all copies.
  52421. //
  52422. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  52423. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  52424. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  52425. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  52426. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  52427. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  52428. // THIS SOFTWARE.
  52429. var Earcut;
  52430. (function (Earcut) {
  52431. /**
  52432. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  52433. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  52434. * @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).
  52435. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  52436. */
  52437. function earcut(data, holeIndices, dim) {
  52438. dim = dim || 2;
  52439. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = [];
  52440. if (!outerNode)
  52441. return triangles;
  52442. var minX, minY, maxX, maxY, x, y, size;
  52443. if (hasHoles)
  52444. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  52445. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  52446. if (data.length > 80 * dim) {
  52447. minX = maxX = data[0];
  52448. minY = maxY = data[1];
  52449. for (var i = dim; i < outerLen; i += dim) {
  52450. x = data[i];
  52451. y = data[i + 1];
  52452. if (x < minX)
  52453. minX = x;
  52454. if (y < minY)
  52455. minY = y;
  52456. if (x > maxX)
  52457. maxX = x;
  52458. if (y > maxY)
  52459. maxY = y;
  52460. }
  52461. // minX, minY and size are later used to transform coords into integers for z-order calculation
  52462. size = Math.max(maxX - minX, maxY - minY);
  52463. }
  52464. earcutLinked(outerNode, triangles, dim, minX, minY, size, undefined);
  52465. return triangles;
  52466. }
  52467. Earcut.earcut = earcut;
  52468. // create a circular doubly linked list from polygon points in the specified winding order
  52469. function linkedList(data, start, end, dim, clockwise) {
  52470. var i, last;
  52471. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  52472. for (i = start; i < end; i += dim)
  52473. last = insertNode(i, data[i], data[i + 1], last);
  52474. }
  52475. else {
  52476. for (i = end - dim; i >= start; i -= dim)
  52477. last = insertNode(i, data[i], data[i + 1], last);
  52478. }
  52479. if (last && equals(last, last.next)) {
  52480. removeNode(last);
  52481. last = last.next;
  52482. }
  52483. return last;
  52484. }
  52485. // eliminate colinear or duplicate points
  52486. function filterPoints(start, end) {
  52487. if (!start)
  52488. return start;
  52489. if (!end)
  52490. end = start;
  52491. var p = start, again;
  52492. do {
  52493. again = false;
  52494. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  52495. removeNode(p);
  52496. p = end = p.prev;
  52497. if (p === p.next)
  52498. return null;
  52499. again = true;
  52500. }
  52501. else {
  52502. p = p.next;
  52503. }
  52504. } while (again || p !== end);
  52505. return end;
  52506. }
  52507. // main ear slicing loop which triangulates a polygon (given as a linked list)
  52508. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  52509. if (!ear)
  52510. return;
  52511. // interlink polygon nodes in z-order
  52512. if (!pass && size)
  52513. indexCurve(ear, minX, minY, size);
  52514. var stop = ear, prev, next;
  52515. // iterate through ears, slicing them one by one
  52516. while (ear.prev !== ear.next) {
  52517. prev = ear.prev;
  52518. next = ear.next;
  52519. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  52520. // cut off the triangle
  52521. triangles.push(prev.i / dim);
  52522. triangles.push(ear.i / dim);
  52523. triangles.push(next.i / dim);
  52524. removeNode(ear);
  52525. // skipping the next vertice leads to less sliver triangles
  52526. ear = next.next;
  52527. stop = next.next;
  52528. continue;
  52529. }
  52530. ear = next;
  52531. // if we looped through the whole remaining polygon and can't find any more ears
  52532. if (ear === stop) {
  52533. // try filtering points and slicing again
  52534. if (!pass) {
  52535. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  52536. // if this didn't work, try curing all small self-intersections locally
  52537. }
  52538. else if (pass === 1) {
  52539. ear = cureLocalIntersections(ear, triangles, dim);
  52540. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  52541. // as a last resort, try splitting the remaining polygon into two
  52542. }
  52543. else if (pass === 2) {
  52544. splitEarcut(ear, triangles, dim, minX, minY, size);
  52545. }
  52546. break;
  52547. }
  52548. }
  52549. }
  52550. // check whether a polygon node forms a valid ear with adjacent nodes
  52551. function isEar(ear) {
  52552. var a = ear.prev, b = ear, c = ear.next;
  52553. if (area(a, b, c) >= 0)
  52554. return false; // reflex, can't be an ear
  52555. // now make sure we don't have other points inside the potential ear
  52556. var p = ear.next.next;
  52557. while (p !== ear.prev) {
  52558. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  52559. area(p.prev, p, p.next) >= 0)
  52560. return false;
  52561. p = p.next;
  52562. }
  52563. return true;
  52564. }
  52565. function isEarHashed(ear, minX, minY, size) {
  52566. var a = ear.prev, b = ear, c = ear.next;
  52567. if (area(a, b, c) >= 0)
  52568. return false; // reflex, can't be an ear
  52569. // triangle bbox; min & max are calculated like this for speed
  52570. 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);
  52571. // z-order range for the current triangle bbox;
  52572. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  52573. // first look for points inside the triangle in increasing z-order
  52574. var p = ear.nextZ;
  52575. while (p && p.z <= maxZ) {
  52576. if (p !== ear.prev &&
  52577. p !== ear.next &&
  52578. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  52579. area(p.prev, p, p.next) >= 0)
  52580. return false;
  52581. p = p.nextZ;
  52582. }
  52583. // then look for points in decreasing z-order
  52584. p = ear.prevZ;
  52585. while (p && p.z >= minZ) {
  52586. if (p !== ear.prev &&
  52587. p !== ear.next &&
  52588. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  52589. area(p.prev, p, p.next) >= 0)
  52590. return false;
  52591. p = p.prevZ;
  52592. }
  52593. return true;
  52594. }
  52595. // go through all polygon nodes and cure small local self-intersections
  52596. function cureLocalIntersections(start, triangles, dim) {
  52597. var p = start;
  52598. do {
  52599. var a = p.prev, b = p.next.next;
  52600. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  52601. triangles.push(a.i / dim);
  52602. triangles.push(p.i / dim);
  52603. triangles.push(b.i / dim);
  52604. // remove two nodes involved
  52605. removeNode(p);
  52606. removeNode(p.next);
  52607. p = start = b;
  52608. }
  52609. p = p.next;
  52610. } while (p !== start);
  52611. return p;
  52612. }
  52613. // try splitting polygon into two and triangulate them independently
  52614. function splitEarcut(start, triangles, dim, minX, minY, size) {
  52615. // look for a valid diagonal that divides the polygon into two
  52616. var a = start;
  52617. do {
  52618. var b = a.next.next;
  52619. while (b !== a.prev) {
  52620. if (a.i !== b.i && isValidDiagonal(a, b)) {
  52621. // split the polygon in two by the diagonal
  52622. var c = splitPolygon(a, b);
  52623. // filter colinear points around the cuts
  52624. a = filterPoints(a, a.next);
  52625. c = filterPoints(c, c.next);
  52626. // run earcut on each half
  52627. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  52628. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  52629. return;
  52630. }
  52631. b = b.next;
  52632. }
  52633. a = a.next;
  52634. } while (a !== start);
  52635. }
  52636. // link every hole into the outer loop, producing a single-ring polygon without holes
  52637. function eliminateHoles(data, holeIndices, outerNode, dim) {
  52638. var queue = [], i, len, start, end, list;
  52639. for (i = 0, len = holeIndices.length; i < len; i++) {
  52640. start = holeIndices[i] * dim;
  52641. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  52642. list = linkedList(data, start, end, dim, false);
  52643. if (list === list.next)
  52644. list.steiner = true;
  52645. queue.push(getLeftmost(list));
  52646. }
  52647. queue.sort(compareX);
  52648. // process holes from left to right
  52649. for (i = 0; i < queue.length; i++) {
  52650. eliminateHole(queue[i], outerNode);
  52651. outerNode = filterPoints(outerNode, outerNode.next);
  52652. }
  52653. return outerNode;
  52654. }
  52655. function compareX(a, b) {
  52656. return a.x - b.x;
  52657. }
  52658. // find a bridge between vertices that connects hole with an outer ring and and link it
  52659. function eliminateHole(hole, outerNode) {
  52660. outerNode = findHoleBridge(hole, outerNode);
  52661. if (outerNode) {
  52662. var b = splitPolygon(outerNode, hole);
  52663. filterPoints(b, b.next);
  52664. }
  52665. }
  52666. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  52667. function findHoleBridge(hole, outerNode) {
  52668. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  52669. // find a segment intersected by a ray from the hole's leftmost point to the left;
  52670. // segment's endpoint with lesser x will be potential connection point
  52671. do {
  52672. if (hy <= p.y && hy >= p.next.y) {
  52673. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  52674. if (x <= hx && x > qx) {
  52675. qx = x;
  52676. if (x === hx) {
  52677. if (hy === p.y)
  52678. return p;
  52679. if (hy === p.next.y)
  52680. return p.next;
  52681. }
  52682. m = p.x < p.next.x ? p : p.next;
  52683. }
  52684. }
  52685. p = p.next;
  52686. } while (p !== outerNode);
  52687. if (!m)
  52688. return null;
  52689. if (hx === qx)
  52690. return m.prev; // hole touches outer segment; pick lower endpoint
  52691. // look for points inside the triangle of hole point, segment intersection and endpoint;
  52692. // if there are no points found, we have a valid connection;
  52693. // otherwise choose the point of the minimum angle with the ray as connection point
  52694. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  52695. p = m.next;
  52696. while (p !== stop) {
  52697. if (hx >= p.x &&
  52698. p.x >= mx &&
  52699. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  52700. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  52701. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  52702. m = p;
  52703. tanMin = tan;
  52704. }
  52705. }
  52706. p = p.next;
  52707. }
  52708. return m;
  52709. }
  52710. // interlink polygon nodes in z-order
  52711. function indexCurve(start, minX, minY, size) {
  52712. var p = start;
  52713. do {
  52714. if (p.z === null)
  52715. p.z = zOrder(p.x, p.y, minX, minY, size);
  52716. p.prevZ = p.prev;
  52717. p.nextZ = p.next;
  52718. p = p.next;
  52719. } while (p !== start);
  52720. p.prevZ.nextZ = null;
  52721. p.prevZ = null;
  52722. sortLinked(p);
  52723. }
  52724. // Simon Tatham's linked list merge sort algorithm
  52725. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  52726. function sortLinked(list) {
  52727. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  52728. do {
  52729. p = list;
  52730. list = null;
  52731. tail = null;
  52732. numMerges = 0;
  52733. while (p) {
  52734. numMerges++;
  52735. q = p;
  52736. pSize = 0;
  52737. for (i = 0; i < inSize; i++) {
  52738. pSize++;
  52739. q = q.nextZ;
  52740. if (!q)
  52741. break;
  52742. }
  52743. qSize = inSize;
  52744. while (pSize > 0 || (qSize > 0 && q)) {
  52745. if (pSize === 0) {
  52746. e = q;
  52747. q = q.nextZ;
  52748. qSize--;
  52749. }
  52750. else if (qSize === 0 || !q) {
  52751. e = p;
  52752. p = p.nextZ;
  52753. pSize--;
  52754. }
  52755. else if (p.z <= q.z) {
  52756. e = p;
  52757. p = p.nextZ;
  52758. pSize--;
  52759. }
  52760. else {
  52761. e = q;
  52762. q = q.nextZ;
  52763. qSize--;
  52764. }
  52765. if (tail)
  52766. tail.nextZ = e;
  52767. else
  52768. list = e;
  52769. e.prevZ = tail;
  52770. tail = e;
  52771. }
  52772. p = q;
  52773. }
  52774. tail.nextZ = null;
  52775. inSize *= 2;
  52776. } while (numMerges > 1);
  52777. return list;
  52778. }
  52779. // z-order of a point given coords and size of the data bounding box
  52780. function zOrder(x, y, minX, minY, size) {
  52781. // coords are transformed into non-negative 15-bit integer range
  52782. x = 32767 * (x - minX) / size;
  52783. y = 32767 * (y - minY) / size;
  52784. x = (x | (x << 8)) & 0x00FF00FF;
  52785. x = (x | (x << 4)) & 0x0F0F0F0F;
  52786. x = (x | (x << 2)) & 0x33333333;
  52787. x = (x | (x << 1)) & 0x55555555;
  52788. y = (y | (y << 8)) & 0x00FF00FF;
  52789. y = (y | (y << 4)) & 0x0F0F0F0F;
  52790. y = (y | (y << 2)) & 0x33333333;
  52791. y = (y | (y << 1)) & 0x55555555;
  52792. return x | (y << 1);
  52793. }
  52794. // find the leftmost node of a polygon ring
  52795. function getLeftmost(start) {
  52796. var p = start, leftmost = start;
  52797. do {
  52798. if (p.x < leftmost.x)
  52799. leftmost = p;
  52800. p = p.next;
  52801. } while (p !== start);
  52802. return leftmost;
  52803. }
  52804. // check if a point lies within a convex triangle
  52805. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  52806. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  52807. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  52808. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  52809. }
  52810. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  52811. function isValidDiagonal(a, b) {
  52812. return a.next.i !== b.i &&
  52813. a.prev.i !== b.i &&
  52814. !intersectsPolygon(a, b) &&
  52815. locallyInside(a, b) &&
  52816. locallyInside(b, a) &&
  52817. middleInside(a, b);
  52818. }
  52819. // signed area of a triangle
  52820. function area(p, q, r) {
  52821. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  52822. }
  52823. // check if two points are equal
  52824. function equals(p1, p2) {
  52825. return p1.x === p2.x && p1.y === p2.y;
  52826. }
  52827. // check if two segments intersect
  52828. function intersects(p1, q1, p2, q2) {
  52829. if ((equals(p1, q1) && equals(p2, q2)) ||
  52830. (equals(p1, q2) && equals(p2, q1)))
  52831. return true;
  52832. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  52833. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  52834. }
  52835. // check if a polygon diagonal intersects any polygon segments
  52836. function intersectsPolygon(a, b) {
  52837. var p = a;
  52838. do {
  52839. if (p.i !== a.i &&
  52840. p.next.i !== a.i &&
  52841. p.i !== b.i &&
  52842. p.next.i !== b.i &&
  52843. intersects(p, p.next, a, b))
  52844. return true;
  52845. p = p.next;
  52846. } while (p !== a);
  52847. return false;
  52848. }
  52849. // check if a polygon diagonal is locally inside the polygon
  52850. function locallyInside(a, b) {
  52851. return area(a.prev, a, a.next) < 0
  52852. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  52853. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  52854. }
  52855. // check if the middle point of a polygon diagonal is inside the polygon
  52856. function middleInside(a, b) {
  52857. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  52858. do {
  52859. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  52860. inside = !inside;
  52861. p = p.next;
  52862. } while (p !== a);
  52863. return inside;
  52864. }
  52865. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  52866. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  52867. function splitPolygon(a, b) {
  52868. 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;
  52869. a.next = b;
  52870. b.prev = a;
  52871. a2.next = an;
  52872. an.prev = a2;
  52873. b2.next = a2;
  52874. a2.prev = b2;
  52875. bp.next = b2;
  52876. b2.prev = bp;
  52877. return b2;
  52878. }
  52879. // create a node and optionally link it with previous one (in a circular doubly linked list)
  52880. function insertNode(i, x, y, last) {
  52881. var p = new Node(i, x, y);
  52882. if (!last) {
  52883. p.prev = p;
  52884. p.next = p;
  52885. }
  52886. else {
  52887. p.next = last.next;
  52888. p.prev = last;
  52889. last.next.prev = p;
  52890. last.next = p;
  52891. }
  52892. return p;
  52893. }
  52894. function removeNode(p) {
  52895. p.next.prev = p.prev;
  52896. p.prev.next = p.next;
  52897. if (p.prevZ)
  52898. p.prevZ.nextZ = p.nextZ;
  52899. if (p.nextZ)
  52900. p.nextZ.prevZ = p.prevZ;
  52901. }
  52902. function Node(i, x, y) {
  52903. // vertice index in coordinates array
  52904. this.i = i;
  52905. // vertex coordinates
  52906. this.x = x;
  52907. this.y = y;
  52908. // previous and next vertice nodes in a polygon ring
  52909. this.prev = null;
  52910. this.next = null;
  52911. // z-order curve value
  52912. this.z = null;
  52913. // previous and next nodes in z-order
  52914. this.prevZ = null;
  52915. this.nextZ = null;
  52916. // indicates whether this is a steiner point
  52917. this.steiner = false;
  52918. }
  52919. /**
  52920. * return a percentage difference between the polygon area and its triangulation area;
  52921. * used to verify correctness of triangulation
  52922. */
  52923. function deviation(data, holeIndices, dim, triangles) {
  52924. var hasHoles = holeIndices && holeIndices.length;
  52925. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  52926. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  52927. if (hasHoles) {
  52928. for (var i = 0, len = holeIndices.length; i < len; i++) {
  52929. var start = holeIndices[i] * dim;
  52930. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  52931. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  52932. }
  52933. }
  52934. var trianglesArea = 0;
  52935. for (i = 0; i < triangles.length; i += 3) {
  52936. var a = triangles[i] * dim;
  52937. var b = triangles[i + 1] * dim;
  52938. var c = triangles[i + 2] * dim;
  52939. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  52940. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  52941. }
  52942. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  52943. }
  52944. Earcut.deviation = deviation;
  52945. ;
  52946. function signedArea(data, start, end, dim) {
  52947. var sum = 0;
  52948. for (var i = start, j = end - dim; i < end; i += dim) {
  52949. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  52950. j = i;
  52951. }
  52952. return sum;
  52953. }
  52954. /**
  52955. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  52956. */
  52957. function flatten(data) {
  52958. var dim = data[0][0].length, result = { vertices: [], holes: [], dimensions: dim }, holeIndex = 0;
  52959. for (var i = 0; i < data.length; i++) {
  52960. for (var j = 0; j < data[i].length; j++) {
  52961. for (var d = 0; d < dim; d++)
  52962. result.vertices.push(data[i][j][d]);
  52963. }
  52964. if (i > 0) {
  52965. holeIndex += data[i - 1].length;
  52966. result.holes.push(holeIndex);
  52967. }
  52968. }
  52969. return result;
  52970. }
  52971. Earcut.flatten = flatten;
  52972. ;
  52973. })(Earcut || (Earcut = {}));
  52974. //# sourceMappingURL=babylon.earcut.js.map
  52975. /// <reference path="..\Math\babylon.math.ts" />
  52976. var BABYLON;
  52977. (function (BABYLON) {
  52978. var IndexedVector2 = (function (_super) {
  52979. __extends(IndexedVector2, _super);
  52980. function IndexedVector2(original, index) {
  52981. var _this = _super.call(this, original.x, original.y) || this;
  52982. _this.index = index;
  52983. return _this;
  52984. }
  52985. return IndexedVector2;
  52986. }(BABYLON.Vector2));
  52987. var PolygonPoints = (function () {
  52988. function PolygonPoints() {
  52989. this.elements = new Array();
  52990. }
  52991. PolygonPoints.prototype.add = function (originalPoints) {
  52992. var _this = this;
  52993. var result = new Array();
  52994. originalPoints.forEach(function (point) {
  52995. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  52996. var newPoint = new IndexedVector2(point, _this.elements.length);
  52997. result.push(newPoint);
  52998. _this.elements.push(newPoint);
  52999. }
  53000. });
  53001. return result;
  53002. };
  53003. PolygonPoints.prototype.computeBounds = function () {
  53004. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  53005. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  53006. this.elements.forEach(function (point) {
  53007. // x
  53008. if (point.x < lmin.x) {
  53009. lmin.x = point.x;
  53010. }
  53011. else if (point.x > lmax.x) {
  53012. lmax.x = point.x;
  53013. }
  53014. // y
  53015. if (point.y < lmin.y) {
  53016. lmin.y = point.y;
  53017. }
  53018. else if (point.y > lmax.y) {
  53019. lmax.y = point.y;
  53020. }
  53021. });
  53022. return {
  53023. min: lmin,
  53024. max: lmax,
  53025. width: lmax.x - lmin.x,
  53026. height: lmax.y - lmin.y
  53027. };
  53028. };
  53029. return PolygonPoints;
  53030. }());
  53031. var Polygon = (function () {
  53032. function Polygon() {
  53033. }
  53034. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  53035. return [
  53036. new BABYLON.Vector2(xmin, ymin),
  53037. new BABYLON.Vector2(xmax, ymin),
  53038. new BABYLON.Vector2(xmax, ymax),
  53039. new BABYLON.Vector2(xmin, ymax)
  53040. ];
  53041. };
  53042. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  53043. if (cx === void 0) { cx = 0; }
  53044. if (cy === void 0) { cy = 0; }
  53045. if (numberOfSides === void 0) { numberOfSides = 32; }
  53046. var result = new Array();
  53047. var angle = 0;
  53048. var increment = (Math.PI * 2) / numberOfSides;
  53049. for (var i = 0; i < numberOfSides; i++) {
  53050. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  53051. angle -= increment;
  53052. }
  53053. return result;
  53054. };
  53055. Polygon.Parse = function (input) {
  53056. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  53057. var i, result = [];
  53058. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  53059. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  53060. }
  53061. return result;
  53062. };
  53063. Polygon.StartingAt = function (x, y) {
  53064. return BABYLON.Path2.StartingAt(x, y);
  53065. };
  53066. return Polygon;
  53067. }());
  53068. BABYLON.Polygon = Polygon;
  53069. var PolygonMeshBuilder = (function () {
  53070. function PolygonMeshBuilder(name, contours, scene) {
  53071. this._points = new PolygonPoints();
  53072. this._outlinepoints = new PolygonPoints();
  53073. this._holes = [];
  53074. this._epoints = new Array();
  53075. this._eholes = new Array();
  53076. this._name = name;
  53077. this._scene = scene;
  53078. var points;
  53079. if (contours instanceof BABYLON.Path2) {
  53080. points = contours.getPoints();
  53081. }
  53082. else {
  53083. points = contours;
  53084. }
  53085. this._addToepoint(points);
  53086. this._points.add(points);
  53087. this._outlinepoints.add(points);
  53088. }
  53089. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  53090. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  53091. var p = points_1[_i];
  53092. this._epoints.push(p.x, p.y);
  53093. }
  53094. };
  53095. PolygonMeshBuilder.prototype.addHole = function (hole) {
  53096. this._points.add(hole);
  53097. var holepoints = new PolygonPoints();
  53098. holepoints.add(hole);
  53099. this._holes.push(holepoints);
  53100. this._eholes.push(this._epoints.length / 2);
  53101. this._addToepoint(hole);
  53102. return this;
  53103. };
  53104. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  53105. var _this = this;
  53106. if (updatable === void 0) { updatable = false; }
  53107. var result = new BABYLON.Mesh(this._name, this._scene);
  53108. var normals = [];
  53109. var positions = [];
  53110. var uvs = [];
  53111. var bounds = this._points.computeBounds();
  53112. this._points.elements.forEach(function (p) {
  53113. normals.push(0, 1.0, 0);
  53114. positions.push(p.x, 0, p.y);
  53115. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  53116. });
  53117. var indices = [];
  53118. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  53119. for (var i = 0; i < res.length; i++) {
  53120. indices.push(res[i]);
  53121. }
  53122. if (depth > 0) {
  53123. var positionscount = (positions.length / 3); //get the current pointcount
  53124. this._points.elements.forEach(function (p) {
  53125. normals.push(0, -1.0, 0);
  53126. positions.push(p.x, -depth, p.y);
  53127. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  53128. });
  53129. var totalCount = indices.length;
  53130. for (var i = 0; i < totalCount; i += 3) {
  53131. var i0 = indices[i + 0];
  53132. var i1 = indices[i + 1];
  53133. var i2 = indices[i + 2];
  53134. indices.push(i2 + positionscount);
  53135. indices.push(i1 + positionscount);
  53136. indices.push(i0 + positionscount);
  53137. }
  53138. //Add the sides
  53139. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  53140. this._holes.forEach(function (hole) {
  53141. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  53142. });
  53143. }
  53144. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  53145. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  53146. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  53147. result.setIndices(indices);
  53148. return result;
  53149. };
  53150. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  53151. var StartIndex = positions.length / 3;
  53152. var ulength = 0;
  53153. for (var i = 0; i < points.elements.length; i++) {
  53154. var p = points.elements[i];
  53155. var p1;
  53156. if ((i + 1) > points.elements.length - 1) {
  53157. p1 = points.elements[0];
  53158. }
  53159. else {
  53160. p1 = points.elements[i + 1];
  53161. }
  53162. positions.push(p.x, 0, p.y);
  53163. positions.push(p.x, -depth, p.y);
  53164. positions.push(p1.x, 0, p1.y);
  53165. positions.push(p1.x, -depth, p1.y);
  53166. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  53167. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  53168. var v3 = v2.subtract(v1);
  53169. var v4 = new BABYLON.Vector3(0, 1, 0);
  53170. var vn = BABYLON.Vector3.Cross(v3, v4);
  53171. vn = vn.normalize();
  53172. uvs.push(ulength / bounds.width, 0);
  53173. uvs.push(ulength / bounds.width, 1);
  53174. ulength += v3.length();
  53175. uvs.push((ulength / bounds.width), 0);
  53176. uvs.push((ulength / bounds.width), 1);
  53177. if (!flip) {
  53178. normals.push(-vn.x, -vn.y, -vn.z);
  53179. normals.push(-vn.x, -vn.y, -vn.z);
  53180. normals.push(-vn.x, -vn.y, -vn.z);
  53181. normals.push(-vn.x, -vn.y, -vn.z);
  53182. indices.push(StartIndex);
  53183. indices.push(StartIndex + 1);
  53184. indices.push(StartIndex + 2);
  53185. indices.push(StartIndex + 1);
  53186. indices.push(StartIndex + 3);
  53187. indices.push(StartIndex + 2);
  53188. }
  53189. else {
  53190. normals.push(vn.x, vn.y, vn.z);
  53191. normals.push(vn.x, vn.y, vn.z);
  53192. normals.push(vn.x, vn.y, vn.z);
  53193. normals.push(vn.x, vn.y, vn.z);
  53194. indices.push(StartIndex);
  53195. indices.push(StartIndex + 2);
  53196. indices.push(StartIndex + 1);
  53197. indices.push(StartIndex + 1);
  53198. indices.push(StartIndex + 2);
  53199. indices.push(StartIndex + 3);
  53200. }
  53201. StartIndex += 4;
  53202. }
  53203. ;
  53204. };
  53205. return PolygonMeshBuilder;
  53206. }());
  53207. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  53208. })(BABYLON || (BABYLON = {}));
  53209. //# sourceMappingURL=babylon.polygonMesh.js.map
  53210. var BABYLON;
  53211. (function (BABYLON) {
  53212. // Unique ID when we import meshes from Babylon to CSG
  53213. var currentCSGMeshId = 0;
  53214. // # class Vertex
  53215. // Represents a vertex of a polygon. Use your own vertex class instead of this
  53216. // one to provide additional features like texture coordinates and vertex
  53217. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  53218. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  53219. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  53220. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  53221. // is not used anywhere else.
  53222. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  53223. var Vertex = (function () {
  53224. function Vertex(pos, normal, uv) {
  53225. this.pos = pos;
  53226. this.normal = normal;
  53227. this.uv = uv;
  53228. }
  53229. Vertex.prototype.clone = function () {
  53230. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  53231. };
  53232. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  53233. // orientation of a polygon is flipped.
  53234. Vertex.prototype.flip = function () {
  53235. this.normal = this.normal.scale(-1);
  53236. };
  53237. // Create a new vertex between this vertex and `other` by linearly
  53238. // interpolating all properties using a parameter of `t`. Subclasses should
  53239. // override this to interpolate additional properties.
  53240. Vertex.prototype.interpolate = function (other, t) {
  53241. 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));
  53242. };
  53243. return Vertex;
  53244. }());
  53245. // # class Plane
  53246. // Represents a plane in 3D space.
  53247. var Plane = (function () {
  53248. function Plane(normal, w) {
  53249. this.normal = normal;
  53250. this.w = w;
  53251. }
  53252. Plane.FromPoints = function (a, b, c) {
  53253. var v0 = c.subtract(a);
  53254. var v1 = b.subtract(a);
  53255. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  53256. return null;
  53257. }
  53258. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  53259. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  53260. };
  53261. Plane.prototype.clone = function () {
  53262. return new Plane(this.normal.clone(), this.w);
  53263. };
  53264. Plane.prototype.flip = function () {
  53265. this.normal.scaleInPlace(-1);
  53266. this.w = -this.w;
  53267. };
  53268. // Split `polygon` by this plane if needed, then put the polygon or polygon
  53269. // fragments in the appropriate lists. Coplanar polygons go into either
  53270. // `coplanarFront` or `coplanarBack` depending on their orientation with
  53271. // respect to this plane. Polygons in front or in back of this plane go into
  53272. // either `front` or `back`.
  53273. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  53274. var COPLANAR = 0;
  53275. var FRONT = 1;
  53276. var BACK = 2;
  53277. var SPANNING = 3;
  53278. // Classify each point as well as the entire polygon into one of the above
  53279. // four classes.
  53280. var polygonType = 0;
  53281. var types = [];
  53282. var i;
  53283. var t;
  53284. for (i = 0; i < polygon.vertices.length; i++) {
  53285. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  53286. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  53287. polygonType |= type;
  53288. types.push(type);
  53289. }
  53290. // Put the polygon in the correct list, splitting it when necessary.
  53291. switch (polygonType) {
  53292. case COPLANAR:
  53293. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  53294. break;
  53295. case FRONT:
  53296. front.push(polygon);
  53297. break;
  53298. case BACK:
  53299. back.push(polygon);
  53300. break;
  53301. case SPANNING:
  53302. var f = [], b = [];
  53303. for (i = 0; i < polygon.vertices.length; i++) {
  53304. var j = (i + 1) % polygon.vertices.length;
  53305. var ti = types[i], tj = types[j];
  53306. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  53307. if (ti !== BACK)
  53308. f.push(vi);
  53309. if (ti !== FRONT)
  53310. b.push(ti !== BACK ? vi.clone() : vi);
  53311. if ((ti | tj) === SPANNING) {
  53312. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  53313. var v = vi.interpolate(vj, t);
  53314. f.push(v);
  53315. b.push(v.clone());
  53316. }
  53317. }
  53318. var poly;
  53319. if (f.length >= 3) {
  53320. poly = new Polygon(f, polygon.shared);
  53321. if (poly.plane)
  53322. front.push(poly);
  53323. }
  53324. if (b.length >= 3) {
  53325. poly = new Polygon(b, polygon.shared);
  53326. if (poly.plane)
  53327. back.push(poly);
  53328. }
  53329. break;
  53330. }
  53331. };
  53332. return Plane;
  53333. }());
  53334. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  53335. // point is on the plane.
  53336. Plane.EPSILON = 1e-5;
  53337. // # class Polygon
  53338. // Represents a convex polygon. The vertices used to initialize a polygon must
  53339. // be coplanar and form a convex loop.
  53340. //
  53341. // Each convex polygon has a `shared` property, which is shared between all
  53342. // polygons that are clones of each other or were split from the same polygon.
  53343. // This can be used to define per-polygon properties (such as surface color).
  53344. var Polygon = (function () {
  53345. function Polygon(vertices, shared) {
  53346. this.vertices = vertices;
  53347. this.shared = shared;
  53348. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  53349. }
  53350. Polygon.prototype.clone = function () {
  53351. var vertices = this.vertices.map(function (v) { return v.clone(); });
  53352. return new Polygon(vertices, this.shared);
  53353. };
  53354. Polygon.prototype.flip = function () {
  53355. this.vertices.reverse().map(function (v) { v.flip(); });
  53356. this.plane.flip();
  53357. };
  53358. return Polygon;
  53359. }());
  53360. // # class Node
  53361. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  53362. // by picking a polygon to split along. That polygon (and all other coplanar
  53363. // polygons) are added directly to that node and the other polygons are added to
  53364. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  53365. // no distinction between internal and leaf nodes.
  53366. var Node = (function () {
  53367. function Node(polygons) {
  53368. this.plane = null;
  53369. this.front = null;
  53370. this.back = null;
  53371. this.polygons = [];
  53372. if (polygons) {
  53373. this.build(polygons);
  53374. }
  53375. }
  53376. Node.prototype.clone = function () {
  53377. var node = new Node();
  53378. node.plane = this.plane && this.plane.clone();
  53379. node.front = this.front && this.front.clone();
  53380. node.back = this.back && this.back.clone();
  53381. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  53382. return node;
  53383. };
  53384. // Convert solid space to empty space and empty space to solid space.
  53385. Node.prototype.invert = function () {
  53386. for (var i = 0; i < this.polygons.length; i++) {
  53387. this.polygons[i].flip();
  53388. }
  53389. if (this.plane) {
  53390. this.plane.flip();
  53391. }
  53392. if (this.front) {
  53393. this.front.invert();
  53394. }
  53395. if (this.back) {
  53396. this.back.invert();
  53397. }
  53398. var temp = this.front;
  53399. this.front = this.back;
  53400. this.back = temp;
  53401. };
  53402. // Recursively remove all polygons in `polygons` that are inside this BSP
  53403. // tree.
  53404. Node.prototype.clipPolygons = function (polygons) {
  53405. if (!this.plane)
  53406. return polygons.slice();
  53407. var front = [], back = [];
  53408. for (var i = 0; i < polygons.length; i++) {
  53409. this.plane.splitPolygon(polygons[i], front, back, front, back);
  53410. }
  53411. if (this.front) {
  53412. front = this.front.clipPolygons(front);
  53413. }
  53414. if (this.back) {
  53415. back = this.back.clipPolygons(back);
  53416. }
  53417. else {
  53418. back = [];
  53419. }
  53420. return front.concat(back);
  53421. };
  53422. // Remove all polygons in this BSP tree that are inside the other BSP tree
  53423. // `bsp`.
  53424. Node.prototype.clipTo = function (bsp) {
  53425. this.polygons = bsp.clipPolygons(this.polygons);
  53426. if (this.front)
  53427. this.front.clipTo(bsp);
  53428. if (this.back)
  53429. this.back.clipTo(bsp);
  53430. };
  53431. // Return a list of all polygons in this BSP tree.
  53432. Node.prototype.allPolygons = function () {
  53433. var polygons = this.polygons.slice();
  53434. if (this.front)
  53435. polygons = polygons.concat(this.front.allPolygons());
  53436. if (this.back)
  53437. polygons = polygons.concat(this.back.allPolygons());
  53438. return polygons;
  53439. };
  53440. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  53441. // new polygons are filtered down to the bottom of the tree and become new
  53442. // nodes there. Each set of polygons is partitioned using the first polygon
  53443. // (no heuristic is used to pick a good split).
  53444. Node.prototype.build = function (polygons) {
  53445. if (!polygons.length)
  53446. return;
  53447. if (!this.plane)
  53448. this.plane = polygons[0].plane.clone();
  53449. var front = [], back = [];
  53450. for (var i = 0; i < polygons.length; i++) {
  53451. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  53452. }
  53453. if (front.length) {
  53454. if (!this.front)
  53455. this.front = new Node();
  53456. this.front.build(front);
  53457. }
  53458. if (back.length) {
  53459. if (!this.back)
  53460. this.back = new Node();
  53461. this.back.build(back);
  53462. }
  53463. };
  53464. return Node;
  53465. }());
  53466. var CSG = (function () {
  53467. function CSG() {
  53468. this.polygons = new Array();
  53469. }
  53470. // Convert BABYLON.Mesh to BABYLON.CSG
  53471. CSG.FromMesh = function (mesh) {
  53472. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  53473. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  53474. if (mesh instanceof BABYLON.Mesh) {
  53475. mesh.computeWorldMatrix(true);
  53476. matrix = mesh.getWorldMatrix();
  53477. meshPosition = mesh.position.clone();
  53478. meshRotation = mesh.rotation.clone();
  53479. if (mesh.rotationQuaternion) {
  53480. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  53481. }
  53482. meshScaling = mesh.scaling.clone();
  53483. }
  53484. else {
  53485. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  53486. }
  53487. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  53488. var subMeshes = mesh.subMeshes;
  53489. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  53490. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  53491. vertices = [];
  53492. for (var j = 0; j < 3; j++) {
  53493. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  53494. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  53495. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  53496. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  53497. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  53498. vertex = new Vertex(position, normal, uv);
  53499. vertices.push(vertex);
  53500. }
  53501. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  53502. // To handle the case of degenerated triangle
  53503. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  53504. if (polygon.plane)
  53505. polygons.push(polygon);
  53506. }
  53507. }
  53508. var csg = CSG.FromPolygons(polygons);
  53509. csg.matrix = matrix;
  53510. csg.position = meshPosition;
  53511. csg.rotation = meshRotation;
  53512. csg.scaling = meshScaling;
  53513. csg.rotationQuaternion = meshRotationQuaternion;
  53514. currentCSGMeshId++;
  53515. return csg;
  53516. };
  53517. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  53518. CSG.FromPolygons = function (polygons) {
  53519. var csg = new CSG();
  53520. csg.polygons = polygons;
  53521. return csg;
  53522. };
  53523. CSG.prototype.clone = function () {
  53524. var csg = new CSG();
  53525. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  53526. csg.copyTransformAttributes(this);
  53527. return csg;
  53528. };
  53529. CSG.prototype.toPolygons = function () {
  53530. return this.polygons;
  53531. };
  53532. CSG.prototype.union = function (csg) {
  53533. var a = new Node(this.clone().polygons);
  53534. var b = new Node(csg.clone().polygons);
  53535. a.clipTo(b);
  53536. b.clipTo(a);
  53537. b.invert();
  53538. b.clipTo(a);
  53539. b.invert();
  53540. a.build(b.allPolygons());
  53541. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  53542. };
  53543. CSG.prototype.unionInPlace = function (csg) {
  53544. var a = new Node(this.polygons);
  53545. var b = new Node(csg.polygons);
  53546. a.clipTo(b);
  53547. b.clipTo(a);
  53548. b.invert();
  53549. b.clipTo(a);
  53550. b.invert();
  53551. a.build(b.allPolygons());
  53552. this.polygons = a.allPolygons();
  53553. };
  53554. CSG.prototype.subtract = function (csg) {
  53555. var a = new Node(this.clone().polygons);
  53556. var b = new Node(csg.clone().polygons);
  53557. a.invert();
  53558. a.clipTo(b);
  53559. b.clipTo(a);
  53560. b.invert();
  53561. b.clipTo(a);
  53562. b.invert();
  53563. a.build(b.allPolygons());
  53564. a.invert();
  53565. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  53566. };
  53567. CSG.prototype.subtractInPlace = function (csg) {
  53568. var a = new Node(this.polygons);
  53569. var b = new Node(csg.polygons);
  53570. a.invert();
  53571. a.clipTo(b);
  53572. b.clipTo(a);
  53573. b.invert();
  53574. b.clipTo(a);
  53575. b.invert();
  53576. a.build(b.allPolygons());
  53577. a.invert();
  53578. this.polygons = a.allPolygons();
  53579. };
  53580. CSG.prototype.intersect = function (csg) {
  53581. var a = new Node(this.clone().polygons);
  53582. var b = new Node(csg.clone().polygons);
  53583. a.invert();
  53584. b.clipTo(a);
  53585. b.invert();
  53586. a.clipTo(b);
  53587. b.clipTo(a);
  53588. a.build(b.allPolygons());
  53589. a.invert();
  53590. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  53591. };
  53592. CSG.prototype.intersectInPlace = function (csg) {
  53593. var a = new Node(this.polygons);
  53594. var b = new Node(csg.polygons);
  53595. a.invert();
  53596. b.clipTo(a);
  53597. b.invert();
  53598. a.clipTo(b);
  53599. b.clipTo(a);
  53600. a.build(b.allPolygons());
  53601. a.invert();
  53602. this.polygons = a.allPolygons();
  53603. };
  53604. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  53605. // not modified.
  53606. CSG.prototype.inverse = function () {
  53607. var csg = this.clone();
  53608. csg.inverseInPlace();
  53609. return csg;
  53610. };
  53611. CSG.prototype.inverseInPlace = function () {
  53612. this.polygons.map(function (p) { p.flip(); });
  53613. };
  53614. // This is used to keep meshes transformations so they can be restored
  53615. // when we build back a Babylon Mesh
  53616. // NB : All CSG operations are performed in world coordinates
  53617. CSG.prototype.copyTransformAttributes = function (csg) {
  53618. this.matrix = csg.matrix;
  53619. this.position = csg.position;
  53620. this.rotation = csg.rotation;
  53621. this.scaling = csg.scaling;
  53622. this.rotationQuaternion = csg.rotationQuaternion;
  53623. return this;
  53624. };
  53625. // Build Raw mesh from CSG
  53626. // Coordinates here are in world space
  53627. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  53628. var matrix = this.matrix.clone();
  53629. matrix.invert();
  53630. 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;
  53631. if (keepSubMeshes) {
  53632. // Sort Polygons, since subMeshes are indices range
  53633. polygons.sort(function (a, b) {
  53634. if (a.shared.meshId === b.shared.meshId) {
  53635. return a.shared.subMeshId - b.shared.subMeshId;
  53636. }
  53637. else {
  53638. return a.shared.meshId - b.shared.meshId;
  53639. }
  53640. });
  53641. }
  53642. for (var i = 0, il = polygons.length; i < il; i++) {
  53643. polygon = polygons[i];
  53644. // Building SubMeshes
  53645. if (!subMesh_dict[polygon.shared.meshId]) {
  53646. subMesh_dict[polygon.shared.meshId] = {};
  53647. }
  53648. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  53649. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  53650. indexStart: +Infinity,
  53651. indexEnd: -Infinity,
  53652. materialIndex: polygon.shared.materialIndex
  53653. };
  53654. }
  53655. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  53656. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  53657. polygonIndices[0] = 0;
  53658. polygonIndices[1] = j - 1;
  53659. polygonIndices[2] = j;
  53660. for (var k = 0; k < 3; k++) {
  53661. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  53662. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  53663. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  53664. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  53665. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  53666. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  53667. // Check if 2 points can be merged
  53668. if (!(typeof vertex_idx !== 'undefined' &&
  53669. normals[vertex_idx * 3] === localNormal.x &&
  53670. normals[vertex_idx * 3 + 1] === localNormal.y &&
  53671. normals[vertex_idx * 3 + 2] === localNormal.z &&
  53672. uvs[vertex_idx * 2] === uv.x &&
  53673. uvs[vertex_idx * 2 + 1] === uv.y)) {
  53674. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  53675. uvs.push(uv.x, uv.y);
  53676. normals.push(normal.x, normal.y, normal.z);
  53677. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  53678. }
  53679. indices.push(vertex_idx);
  53680. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  53681. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  53682. currentIndex++;
  53683. }
  53684. }
  53685. }
  53686. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  53687. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  53688. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  53689. mesh.setIndices(indices);
  53690. if (keepSubMeshes) {
  53691. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  53692. var materialIndexOffset = 0, materialMaxIndex;
  53693. mesh.subMeshes = new Array();
  53694. for (var m in subMesh_dict) {
  53695. materialMaxIndex = -1;
  53696. for (var sm in subMesh_dict[m]) {
  53697. subMesh_obj = subMesh_dict[m][sm];
  53698. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  53699. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  53700. }
  53701. materialIndexOffset += ++materialMaxIndex;
  53702. }
  53703. }
  53704. return mesh;
  53705. };
  53706. // Build Mesh from CSG taking material and transforms into account
  53707. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  53708. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  53709. mesh.material = material;
  53710. mesh.position.copyFrom(this.position);
  53711. mesh.rotation.copyFrom(this.rotation);
  53712. if (this.rotationQuaternion) {
  53713. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  53714. }
  53715. mesh.scaling.copyFrom(this.scaling);
  53716. mesh.computeWorldMatrix(true);
  53717. return mesh;
  53718. };
  53719. return CSG;
  53720. }());
  53721. BABYLON.CSG = CSG;
  53722. })(BABYLON || (BABYLON = {}));
  53723. //# sourceMappingURL=babylon.csg.js.map
  53724. var BABYLON;
  53725. (function (BABYLON) {
  53726. var LensFlare = (function () {
  53727. function LensFlare(size, position, color, imgUrl, system) {
  53728. this.size = size;
  53729. this.position = position;
  53730. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  53731. this.dispose = function () {
  53732. if (this.texture) {
  53733. this.texture.dispose();
  53734. }
  53735. // Remove from scene
  53736. var index = this._system.lensFlares.indexOf(this);
  53737. this._system.lensFlares.splice(index, 1);
  53738. };
  53739. this.color = color || new BABYLON.Color3(1, 1, 1);
  53740. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  53741. this._system = system;
  53742. system.lensFlares.push(this);
  53743. }
  53744. return LensFlare;
  53745. }());
  53746. BABYLON.LensFlare = LensFlare;
  53747. })(BABYLON || (BABYLON = {}));
  53748. //# sourceMappingURL=babylon.lensFlare.js.map
  53749. var BABYLON;
  53750. (function (BABYLON) {
  53751. var LensFlareSystem = (function () {
  53752. function LensFlareSystem(name, emitter, scene) {
  53753. this.name = name;
  53754. this.lensFlares = new Array();
  53755. this.borderLimit = 300;
  53756. this.viewportBorder = 0;
  53757. this.layerMask = 0x0FFFFFFF;
  53758. this._vertexBuffers = {};
  53759. this._isEnabled = true;
  53760. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  53761. this._emitter = emitter;
  53762. this.id = name;
  53763. scene.lensFlareSystems.push(this);
  53764. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  53765. var engine = scene.getEngine();
  53766. // VBO
  53767. var vertices = [];
  53768. vertices.push(1, 1);
  53769. vertices.push(-1, 1);
  53770. vertices.push(-1, -1);
  53771. vertices.push(1, -1);
  53772. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  53773. // Indices
  53774. var indices = [];
  53775. indices.push(0);
  53776. indices.push(1);
  53777. indices.push(2);
  53778. indices.push(0);
  53779. indices.push(2);
  53780. indices.push(3);
  53781. this._indexBuffer = engine.createIndexBuffer(indices);
  53782. // Effects
  53783. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  53784. }
  53785. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  53786. get: function () {
  53787. return this._isEnabled;
  53788. },
  53789. set: function (value) {
  53790. this._isEnabled = value;
  53791. },
  53792. enumerable: true,
  53793. configurable: true
  53794. });
  53795. LensFlareSystem.prototype.getScene = function () {
  53796. return this._scene;
  53797. };
  53798. LensFlareSystem.prototype.getEmitter = function () {
  53799. return this._emitter;
  53800. };
  53801. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  53802. this._emitter = newEmitter;
  53803. };
  53804. LensFlareSystem.prototype.getEmitterPosition = function () {
  53805. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  53806. };
  53807. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  53808. var position = this.getEmitterPosition();
  53809. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  53810. this._positionX = position.x;
  53811. this._positionY = position.y;
  53812. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  53813. if (this.viewportBorder > 0) {
  53814. globalViewport.x -= this.viewportBorder;
  53815. globalViewport.y -= this.viewportBorder;
  53816. globalViewport.width += this.viewportBorder * 2;
  53817. globalViewport.height += this.viewportBorder * 2;
  53818. position.x += this.viewportBorder;
  53819. position.y += this.viewportBorder;
  53820. this._positionX += this.viewportBorder;
  53821. this._positionY += this.viewportBorder;
  53822. }
  53823. if (position.z > 0) {
  53824. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  53825. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  53826. return true;
  53827. }
  53828. return true;
  53829. }
  53830. return false;
  53831. };
  53832. LensFlareSystem.prototype._isVisible = function () {
  53833. if (!this._isEnabled) {
  53834. return false;
  53835. }
  53836. var emitterPosition = this.getEmitterPosition();
  53837. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  53838. var distance = direction.length();
  53839. direction.normalize();
  53840. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  53841. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  53842. return !pickInfo.hit || pickInfo.distance > distance;
  53843. };
  53844. LensFlareSystem.prototype.render = function () {
  53845. if (!this._effect.isReady())
  53846. return false;
  53847. var engine = this._scene.getEngine();
  53848. var viewport = this._scene.activeCamera.viewport;
  53849. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  53850. // Position
  53851. if (!this.computeEffectivePosition(globalViewport)) {
  53852. return false;
  53853. }
  53854. // Visibility
  53855. if (!this._isVisible()) {
  53856. return false;
  53857. }
  53858. // Intensity
  53859. var awayX;
  53860. var awayY;
  53861. if (this._positionX < this.borderLimit + globalViewport.x) {
  53862. awayX = this.borderLimit + globalViewport.x - this._positionX;
  53863. }
  53864. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  53865. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  53866. }
  53867. else {
  53868. awayX = 0;
  53869. }
  53870. if (this._positionY < this.borderLimit + globalViewport.y) {
  53871. awayY = this.borderLimit + globalViewport.y - this._positionY;
  53872. }
  53873. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  53874. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  53875. }
  53876. else {
  53877. awayY = 0;
  53878. }
  53879. var away = (awayX > awayY) ? awayX : awayY;
  53880. away -= this.viewportBorder;
  53881. if (away > this.borderLimit) {
  53882. away = this.borderLimit;
  53883. }
  53884. var intensity = 1.0 - (away / this.borderLimit);
  53885. if (intensity < 0) {
  53886. return false;
  53887. }
  53888. if (intensity > 1.0) {
  53889. intensity = 1.0;
  53890. }
  53891. if (this.viewportBorder > 0) {
  53892. globalViewport.x += this.viewportBorder;
  53893. globalViewport.y += this.viewportBorder;
  53894. globalViewport.width -= this.viewportBorder * 2;
  53895. globalViewport.height -= this.viewportBorder * 2;
  53896. this._positionX -= this.viewportBorder;
  53897. this._positionY -= this.viewportBorder;
  53898. }
  53899. // Position
  53900. var centerX = globalViewport.x + globalViewport.width / 2;
  53901. var centerY = globalViewport.y + globalViewport.height / 2;
  53902. var distX = centerX - this._positionX;
  53903. var distY = centerY - this._positionY;
  53904. // Effects
  53905. engine.enableEffect(this._effect);
  53906. engine.setState(false);
  53907. engine.setDepthBuffer(false);
  53908. // VBOs
  53909. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  53910. // Flares
  53911. for (var index = 0; index < this.lensFlares.length; index++) {
  53912. var flare = this.lensFlares[index];
  53913. engine.setAlphaMode(flare.alphaMode);
  53914. var x = centerX - (distX * flare.position);
  53915. var y = centerY - (distY * flare.position);
  53916. var cw = flare.size;
  53917. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  53918. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  53919. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  53920. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  53921. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  53922. // Texture
  53923. this._effect.setTexture("textureSampler", flare.texture);
  53924. // Color
  53925. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  53926. // Draw order
  53927. engine.draw(true, 0, 6);
  53928. }
  53929. engine.setDepthBuffer(true);
  53930. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  53931. return true;
  53932. };
  53933. LensFlareSystem.prototype.dispose = function () {
  53934. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  53935. if (vertexBuffer) {
  53936. vertexBuffer.dispose();
  53937. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  53938. }
  53939. if (this._indexBuffer) {
  53940. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  53941. this._indexBuffer = null;
  53942. }
  53943. while (this.lensFlares.length) {
  53944. this.lensFlares[0].dispose();
  53945. }
  53946. // Remove from scene
  53947. var index = this._scene.lensFlareSystems.indexOf(this);
  53948. this._scene.lensFlareSystems.splice(index, 1);
  53949. };
  53950. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  53951. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  53952. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  53953. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  53954. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  53955. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  53956. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  53957. var parsedFlare = parsedLensFlareSystem.flares[index];
  53958. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  53959. }
  53960. return lensFlareSystem;
  53961. };
  53962. LensFlareSystem.prototype.serialize = function () {
  53963. var serializationObject = {};
  53964. serializationObject.id = this.id;
  53965. serializationObject.name = this.name;
  53966. serializationObject.emitterId = this.getEmitter().id;
  53967. serializationObject.borderLimit = this.borderLimit;
  53968. serializationObject.flares = [];
  53969. for (var index = 0; index < this.lensFlares.length; index++) {
  53970. var flare = this.lensFlares[index];
  53971. serializationObject.flares.push({
  53972. size: flare.size,
  53973. position: flare.position,
  53974. color: flare.color.asArray(),
  53975. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  53976. });
  53977. }
  53978. return serializationObject;
  53979. };
  53980. return LensFlareSystem;
  53981. }());
  53982. BABYLON.LensFlareSystem = LensFlareSystem;
  53983. })(BABYLON || (BABYLON = {}));
  53984. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  53985. var BABYLON;
  53986. (function (BABYLON) {
  53987. /**
  53988. * This is a holder class for the physics joint created by the physics plugin.
  53989. * It holds a set of functions to control the underlying joint.
  53990. */
  53991. var PhysicsJoint = (function () {
  53992. function PhysicsJoint(type, jointData) {
  53993. this.type = type;
  53994. this.jointData = jointData;
  53995. jointData.nativeParams = jointData.nativeParams || {};
  53996. }
  53997. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  53998. get: function () {
  53999. return this._physicsJoint;
  54000. },
  54001. set: function (newJoint) {
  54002. if (this._physicsJoint) {
  54003. //remove from the wolrd
  54004. }
  54005. this._physicsJoint = newJoint;
  54006. },
  54007. enumerable: true,
  54008. configurable: true
  54009. });
  54010. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  54011. set: function (physicsPlugin) {
  54012. this._physicsPlugin = physicsPlugin;
  54013. },
  54014. enumerable: true,
  54015. configurable: true
  54016. });
  54017. /**
  54018. * Execute a function that is physics-plugin specific.
  54019. * @param {Function} func the function that will be executed.
  54020. * It accepts two parameters: the physics world and the physics joint.
  54021. */
  54022. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  54023. func(this._physicsPlugin.world, this._physicsJoint);
  54024. };
  54025. return PhysicsJoint;
  54026. }());
  54027. //TODO check if the native joints are the same
  54028. //Joint Types
  54029. PhysicsJoint.DistanceJoint = 0;
  54030. PhysicsJoint.HingeJoint = 1;
  54031. PhysicsJoint.BallAndSocketJoint = 2;
  54032. PhysicsJoint.WheelJoint = 3;
  54033. PhysicsJoint.SliderJoint = 4;
  54034. //OIMO
  54035. PhysicsJoint.PrismaticJoint = 5;
  54036. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  54037. PhysicsJoint.UniversalJoint = 6;
  54038. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  54039. //Cannon
  54040. //Similar to a Ball-Joint. Different in params
  54041. PhysicsJoint.PointToPointJoint = 8;
  54042. //Cannon only at the moment
  54043. PhysicsJoint.SpringJoint = 9;
  54044. PhysicsJoint.LockJoint = 10;
  54045. BABYLON.PhysicsJoint = PhysicsJoint;
  54046. /**
  54047. * A class representing a physics distance joint.
  54048. */
  54049. var DistanceJoint = (function (_super) {
  54050. __extends(DistanceJoint, _super);
  54051. function DistanceJoint(jointData) {
  54052. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  54053. }
  54054. /**
  54055. * Update the predefined distance.
  54056. */
  54057. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  54058. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  54059. };
  54060. return DistanceJoint;
  54061. }(PhysicsJoint));
  54062. BABYLON.DistanceJoint = DistanceJoint;
  54063. var MotorEnabledJoint = (function (_super) {
  54064. __extends(MotorEnabledJoint, _super);
  54065. function MotorEnabledJoint(type, jointData) {
  54066. return _super.call(this, type, jointData) || this;
  54067. }
  54068. /**
  54069. * Set the motor values.
  54070. * Attention, this function is plugin specific. Engines won't react 100% the same.
  54071. * @param {number} force the force to apply
  54072. * @param {number} maxForce max force for this motor.
  54073. */
  54074. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  54075. this._physicsPlugin.setMotor(this, force, maxForce);
  54076. };
  54077. /**
  54078. * Set the motor's limits.
  54079. * Attention, this function is plugin specific. Engines won't react 100% the same.
  54080. */
  54081. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  54082. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  54083. };
  54084. return MotorEnabledJoint;
  54085. }(PhysicsJoint));
  54086. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  54087. /**
  54088. * This class represents a single hinge physics joint
  54089. */
  54090. var HingeJoint = (function (_super) {
  54091. __extends(HingeJoint, _super);
  54092. function HingeJoint(jointData) {
  54093. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  54094. }
  54095. /**
  54096. * Set the motor values.
  54097. * Attention, this function is plugin specific. Engines won't react 100% the same.
  54098. * @param {number} force the force to apply
  54099. * @param {number} maxForce max force for this motor.
  54100. */
  54101. HingeJoint.prototype.setMotor = function (force, maxForce) {
  54102. this._physicsPlugin.setMotor(this, force, maxForce);
  54103. };
  54104. /**
  54105. * Set the motor's limits.
  54106. * Attention, this function is plugin specific. Engines won't react 100% the same.
  54107. */
  54108. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  54109. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  54110. };
  54111. return HingeJoint;
  54112. }(MotorEnabledJoint));
  54113. BABYLON.HingeJoint = HingeJoint;
  54114. /**
  54115. * This class represents a dual hinge physics joint (same as wheel joint)
  54116. */
  54117. var Hinge2Joint = (function (_super) {
  54118. __extends(Hinge2Joint, _super);
  54119. function Hinge2Joint(jointData) {
  54120. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  54121. }
  54122. /**
  54123. * Set the motor values.
  54124. * Attention, this function is plugin specific. Engines won't react 100% the same.
  54125. * @param {number} force the force to apply
  54126. * @param {number} maxForce max force for this motor.
  54127. * @param {motorIndex} the motor's index, 0 or 1.
  54128. */
  54129. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  54130. if (motorIndex === void 0) { motorIndex = 0; }
  54131. this._physicsPlugin.setMotor(this, force, maxForce, motorIndex);
  54132. };
  54133. /**
  54134. * Set the motor limits.
  54135. * Attention, this function is plugin specific. Engines won't react 100% the same.
  54136. * @param {number} upperLimit the upper limit
  54137. * @param {number} lowerLimit lower limit
  54138. * @param {motorIndex} the motor's index, 0 or 1.
  54139. */
  54140. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  54141. if (motorIndex === void 0) { motorIndex = 0; }
  54142. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  54143. };
  54144. return Hinge2Joint;
  54145. }(MotorEnabledJoint));
  54146. BABYLON.Hinge2Joint = Hinge2Joint;
  54147. })(BABYLON || (BABYLON = {}));
  54148. //# sourceMappingURL=babylon.physicsJoint.js.map
  54149. var BABYLON;
  54150. (function (BABYLON) {
  54151. var PhysicsImpostor = (function () {
  54152. function PhysicsImpostor(object, type, _options, _scene) {
  54153. if (_options === void 0) { _options = { mass: 0 }; }
  54154. var _this = this;
  54155. this.object = object;
  54156. this.type = type;
  54157. this._options = _options;
  54158. this._scene = _scene;
  54159. this._bodyUpdateRequired = false;
  54160. this._onBeforePhysicsStepCallbacks = new Array();
  54161. this._onAfterPhysicsStepCallbacks = new Array();
  54162. this._onPhysicsCollideCallbacks = [];
  54163. this._deltaPosition = BABYLON.Vector3.Zero();
  54164. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  54165. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  54166. /**
  54167. * this function is executed by the physics engine.
  54168. */
  54169. this.beforeStep = function () {
  54170. _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  54171. //conjugate deltaRotation
  54172. if (_this._deltaRotationConjugated) {
  54173. _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  54174. }
  54175. else {
  54176. _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
  54177. }
  54178. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  54179. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  54180. func(_this);
  54181. });
  54182. };
  54183. /**
  54184. * this function is executed by the physics engine.
  54185. */
  54186. this.afterStep = function () {
  54187. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  54188. func(_this);
  54189. });
  54190. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  54191. _this.object.position.addInPlace(_this._deltaPosition);
  54192. if (_this._deltaRotation) {
  54193. _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  54194. }
  54195. };
  54196. /**
  54197. * Legacy collision detection event support
  54198. */
  54199. this.onCollideEvent = null;
  54200. //event and body object due to cannon's event-based architecture.
  54201. this.onCollide = function (e) {
  54202. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent)
  54203. return;
  54204. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  54205. if (otherImpostor) {
  54206. // Legacy collision detection event support
  54207. if (_this.onCollideEvent) {
  54208. _this.onCollideEvent(_this, otherImpostor);
  54209. }
  54210. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  54211. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  54212. }).forEach(function (obj) {
  54213. obj.callback(_this, otherImpostor);
  54214. });
  54215. }
  54216. };
  54217. //sanity check!
  54218. if (!this.object) {
  54219. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  54220. return;
  54221. }
  54222. //legacy support for old syntax.
  54223. if (!this._scene && object.getScene) {
  54224. this._scene = object.getScene();
  54225. }
  54226. this._physicsEngine = this._scene.getPhysicsEngine();
  54227. if (!this._physicsEngine) {
  54228. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  54229. }
  54230. else {
  54231. //set the object's quaternion, if not set
  54232. if (!this.object.rotationQuaternion) {
  54233. if (this.object.rotation) {
  54234. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  54235. }
  54236. else {
  54237. this.object.rotationQuaternion = new BABYLON.Quaternion();
  54238. }
  54239. }
  54240. //default options params
  54241. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  54242. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  54243. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  54244. this._joints = [];
  54245. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  54246. if (!this.object.parent) {
  54247. this._init();
  54248. }
  54249. }
  54250. }
  54251. /**
  54252. * This function will completly initialize this impostor.
  54253. * It will create a new body - but only if this mesh has no parent.
  54254. * If it has, this impostor will not be used other than to define the impostor
  54255. * of the child mesh.
  54256. */
  54257. PhysicsImpostor.prototype._init = function () {
  54258. this._physicsEngine.removeImpostor(this);
  54259. this.physicsBody = null;
  54260. this._parent = this._parent || this._getPhysicsParent();
  54261. if (!this.parent) {
  54262. this._physicsEngine.addImpostor(this);
  54263. }
  54264. };
  54265. PhysicsImpostor.prototype._getPhysicsParent = function () {
  54266. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  54267. var parentMesh = this.object.parent;
  54268. return parentMesh.physicsImpostor;
  54269. }
  54270. return;
  54271. };
  54272. /**
  54273. * Should a new body be generated.
  54274. */
  54275. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  54276. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  54277. };
  54278. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  54279. this.forceUpdate();
  54280. };
  54281. /**
  54282. * Force a regeneration of this or the parent's impostor's body.
  54283. * Use under cautious - This will remove all joints already implemented.
  54284. */
  54285. PhysicsImpostor.prototype.forceUpdate = function () {
  54286. this._init();
  54287. if (this.parent) {
  54288. this.parent.forceUpdate();
  54289. }
  54290. };
  54291. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  54292. /*public get mesh(): AbstractMesh {
  54293. return this._mesh;
  54294. }*/
  54295. /**
  54296. * Gets the body that holds this impostor. Either its own, or its parent.
  54297. */
  54298. get: function () {
  54299. return this._parent ? this._parent.physicsBody : this._physicsBody;
  54300. },
  54301. /**
  54302. * Set the physics body. Used mainly by the physics engine/plugin
  54303. */
  54304. set: function (physicsBody) {
  54305. if (this._physicsBody) {
  54306. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  54307. }
  54308. this._physicsBody = physicsBody;
  54309. this.resetUpdateFlags();
  54310. },
  54311. enumerable: true,
  54312. configurable: true
  54313. });
  54314. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  54315. get: function () {
  54316. return this._parent;
  54317. },
  54318. set: function (value) {
  54319. this._parent = value;
  54320. },
  54321. enumerable: true,
  54322. configurable: true
  54323. });
  54324. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  54325. this._bodyUpdateRequired = false;
  54326. };
  54327. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  54328. if (this.object.getBoundingInfo) {
  54329. var q = this.object.rotationQuaternion;
  54330. //reset rotation
  54331. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  54332. //calculate the world matrix with no rotation
  54333. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  54334. var size = this.object.getBoundingInfo().boundingBox.extendSizeWorld.scale(2);
  54335. //bring back the rotation
  54336. this.object.rotationQuaternion = q;
  54337. //calculate the world matrix with the new rotation
  54338. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  54339. return size;
  54340. }
  54341. else {
  54342. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  54343. }
  54344. };
  54345. PhysicsImpostor.prototype.getObjectCenter = function () {
  54346. if (this.object.getBoundingInfo) {
  54347. return this.object.getBoundingInfo().boundingBox.centerWorld;
  54348. }
  54349. else {
  54350. return this.object.position;
  54351. }
  54352. };
  54353. /**
  54354. * Get a specific parametes from the options parameter.
  54355. */
  54356. PhysicsImpostor.prototype.getParam = function (paramName) {
  54357. return this._options[paramName];
  54358. };
  54359. /**
  54360. * Sets a specific parameter in the options given to the physics plugin
  54361. */
  54362. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  54363. this._options[paramName] = value;
  54364. this._bodyUpdateRequired = true;
  54365. };
  54366. /**
  54367. * Specifically change the body's mass option. Won't recreate the physics body object
  54368. */
  54369. PhysicsImpostor.prototype.setMass = function (mass) {
  54370. if (this.getParam("mass") !== mass) {
  54371. this.setParam("mass", mass);
  54372. }
  54373. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  54374. };
  54375. PhysicsImpostor.prototype.getLinearVelocity = function () {
  54376. return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this);
  54377. };
  54378. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  54379. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  54380. };
  54381. PhysicsImpostor.prototype.getAngularVelocity = function () {
  54382. return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this);
  54383. };
  54384. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  54385. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  54386. };
  54387. /**
  54388. * Execute a function with the physics plugin native code.
  54389. * Provide a function the will have two variables - the world object and the physics body object.
  54390. */
  54391. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  54392. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  54393. };
  54394. /**
  54395. * Register a function that will be executed before the physics world is stepping forward.
  54396. */
  54397. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  54398. this._onBeforePhysicsStepCallbacks.push(func);
  54399. };
  54400. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  54401. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  54402. if (index > -1) {
  54403. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  54404. }
  54405. else {
  54406. BABYLON.Tools.Warn("Function to remove was not found");
  54407. }
  54408. };
  54409. /**
  54410. * Register a function that will be executed after the physics step
  54411. */
  54412. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  54413. this._onAfterPhysicsStepCallbacks.push(func);
  54414. };
  54415. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  54416. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  54417. if (index > -1) {
  54418. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  54419. }
  54420. else {
  54421. BABYLON.Tools.Warn("Function to remove was not found");
  54422. }
  54423. };
  54424. /**
  54425. * register a function that will be executed when this impostor collides against a different body.
  54426. */
  54427. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  54428. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  54429. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  54430. };
  54431. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  54432. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  54433. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  54434. if (index > -1) {
  54435. this._onPhysicsCollideCallbacks.splice(index, 1);
  54436. }
  54437. else {
  54438. BABYLON.Tools.Warn("Function to remove was not found");
  54439. }
  54440. };
  54441. /**
  54442. * Apply a force
  54443. */
  54444. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  54445. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  54446. };
  54447. /**
  54448. * Apply an impulse
  54449. */
  54450. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  54451. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  54452. };
  54453. /**
  54454. * A help function to create a joint.
  54455. */
  54456. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  54457. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  54458. this.addJoint(otherImpostor, joint);
  54459. };
  54460. /**
  54461. * Add a joint to this impostor with a different impostor.
  54462. */
  54463. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  54464. this._joints.push({
  54465. otherImpostor: otherImpostor,
  54466. joint: joint
  54467. });
  54468. this._physicsEngine.addJoint(this, otherImpostor, joint);
  54469. };
  54470. /**
  54471. * Will keep this body still, in a sleep mode.
  54472. */
  54473. PhysicsImpostor.prototype.sleep = function () {
  54474. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  54475. };
  54476. /**
  54477. * Wake the body up.
  54478. */
  54479. PhysicsImpostor.prototype.wakeUp = function () {
  54480. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  54481. };
  54482. PhysicsImpostor.prototype.clone = function (newObject) {
  54483. if (!newObject)
  54484. return null;
  54485. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  54486. };
  54487. PhysicsImpostor.prototype.dispose = function () {
  54488. var _this = this;
  54489. //no dispose if no physics engine is available.
  54490. if (!this._physicsEngine) {
  54491. return;
  54492. }
  54493. this._joints.forEach(function (j) {
  54494. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  54495. });
  54496. //dispose the physics body
  54497. this._physicsEngine.removeImpostor(this);
  54498. if (this.parent) {
  54499. this.parent.forceUpdate();
  54500. }
  54501. else {
  54502. /*this._object.getChildMeshes().forEach(function(mesh) {
  54503. if (mesh.physicsImpostor) {
  54504. if (disposeChildren) {
  54505. mesh.physicsImpostor.dispose();
  54506. mesh.physicsImpostor = null;
  54507. }
  54508. }
  54509. })*/
  54510. }
  54511. };
  54512. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  54513. this._deltaPosition.copyFrom(position);
  54514. };
  54515. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  54516. if (!this._deltaRotation) {
  54517. this._deltaRotation = new BABYLON.Quaternion();
  54518. }
  54519. this._deltaRotation.copyFrom(rotation);
  54520. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  54521. };
  54522. return PhysicsImpostor;
  54523. }());
  54524. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  54525. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  54526. //Impostor types
  54527. PhysicsImpostor.NoImpostor = 0;
  54528. PhysicsImpostor.SphereImpostor = 1;
  54529. PhysicsImpostor.BoxImpostor = 2;
  54530. PhysicsImpostor.PlaneImpostor = 3;
  54531. PhysicsImpostor.MeshImpostor = 4;
  54532. PhysicsImpostor.CylinderImpostor = 7;
  54533. PhysicsImpostor.ParticleImpostor = 8;
  54534. PhysicsImpostor.HeightmapImpostor = 9;
  54535. BABYLON.PhysicsImpostor = PhysicsImpostor;
  54536. })(BABYLON || (BABYLON = {}));
  54537. //# sourceMappingURL=babylon.physicsImpostor.js.map
  54538. var BABYLON;
  54539. (function (BABYLON) {
  54540. var PhysicsEngine = (function () {
  54541. function PhysicsEngine(gravity, _physicsPlugin) {
  54542. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  54543. this._physicsPlugin = _physicsPlugin;
  54544. //new methods and parameters
  54545. this._impostors = [];
  54546. this._joints = [];
  54547. if (!this._physicsPlugin.isSupported()) {
  54548. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  54549. + "Please make sure it is included.");
  54550. }
  54551. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  54552. this.setGravity(gravity);
  54553. this.setTimeStep();
  54554. }
  54555. PhysicsEngine.prototype.setGravity = function (gravity) {
  54556. this.gravity = gravity;
  54557. this._physicsPlugin.setGravity(this.gravity);
  54558. };
  54559. /**
  54560. * Set the time step of the physics engine.
  54561. * default is 1/60.
  54562. * To slow it down, enter 1/600 for example.
  54563. * To speed it up, 1/30
  54564. * @param {number} newTimeStep the new timestep to apply to this world.
  54565. */
  54566. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  54567. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  54568. this._physicsPlugin.setTimeStep(newTimeStep);
  54569. };
  54570. PhysicsEngine.prototype.dispose = function () {
  54571. this._impostors.forEach(function (impostor) {
  54572. impostor.dispose();
  54573. });
  54574. this._physicsPlugin.dispose();
  54575. };
  54576. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  54577. return this._physicsPlugin.name;
  54578. };
  54579. /**
  54580. * Adding a new impostor for the impostor tracking.
  54581. * This will be done by the impostor itself.
  54582. * @param {PhysicsImpostor} impostor the impostor to add
  54583. */
  54584. PhysicsEngine.prototype.addImpostor = function (impostor) {
  54585. impostor.uniqueId = this._impostors.push(impostor);
  54586. //if no parent, generate the body
  54587. if (!impostor.parent) {
  54588. this._physicsPlugin.generatePhysicsBody(impostor);
  54589. }
  54590. };
  54591. /**
  54592. * Remove an impostor from the engine.
  54593. * This impostor and its mesh will not longer be updated by the physics engine.
  54594. * @param {PhysicsImpostor} impostor the impostor to remove
  54595. */
  54596. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  54597. var index = this._impostors.indexOf(impostor);
  54598. if (index > -1) {
  54599. var removed = this._impostors.splice(index, 1);
  54600. //Is it needed?
  54601. if (removed.length) {
  54602. //this will also remove it from the world.
  54603. removed[0].physicsBody = null;
  54604. }
  54605. }
  54606. };
  54607. /**
  54608. * Add a joint to the physics engine
  54609. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  54610. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  54611. * @param {PhysicsJoint} the joint that will connect both impostors.
  54612. */
  54613. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  54614. var impostorJoint = {
  54615. mainImpostor: mainImpostor,
  54616. connectedImpostor: connectedImpostor,
  54617. joint: joint
  54618. };
  54619. joint.physicsPlugin = this._physicsPlugin;
  54620. this._joints.push(impostorJoint);
  54621. this._physicsPlugin.generateJoint(impostorJoint);
  54622. };
  54623. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  54624. var matchingJoints = this._joints.filter(function (impostorJoint) {
  54625. return (impostorJoint.connectedImpostor === connectedImpostor
  54626. && impostorJoint.joint === joint
  54627. && impostorJoint.mainImpostor === mainImpostor);
  54628. });
  54629. if (matchingJoints.length) {
  54630. this._physicsPlugin.removeJoint(matchingJoints[0]);
  54631. //TODO remove it from the list as well
  54632. }
  54633. };
  54634. /**
  54635. * Called by the scene. no need to call it.
  54636. */
  54637. PhysicsEngine.prototype._step = function (delta) {
  54638. var _this = this;
  54639. //check if any mesh has no body / requires an update
  54640. this._impostors.forEach(function (impostor) {
  54641. if (impostor.isBodyInitRequired()) {
  54642. _this._physicsPlugin.generatePhysicsBody(impostor);
  54643. }
  54644. });
  54645. if (delta > 0.1) {
  54646. delta = 0.1;
  54647. }
  54648. else if (delta <= 0) {
  54649. delta = 1.0 / 60.0;
  54650. }
  54651. this._physicsPlugin.executeStep(delta, this._impostors);
  54652. };
  54653. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  54654. return this._physicsPlugin;
  54655. };
  54656. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  54657. for (var i = 0; i < this._impostors.length; ++i) {
  54658. if (this._impostors[i].object === object) {
  54659. return this._impostors[i];
  54660. }
  54661. }
  54662. };
  54663. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  54664. for (var i = 0; i < this._impostors.length; ++i) {
  54665. if (this._impostors[i].physicsBody === body) {
  54666. return this._impostors[i];
  54667. }
  54668. }
  54669. };
  54670. return PhysicsEngine;
  54671. }());
  54672. // Statics
  54673. PhysicsEngine.Epsilon = 0.001;
  54674. BABYLON.PhysicsEngine = PhysicsEngine;
  54675. })(BABYLON || (BABYLON = {}));
  54676. //# sourceMappingURL=babylon.physicsEngine.js.map
  54677. var BABYLON;
  54678. (function (BABYLON) {
  54679. var CannonJSPlugin = (function () {
  54680. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  54681. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  54682. if (iterations === void 0) { iterations = 10; }
  54683. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  54684. this.name = "CannonJSPlugin";
  54685. this._physicsMaterials = [];
  54686. this._fixedTimeStep = 1 / 60;
  54687. //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  54688. this._currentCollisionGroup = 2;
  54689. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  54690. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  54691. this._tmpPosition = BABYLON.Vector3.Zero();
  54692. this._tmpQuaternion = new BABYLON.Quaternion();
  54693. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  54694. this._tmpDeltaRotation = new BABYLON.Quaternion();
  54695. this._tmpUnityRotation = new BABYLON.Quaternion();
  54696. if (!this.isSupported()) {
  54697. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  54698. return;
  54699. }
  54700. this.world = new CANNON.World();
  54701. this.world.broadphase = new CANNON.NaiveBroadphase();
  54702. this.world.solver.iterations = iterations;
  54703. }
  54704. CannonJSPlugin.prototype.setGravity = function (gravity) {
  54705. this.world.gravity.copy(gravity);
  54706. };
  54707. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  54708. this._fixedTimeStep = timeStep;
  54709. };
  54710. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  54711. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0, 3);
  54712. };
  54713. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  54714. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  54715. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  54716. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  54717. };
  54718. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  54719. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  54720. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  54721. impostor.physicsBody.applyForce(impulse, worldPoint);
  54722. };
  54723. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  54724. //parent-child relationship. Does this impostor has a parent impostor?
  54725. if (impostor.parent) {
  54726. if (impostor.physicsBody) {
  54727. this.removePhysicsBody(impostor);
  54728. //TODO is that needed?
  54729. impostor.forceUpdate();
  54730. }
  54731. return;
  54732. }
  54733. //should a new body be created for this impostor?
  54734. if (impostor.isBodyInitRequired()) {
  54735. var shape = this._createShape(impostor);
  54736. //unregister events, if body is being changed
  54737. var oldBody = impostor.physicsBody;
  54738. if (oldBody) {
  54739. this.removePhysicsBody(impostor);
  54740. }
  54741. //create the body and material
  54742. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  54743. var bodyCreationObject = {
  54744. mass: impostor.getParam("mass"),
  54745. material: material
  54746. };
  54747. // A simple extend, in case native options were used.
  54748. var nativeOptions = impostor.getParam("nativeOptions");
  54749. for (var key in nativeOptions) {
  54750. if (nativeOptions.hasOwnProperty(key)) {
  54751. bodyCreationObject[key] = nativeOptions[key];
  54752. }
  54753. }
  54754. impostor.physicsBody = new CANNON.Body(bodyCreationObject);
  54755. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  54756. this.world.addEventListener("preStep", impostor.beforeStep);
  54757. this.world.addEventListener("postStep", impostor.afterStep);
  54758. impostor.physicsBody.addShape(shape);
  54759. this.world.add(impostor.physicsBody);
  54760. //try to keep the body moving in the right direction by taking old properties.
  54761. //Should be tested!
  54762. if (oldBody) {
  54763. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  54764. impostor.physicsBody[param].copy(oldBody[param]);
  54765. });
  54766. }
  54767. this._processChildMeshes(impostor);
  54768. }
  54769. //now update the body's transformation
  54770. this._updatePhysicsBodyTransformation(impostor);
  54771. };
  54772. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  54773. var _this = this;
  54774. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes() : [];
  54775. if (meshChildren.length) {
  54776. var processMesh = function (localPosition, mesh) {
  54777. var childImpostor = mesh.getPhysicsImpostor();
  54778. if (childImpostor) {
  54779. var parent = childImpostor.parent;
  54780. if (parent !== mainImpostor) {
  54781. var localPosition = mesh.position;
  54782. if (childImpostor.physicsBody) {
  54783. _this.removePhysicsBody(childImpostor);
  54784. childImpostor.physicsBody = null;
  54785. }
  54786. childImpostor.parent = mainImpostor;
  54787. childImpostor.resetUpdateFlags();
  54788. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  54789. //Add the mass of the children.
  54790. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  54791. }
  54792. }
  54793. mesh.getChildMeshes().forEach(processMesh.bind(_this, mesh.position));
  54794. };
  54795. meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
  54796. }
  54797. };
  54798. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  54799. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  54800. this.world.removeEventListener("preStep", impostor.beforeStep);
  54801. this.world.removeEventListener("postStep", impostor.afterStep);
  54802. this.world.remove(impostor.physicsBody);
  54803. };
  54804. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  54805. var mainBody = impostorJoint.mainImpostor.physicsBody;
  54806. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  54807. if (!mainBody || !connectedBody) {
  54808. return;
  54809. }
  54810. var constraint;
  54811. var jointData = impostorJoint.joint.jointData;
  54812. //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  54813. var constraintData = {
  54814. pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
  54815. pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
  54816. axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
  54817. axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
  54818. maxForce: jointData.nativeParams.maxForce,
  54819. collideConnected: !!jointData.collision
  54820. };
  54821. switch (impostorJoint.joint.type) {
  54822. case BABYLON.PhysicsJoint.HingeJoint:
  54823. case BABYLON.PhysicsJoint.Hinge2Joint:
  54824. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  54825. break;
  54826. case BABYLON.PhysicsJoint.DistanceJoint:
  54827. constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  54828. break;
  54829. case BABYLON.PhysicsJoint.SpringJoint:
  54830. var springData = jointData;
  54831. constraint = new CANNON.Spring(mainBody, connectedBody, {
  54832. restLength: springData.length,
  54833. stiffness: springData.stiffness,
  54834. damping: springData.damping,
  54835. localAnchorA: constraintData.pivotA,
  54836. localAnchorB: constraintData.pivotB
  54837. });
  54838. break;
  54839. case BABYLON.PhysicsJoint.LockJoint:
  54840. constraint = new CANNON.LockConstraint(mainBody, connectedBody, constraintData);
  54841. break;
  54842. case BABYLON.PhysicsJoint.PointToPointJoint:
  54843. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  54844. default:
  54845. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  54846. break;
  54847. }
  54848. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  54849. constraint.collideConnected = !!jointData.collision;
  54850. impostorJoint.joint.physicsJoint = constraint;
  54851. //don't add spring as constraint, as it is not one.
  54852. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  54853. this.world.addConstraint(constraint);
  54854. }
  54855. else {
  54856. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  54857. constraint.applyForce();
  54858. });
  54859. }
  54860. };
  54861. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  54862. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  54863. };
  54864. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  54865. var index;
  54866. var mat;
  54867. for (index = 0; index < this._physicsMaterials.length; index++) {
  54868. mat = this._physicsMaterials[index];
  54869. if (mat.friction === friction && mat.restitution === restitution) {
  54870. return mat;
  54871. }
  54872. }
  54873. var currentMat = new CANNON.Material(name);
  54874. currentMat.friction = friction;
  54875. currentMat.restitution = restitution;
  54876. this._physicsMaterials.push(currentMat);
  54877. return currentMat;
  54878. };
  54879. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  54880. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  54881. };
  54882. CannonJSPlugin.prototype._createShape = function (impostor) {
  54883. var object = impostor.object;
  54884. var returnValue;
  54885. var extendSize = impostor.getObjectExtendSize();
  54886. switch (impostor.type) {
  54887. case BABYLON.PhysicsImpostor.SphereImpostor:
  54888. var radiusX = extendSize.x;
  54889. var radiusY = extendSize.y;
  54890. var radiusZ = extendSize.z;
  54891. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  54892. break;
  54893. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  54894. case BABYLON.PhysicsImpostor.CylinderImpostor:
  54895. returnValue = new CANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  54896. break;
  54897. case BABYLON.PhysicsImpostor.BoxImpostor:
  54898. var box = extendSize.scale(0.5);
  54899. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  54900. break;
  54901. case BABYLON.PhysicsImpostor.PlaneImpostor:
  54902. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  54903. returnValue = new CANNON.Plane();
  54904. break;
  54905. case BABYLON.PhysicsImpostor.MeshImpostor:
  54906. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  54907. var rawFaces = object.getIndices ? object.getIndices() : [];
  54908. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  54909. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  54910. break;
  54911. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  54912. returnValue = this._createHeightmap(object);
  54913. break;
  54914. case BABYLON.PhysicsImpostor.ParticleImpostor:
  54915. returnValue = new CANNON.Particle();
  54916. break;
  54917. }
  54918. return returnValue;
  54919. };
  54920. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  54921. var pos = object.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54922. var matrix = [];
  54923. //For now pointDepth will not be used and will be automatically calculated.
  54924. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  54925. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  54926. var dim = Math.min(object.getBoundingInfo().boundingBox.extendSize.x, object.getBoundingInfo().boundingBox.extendSize.z);
  54927. var elementSize = dim * 2 / arraySize;
  54928. var minY = object.getBoundingInfo().boundingBox.extendSize.y;
  54929. for (var i = 0; i < pos.length; i = i + 3) {
  54930. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  54931. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  54932. var y = pos[i + 1] + minY;
  54933. if (!matrix[x]) {
  54934. matrix[x] = [];
  54935. }
  54936. if (!matrix[x][z]) {
  54937. matrix[x][z] = y;
  54938. }
  54939. matrix[x][z] = Math.max(y, matrix[x][z]);
  54940. }
  54941. for (var x = 0; x <= arraySize; ++x) {
  54942. if (!matrix[x]) {
  54943. var loc = 1;
  54944. while (!matrix[(x + loc) % arraySize]) {
  54945. loc++;
  54946. }
  54947. matrix[x] = matrix[(x + loc) % arraySize].slice();
  54948. //console.log("missing x", x);
  54949. }
  54950. for (var z = 0; z <= arraySize; ++z) {
  54951. if (!matrix[x][z]) {
  54952. var loc = 1;
  54953. var newValue;
  54954. while (newValue === undefined) {
  54955. newValue = matrix[x][(z + loc++) % arraySize];
  54956. }
  54957. matrix[x][z] = newValue;
  54958. }
  54959. }
  54960. }
  54961. var shape = new CANNON.Heightfield(matrix, {
  54962. elementSize: elementSize
  54963. });
  54964. //For future reference, needed for body transformation
  54965. shape.minY = minY;
  54966. return shape;
  54967. };
  54968. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  54969. var object = impostor.object;
  54970. //make sure it is updated...
  54971. object.computeWorldMatrix && object.computeWorldMatrix(true);
  54972. // The delta between the mesh position and the mesh bounding box center
  54973. var center = impostor.getObjectCenter();
  54974. this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
  54975. this._tmpPosition.copyFrom(center);
  54976. var quaternion = object.rotationQuaternion;
  54977. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  54978. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  54979. //-90 DEG in X, precalculated
  54980. quaternion = quaternion.multiply(this._minus90X);
  54981. //Invert! (Precalculated, 90 deg in X)
  54982. //No need to clone. this will never change.
  54983. impostor.setDeltaRotation(this._plus90X);
  54984. }
  54985. //If it is a heightfield, if should be centered.
  54986. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  54987. var mesh = object;
  54988. //calculate the correct body position:
  54989. var rotationQuaternion = mesh.rotationQuaternion;
  54990. mesh.rotationQuaternion = this._tmpUnityRotation;
  54991. mesh.computeWorldMatrix(true);
  54992. //get original center with no rotation
  54993. var c = center.clone();
  54994. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  54995. //rotation is back
  54996. mesh.rotationQuaternion = rotationQuaternion;
  54997. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  54998. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  54999. mesh.setPivotMatrix(p);
  55000. mesh.computeWorldMatrix(true);
  55001. //calculate the translation
  55002. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  55003. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  55004. //add it inverted to the delta
  55005. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.center.subtract(c));
  55006. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  55007. mesh.setPivotMatrix(oldPivot);
  55008. mesh.computeWorldMatrix(true);
  55009. }
  55010. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  55011. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  55012. this._tmpPosition.copyFrom(object.position);
  55013. }
  55014. impostor.setDeltaPosition(this._tmpDeltaPosition);
  55015. //Now update the impostor object
  55016. impostor.physicsBody.position.copy(this._tmpPosition);
  55017. impostor.physicsBody.quaternion.copy(quaternion);
  55018. };
  55019. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  55020. impostor.object.position.copyFrom(impostor.physicsBody.position);
  55021. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  55022. };
  55023. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  55024. impostor.physicsBody.position.copy(newPosition);
  55025. impostor.physicsBody.quaternion.copy(newRotation);
  55026. };
  55027. CannonJSPlugin.prototype.isSupported = function () {
  55028. return window.CANNON !== undefined;
  55029. };
  55030. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  55031. impostor.physicsBody.velocity.copy(velocity);
  55032. };
  55033. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  55034. impostor.physicsBody.angularVelocity.copy(velocity);
  55035. };
  55036. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  55037. var v = impostor.physicsBody.velocity;
  55038. if (!v)
  55039. return null;
  55040. return new BABYLON.Vector3(v.x, v.y, v.z);
  55041. };
  55042. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  55043. var v = impostor.physicsBody.angularVelocity;
  55044. if (!v)
  55045. return null;
  55046. return new BABYLON.Vector3(v.x, v.y, v.z);
  55047. };
  55048. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  55049. impostor.physicsBody.mass = mass;
  55050. impostor.physicsBody.updateMassProperties();
  55051. };
  55052. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  55053. impostor.physicsBody.sleep();
  55054. };
  55055. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  55056. impostor.physicsBody.wakeUp();
  55057. };
  55058. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  55059. joint.physicsJoint.distance = maxDistance;
  55060. };
  55061. CannonJSPlugin.prototype.enableMotor = function (joint, motorIndex) {
  55062. if (!motorIndex) {
  55063. joint.physicsJoint.enableMotor();
  55064. }
  55065. };
  55066. CannonJSPlugin.prototype.disableMotor = function (joint, motorIndex) {
  55067. if (!motorIndex) {
  55068. joint.physicsJoint.disableMotor();
  55069. }
  55070. };
  55071. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  55072. if (!motorIndex) {
  55073. joint.physicsJoint.enableMotor();
  55074. joint.physicsJoint.setMotorSpeed(speed);
  55075. if (maxForce) {
  55076. this.setLimit(joint, maxForce);
  55077. }
  55078. }
  55079. };
  55080. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  55081. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  55082. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  55083. };
  55084. CannonJSPlugin.prototype.dispose = function () {
  55085. //nothing to do, actually.
  55086. };
  55087. return CannonJSPlugin;
  55088. }());
  55089. BABYLON.CannonJSPlugin = CannonJSPlugin;
  55090. })(BABYLON || (BABYLON = {}));
  55091. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  55092. var BABYLON;
  55093. (function (BABYLON) {
  55094. var OimoJSPlugin = (function () {
  55095. function OimoJSPlugin(iterations) {
  55096. this.name = "OimoJSPlugin";
  55097. this._tmpImpostorsArray = [];
  55098. this._tmpPositionVector = BABYLON.Vector3.Zero();
  55099. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  55100. this.world.worldscale(1);
  55101. this.world.clear();
  55102. //making sure no stats are calculated
  55103. this.world.isNoStat = true;
  55104. }
  55105. OimoJSPlugin.prototype.setGravity = function (gravity) {
  55106. this.world.gravity.copy(gravity);
  55107. };
  55108. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  55109. this.world.timeStep = timeStep;
  55110. };
  55111. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  55112. var _this = this;
  55113. impostors.forEach(function (impostor) {
  55114. impostor.beforeStep();
  55115. });
  55116. this.world.step();
  55117. impostors.forEach(function (impostor) {
  55118. impostor.afterStep();
  55119. //update the ordered impostors array
  55120. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  55121. });
  55122. //check for collisions
  55123. var contact = this.world.contacts;
  55124. while (contact !== null) {
  55125. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  55126. contact = contact.next;
  55127. continue;
  55128. }
  55129. //is this body colliding with any other? get the impostor
  55130. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  55131. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  55132. if (!mainImpostor || !collidingImpostor) {
  55133. contact = contact.next;
  55134. continue;
  55135. }
  55136. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  55137. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  55138. contact = contact.next;
  55139. }
  55140. };
  55141. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  55142. var mass = impostor.physicsBody.massInfo.mass;
  55143. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  55144. };
  55145. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  55146. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  55147. this.applyImpulse(impostor, force, contactPoint);
  55148. };
  55149. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  55150. var _this = this;
  55151. //parent-child relationship. Does this impostor has a parent impostor?
  55152. if (impostor.parent) {
  55153. if (impostor.physicsBody) {
  55154. this.removePhysicsBody(impostor);
  55155. //TODO is that needed?
  55156. impostor.forceUpdate();
  55157. }
  55158. return;
  55159. }
  55160. if (impostor.isBodyInitRequired()) {
  55161. var bodyConfig = {
  55162. name: impostor.uniqueId,
  55163. //Oimo must have mass, also for static objects.
  55164. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  55165. size: [],
  55166. type: [],
  55167. pos: [],
  55168. rot: [],
  55169. move: impostor.getParam("mass") !== 0,
  55170. //Supporting older versions of Oimo
  55171. world: this.world
  55172. };
  55173. var impostors = [impostor];
  55174. var addToArray = function (parent) {
  55175. if (!parent.getChildMeshes)
  55176. return;
  55177. parent.getChildMeshes().forEach(function (m) {
  55178. if (m.physicsImpostor) {
  55179. impostors.push(m.physicsImpostor);
  55180. m.physicsImpostor._init();
  55181. }
  55182. });
  55183. };
  55184. addToArray(impostor.object);
  55185. var checkWithEpsilon_1 = function (value) {
  55186. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  55187. };
  55188. impostors.forEach(function (i) {
  55189. //get the correct bounding box
  55190. var oldQuaternion = i.object.rotationQuaternion;
  55191. var rot = new OIMO.Euler().setFromQuaternion({
  55192. x: impostor.object.rotationQuaternion.x,
  55193. y: impostor.object.rotationQuaternion.y,
  55194. z: impostor.object.rotationQuaternion.z,
  55195. s: impostor.object.rotationQuaternion.w
  55196. });
  55197. var extendSize = i.getObjectExtendSize();
  55198. if (i === impostor) {
  55199. var center = impostor.getObjectCenter();
  55200. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  55201. //Can also use Array.prototype.push.apply
  55202. bodyConfig.pos.push(center.x);
  55203. bodyConfig.pos.push(center.y);
  55204. bodyConfig.pos.push(center.z);
  55205. //tmp solution
  55206. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  55207. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  55208. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  55209. }
  55210. else {
  55211. bodyConfig.pos.push(i.object.position.x);
  55212. bodyConfig.pos.push(i.object.position.y);
  55213. bodyConfig.pos.push(i.object.position.z);
  55214. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  55215. bodyConfig.rot.push(0);
  55216. bodyConfig.rot.push(0);
  55217. bodyConfig.rot.push(0);
  55218. }
  55219. // register mesh
  55220. switch (i.type) {
  55221. case BABYLON.PhysicsImpostor.ParticleImpostor:
  55222. BABYLON.Tools.Warn("No Particle support in Oimo.js. using SphereImpostor instead");
  55223. case BABYLON.PhysicsImpostor.SphereImpostor:
  55224. var radiusX = extendSize.x;
  55225. var radiusY = extendSize.y;
  55226. var radiusZ = extendSize.z;
  55227. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  55228. bodyConfig.type.push('sphere');
  55229. //due to the way oimo works with compounds, add 3 times
  55230. bodyConfig.size.push(size);
  55231. bodyConfig.size.push(size);
  55232. bodyConfig.size.push(size);
  55233. break;
  55234. case BABYLON.PhysicsImpostor.CylinderImpostor:
  55235. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  55236. var sizeY = checkWithEpsilon_1(extendSize.y);
  55237. bodyConfig.type.push('cylinder');
  55238. bodyConfig.size.push(sizeX);
  55239. bodyConfig.size.push(sizeY);
  55240. //due to the way oimo works with compounds, add one more value.
  55241. bodyConfig.size.push(sizeY);
  55242. break;
  55243. case BABYLON.PhysicsImpostor.PlaneImpostor:
  55244. case BABYLON.PhysicsImpostor.BoxImpostor:
  55245. default:
  55246. var sizeX = checkWithEpsilon_1(extendSize.x);
  55247. var sizeY = checkWithEpsilon_1(extendSize.y);
  55248. var sizeZ = checkWithEpsilon_1(extendSize.z);
  55249. bodyConfig.type.push('box');
  55250. bodyConfig.size.push(sizeX);
  55251. bodyConfig.size.push(sizeY);
  55252. bodyConfig.size.push(sizeZ);
  55253. break;
  55254. }
  55255. //actually not needed, but hey...
  55256. i.object.rotationQuaternion = oldQuaternion;
  55257. });
  55258. impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  55259. }
  55260. else {
  55261. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  55262. }
  55263. impostor.setDeltaPosition(this._tmpPositionVector);
  55264. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  55265. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  55266. };
  55267. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  55268. //impostor.physicsBody.dispose();
  55269. //Same as : (older oimo versions)
  55270. this.world.removeRigidBody(impostor.physicsBody);
  55271. };
  55272. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  55273. var mainBody = impostorJoint.mainImpostor.physicsBody;
  55274. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  55275. if (!mainBody || !connectedBody) {
  55276. return;
  55277. }
  55278. var jointData = impostorJoint.joint.jointData;
  55279. var options = jointData.nativeParams || {};
  55280. var type;
  55281. var nativeJointData = {
  55282. body1: mainBody,
  55283. body2: connectedBody,
  55284. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  55285. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  55286. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  55287. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  55288. min: options.min,
  55289. max: options.max,
  55290. collision: options.collision || jointData.collision,
  55291. spring: options.spring,
  55292. //supporting older version of Oimo
  55293. world: this.world
  55294. };
  55295. switch (impostorJoint.joint.type) {
  55296. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  55297. type = "jointBall";
  55298. break;
  55299. case BABYLON.PhysicsJoint.SpringJoint:
  55300. BABYLON.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  55301. var springData = jointData;
  55302. nativeJointData.min = springData.length || nativeJointData.min;
  55303. //Max should also be set, just make sure it is at least min
  55304. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  55305. case BABYLON.PhysicsJoint.DistanceJoint:
  55306. type = "jointDistance";
  55307. nativeJointData.max = jointData.maxDistance;
  55308. break;
  55309. case BABYLON.PhysicsJoint.PrismaticJoint:
  55310. type = "jointPrisme";
  55311. break;
  55312. case BABYLON.PhysicsJoint.SliderJoint:
  55313. type = "jointSlide";
  55314. break;
  55315. case BABYLON.PhysicsJoint.WheelJoint:
  55316. type = "jointWheel";
  55317. break;
  55318. case BABYLON.PhysicsJoint.HingeJoint:
  55319. default:
  55320. type = "jointHinge";
  55321. break;
  55322. }
  55323. nativeJointData.type = type;
  55324. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  55325. };
  55326. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  55327. //Bug in Oimo prevents us from disposing a joint in the playground
  55328. //joint.joint.physicsJoint.dispose();
  55329. //So we will bruteforce it!
  55330. try {
  55331. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  55332. }
  55333. catch (e) {
  55334. BABYLON.Tools.Warn(e);
  55335. }
  55336. };
  55337. OimoJSPlugin.prototype.isSupported = function () {
  55338. return OIMO !== undefined;
  55339. };
  55340. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  55341. if (!impostor.physicsBody.sleeping) {
  55342. //TODO check that
  55343. if (impostor.physicsBody.shapes.next) {
  55344. var parentShape = this._getLastShape(impostor.physicsBody);
  55345. impostor.object.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  55346. impostor.object.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  55347. impostor.object.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  55348. }
  55349. else {
  55350. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  55351. }
  55352. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  55353. impostor.object.rotationQuaternion.normalize();
  55354. }
  55355. };
  55356. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  55357. var body = impostor.physicsBody;
  55358. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  55359. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  55360. body.syncShapes();
  55361. body.awake();
  55362. };
  55363. OimoJSPlugin.prototype._getLastShape = function (body) {
  55364. var lastShape = body.shapes;
  55365. while (lastShape.next) {
  55366. lastShape = lastShape.next;
  55367. }
  55368. return lastShape;
  55369. };
  55370. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  55371. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  55372. };
  55373. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  55374. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  55375. };
  55376. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  55377. var v = impostor.physicsBody.linearVelocity;
  55378. if (!v)
  55379. return null;
  55380. return new BABYLON.Vector3(v.x, v.y, v.z);
  55381. };
  55382. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  55383. var v = impostor.physicsBody.angularVelocity;
  55384. if (!v)
  55385. return null;
  55386. return new BABYLON.Vector3(v.x, v.y, v.z);
  55387. };
  55388. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  55389. var staticBody = mass === 0;
  55390. //this will actually set the body's density and not its mass.
  55391. //But this is how oimo treats the mass variable.
  55392. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  55393. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  55394. };
  55395. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  55396. impostor.physicsBody.sleep();
  55397. };
  55398. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  55399. impostor.physicsBody.awake();
  55400. };
  55401. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  55402. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  55403. if (minDistance !== void 0) {
  55404. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  55405. }
  55406. };
  55407. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  55408. //TODO separate rotational and transational motors.
  55409. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  55410. if (motor) {
  55411. motor.setMotor(speed, maxForce);
  55412. }
  55413. };
  55414. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  55415. //TODO separate rotational and transational motors.
  55416. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  55417. if (motor) {
  55418. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  55419. }
  55420. };
  55421. OimoJSPlugin.prototype.dispose = function () {
  55422. this.world.clear();
  55423. };
  55424. return OimoJSPlugin;
  55425. }());
  55426. BABYLON.OimoJSPlugin = OimoJSPlugin;
  55427. })(BABYLON || (BABYLON = {}));
  55428. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  55429. var BABYLON;
  55430. (function (BABYLON) {
  55431. var Internals;
  55432. (function (Internals) {
  55433. /*
  55434. * Based on jsTGALoader - Javascript loader for TGA file
  55435. * By Vincent Thibault
  55436. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  55437. */
  55438. var TGATools = (function () {
  55439. function TGATools() {
  55440. }
  55441. TGATools.GetTGAHeader = function (data) {
  55442. var offset = 0;
  55443. var header = {
  55444. id_length: data[offset++],
  55445. colormap_type: data[offset++],
  55446. image_type: data[offset++],
  55447. colormap_index: data[offset++] | data[offset++] << 8,
  55448. colormap_length: data[offset++] | data[offset++] << 8,
  55449. colormap_size: data[offset++],
  55450. origin: [
  55451. data[offset++] | data[offset++] << 8,
  55452. data[offset++] | data[offset++] << 8
  55453. ],
  55454. width: data[offset++] | data[offset++] << 8,
  55455. height: data[offset++] | data[offset++] << 8,
  55456. pixel_size: data[offset++],
  55457. flags: data[offset++]
  55458. };
  55459. return header;
  55460. };
  55461. TGATools.UploadContent = function (gl, data) {
  55462. // Not enough data to contain header ?
  55463. if (data.length < 19) {
  55464. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  55465. return;
  55466. }
  55467. // Read Header
  55468. var offset = 18;
  55469. var header = TGATools.GetTGAHeader(data);
  55470. // Assume it's a valid Targa file.
  55471. if (header.id_length + offset > data.length) {
  55472. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  55473. return;
  55474. }
  55475. // Skip not needed data
  55476. offset += header.id_length;
  55477. var use_rle = false;
  55478. var use_pal = false;
  55479. var use_rgb = false;
  55480. var use_grey = false;
  55481. // Get some informations.
  55482. switch (header.image_type) {
  55483. case TGATools._TYPE_RLE_INDEXED:
  55484. use_rle = true;
  55485. case TGATools._TYPE_INDEXED:
  55486. use_pal = true;
  55487. break;
  55488. case TGATools._TYPE_RLE_RGB:
  55489. use_rle = true;
  55490. case TGATools._TYPE_RGB:
  55491. use_rgb = true;
  55492. break;
  55493. case TGATools._TYPE_RLE_GREY:
  55494. use_rle = true;
  55495. case TGATools._TYPE_GREY:
  55496. use_grey = true;
  55497. break;
  55498. }
  55499. var pixel_data;
  55500. var numAlphaBits = header.flags & 0xf;
  55501. var pixel_size = header.pixel_size >> 3;
  55502. var pixel_total = header.width * header.height * pixel_size;
  55503. // Read palettes
  55504. var palettes;
  55505. if (use_pal) {
  55506. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  55507. }
  55508. // Read LRE
  55509. if (use_rle) {
  55510. pixel_data = new Uint8Array(pixel_total);
  55511. var c, count, i;
  55512. var localOffset = 0;
  55513. var pixels = new Uint8Array(pixel_size);
  55514. while (offset < pixel_total && localOffset < pixel_total) {
  55515. c = data[offset++];
  55516. count = (c & 0x7f) + 1;
  55517. // RLE pixels
  55518. if (c & 0x80) {
  55519. // Bind pixel tmp array
  55520. for (i = 0; i < pixel_size; ++i) {
  55521. pixels[i] = data[offset++];
  55522. }
  55523. // Copy pixel array
  55524. for (i = 0; i < count; ++i) {
  55525. pixel_data.set(pixels, localOffset + i * pixel_size);
  55526. }
  55527. localOffset += pixel_size * count;
  55528. }
  55529. else {
  55530. count *= pixel_size;
  55531. for (i = 0; i < count; ++i) {
  55532. pixel_data[localOffset + i] = data[offset++];
  55533. }
  55534. localOffset += count;
  55535. }
  55536. }
  55537. }
  55538. else {
  55539. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  55540. }
  55541. // Load to texture
  55542. var x_start, y_start, x_step, y_step, y_end, x_end;
  55543. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  55544. default:
  55545. case TGATools._ORIGIN_UL:
  55546. x_start = 0;
  55547. x_step = 1;
  55548. x_end = header.width;
  55549. y_start = 0;
  55550. y_step = 1;
  55551. y_end = header.height;
  55552. break;
  55553. case TGATools._ORIGIN_BL:
  55554. x_start = 0;
  55555. x_step = 1;
  55556. x_end = header.width;
  55557. y_start = header.height - 1;
  55558. y_step = -1;
  55559. y_end = -1;
  55560. break;
  55561. case TGATools._ORIGIN_UR:
  55562. x_start = header.width - 1;
  55563. x_step = -1;
  55564. x_end = -1;
  55565. y_start = 0;
  55566. y_step = 1;
  55567. y_end = header.height;
  55568. break;
  55569. case TGATools._ORIGIN_BR:
  55570. x_start = header.width - 1;
  55571. x_step = -1;
  55572. x_end = -1;
  55573. y_start = header.height - 1;
  55574. y_step = -1;
  55575. y_end = -1;
  55576. break;
  55577. }
  55578. // Load the specify method
  55579. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  55580. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  55581. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  55582. };
  55583. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  55584. var image = pixel_data, colormap = palettes;
  55585. var width = header.width, height = header.height;
  55586. var color, i = 0, x, y;
  55587. var imageData = new Uint8Array(width * height * 4);
  55588. for (y = y_start; y !== y_end; y += y_step) {
  55589. for (x = x_start; x !== x_end; x += x_step, i++) {
  55590. color = image[i];
  55591. imageData[(x + width * y) * 4 + 3] = 255;
  55592. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  55593. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  55594. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  55595. }
  55596. }
  55597. return imageData;
  55598. };
  55599. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  55600. var image = pixel_data;
  55601. var width = header.width, height = header.height;
  55602. var color, i = 0, x, y;
  55603. var imageData = new Uint8Array(width * height * 4);
  55604. for (y = y_start; y !== y_end; y += y_step) {
  55605. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  55606. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  55607. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  55608. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  55609. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  55610. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  55611. }
  55612. }
  55613. return imageData;
  55614. };
  55615. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  55616. var image = pixel_data;
  55617. var width = header.width, height = header.height;
  55618. var i = 0, x, y;
  55619. var imageData = new Uint8Array(width * height * 4);
  55620. for (y = y_start; y !== y_end; y += y_step) {
  55621. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  55622. imageData[(x + width * y) * 4 + 3] = 255;
  55623. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  55624. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  55625. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  55626. }
  55627. }
  55628. return imageData;
  55629. };
  55630. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  55631. var image = pixel_data;
  55632. var width = header.width, height = header.height;
  55633. var i = 0, x, y;
  55634. var imageData = new Uint8Array(width * height * 4);
  55635. for (y = y_start; y !== y_end; y += y_step) {
  55636. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  55637. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  55638. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  55639. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  55640. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  55641. }
  55642. }
  55643. return imageData;
  55644. };
  55645. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  55646. var image = pixel_data;
  55647. var width = header.width, height = header.height;
  55648. var color, i = 0, x, y;
  55649. var imageData = new Uint8Array(width * height * 4);
  55650. for (y = y_start; y !== y_end; y += y_step) {
  55651. for (x = x_start; x !== x_end; x += x_step, i++) {
  55652. color = image[i];
  55653. imageData[(x + width * y) * 4 + 0] = color;
  55654. imageData[(x + width * y) * 4 + 1] = color;
  55655. imageData[(x + width * y) * 4 + 2] = color;
  55656. imageData[(x + width * y) * 4 + 3] = 255;
  55657. }
  55658. }
  55659. return imageData;
  55660. };
  55661. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  55662. var image = pixel_data;
  55663. var width = header.width, height = header.height;
  55664. var i = 0, x, y;
  55665. var imageData = new Uint8Array(width * height * 4);
  55666. for (y = y_start; y !== y_end; y += y_step) {
  55667. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  55668. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  55669. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  55670. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  55671. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  55672. }
  55673. }
  55674. return imageData;
  55675. };
  55676. return TGATools;
  55677. }());
  55678. TGATools._TYPE_NO_DATA = 0;
  55679. TGATools._TYPE_INDEXED = 1;
  55680. TGATools._TYPE_RGB = 2;
  55681. TGATools._TYPE_GREY = 3;
  55682. TGATools._TYPE_RLE_INDEXED = 9;
  55683. TGATools._TYPE_RLE_RGB = 10;
  55684. TGATools._TYPE_RLE_GREY = 11;
  55685. TGATools._ORIGIN_MASK = 0x30;
  55686. TGATools._ORIGIN_SHIFT = 0x04;
  55687. TGATools._ORIGIN_BL = 0x00;
  55688. TGATools._ORIGIN_BR = 0x01;
  55689. TGATools._ORIGIN_UL = 0x02;
  55690. TGATools._ORIGIN_UR = 0x03;
  55691. Internals.TGATools = TGATools;
  55692. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  55693. })(BABYLON || (BABYLON = {}));
  55694. //# sourceMappingURL=babylon.tga.js.map
  55695. var BABYLON;
  55696. (function (BABYLON) {
  55697. var Internals;
  55698. (function (Internals) {
  55699. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  55700. // All values and structures referenced from:
  55701. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  55702. var DDS_MAGIC = 0x20534444;
  55703. 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;
  55704. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  55705. 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;
  55706. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  55707. function FourCCToInt32(value) {
  55708. return value.charCodeAt(0) +
  55709. (value.charCodeAt(1) << 8) +
  55710. (value.charCodeAt(2) << 16) +
  55711. (value.charCodeAt(3) << 24);
  55712. }
  55713. function Int32ToFourCC(value) {
  55714. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  55715. }
  55716. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  55717. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  55718. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  55719. var headerLengthInt = 31; // The header length in 32 bit ints
  55720. // Offsets into the header array
  55721. var off_magic = 0;
  55722. var off_size = 1;
  55723. var off_flags = 2;
  55724. var off_height = 3;
  55725. var off_width = 4;
  55726. var off_mipmapCount = 7;
  55727. var off_pfFlags = 20;
  55728. var off_pfFourCC = 21;
  55729. var off_RGBbpp = 22;
  55730. var off_RMask = 23;
  55731. var off_GMask = 24;
  55732. var off_BMask = 25;
  55733. var off_AMask = 26;
  55734. var off_caps1 = 27;
  55735. var off_caps2 = 28;
  55736. ;
  55737. var DDSTools = (function () {
  55738. function DDSTools() {
  55739. }
  55740. DDSTools.GetDDSInfo = function (arrayBuffer) {
  55741. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  55742. var mipmapCount = 1;
  55743. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  55744. mipmapCount = Math.max(1, header[off_mipmapCount]);
  55745. }
  55746. return {
  55747. width: header[off_width],
  55748. height: header[off_height],
  55749. mipmapCount: mipmapCount,
  55750. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  55751. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  55752. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  55753. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  55754. };
  55755. };
  55756. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  55757. var byteArray = new Uint8Array(dataLength);
  55758. var srcData = new Uint8Array(arrayBuffer);
  55759. var index = 0;
  55760. for (var y = height - 1; y >= 0; y--) {
  55761. for (var x = 0; x < width; x++) {
  55762. var srcPos = dataOffset + (x + y * width) * 4;
  55763. byteArray[index + 2] = srcData[srcPos];
  55764. byteArray[index + 1] = srcData[srcPos + 1];
  55765. byteArray[index] = srcData[srcPos + 2];
  55766. byteArray[index + 3] = srcData[srcPos + 3];
  55767. index += 4;
  55768. }
  55769. }
  55770. return byteArray;
  55771. };
  55772. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  55773. var byteArray = new Uint8Array(dataLength);
  55774. var srcData = new Uint8Array(arrayBuffer);
  55775. var index = 0;
  55776. for (var y = height - 1; y >= 0; y--) {
  55777. for (var x = 0; x < width; x++) {
  55778. var srcPos = dataOffset + (x + y * width) * 3;
  55779. byteArray[index + 2] = srcData[srcPos];
  55780. byteArray[index + 1] = srcData[srcPos + 1];
  55781. byteArray[index] = srcData[srcPos + 2];
  55782. index += 3;
  55783. }
  55784. }
  55785. return byteArray;
  55786. };
  55787. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  55788. var byteArray = new Uint8Array(dataLength);
  55789. var srcData = new Uint8Array(arrayBuffer);
  55790. var index = 0;
  55791. for (var y = height - 1; y >= 0; y--) {
  55792. for (var x = 0; x < width; x++) {
  55793. var srcPos = dataOffset + (x + y * width);
  55794. byteArray[index] = srcData[srcPos];
  55795. index++;
  55796. }
  55797. }
  55798. return byteArray;
  55799. };
  55800. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  55801. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  55802. if (header[off_magic] != DDS_MAGIC) {
  55803. BABYLON.Tools.Error("Invalid magic number in DDS header");
  55804. return;
  55805. }
  55806. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  55807. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  55808. return;
  55809. }
  55810. if (info.isFourCC) {
  55811. fourCC = header[off_pfFourCC];
  55812. switch (fourCC) {
  55813. case FOURCC_DXT1:
  55814. blockBytes = 8;
  55815. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  55816. break;
  55817. case FOURCC_DXT3:
  55818. blockBytes = 16;
  55819. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  55820. break;
  55821. case FOURCC_DXT5:
  55822. blockBytes = 16;
  55823. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  55824. break;
  55825. default:
  55826. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  55827. return;
  55828. }
  55829. }
  55830. mipmapCount = 1;
  55831. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  55832. mipmapCount = Math.max(1, header[off_mipmapCount]);
  55833. }
  55834. var bpp = header[off_RGBbpp];
  55835. for (var face = 0; face < faces; face++) {
  55836. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  55837. width = header[off_width];
  55838. height = header[off_height];
  55839. dataOffset = header[off_size] + 4;
  55840. for (i = 0; i < mipmapCount; ++i) {
  55841. if (info.isRGB) {
  55842. if (bpp === 24) {
  55843. dataLength = width * height * 3;
  55844. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  55845. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  55846. }
  55847. else {
  55848. dataLength = width * height * 4;
  55849. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  55850. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  55851. }
  55852. }
  55853. else if (info.isLuminance) {
  55854. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  55855. var unpaddedRowSize = width;
  55856. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  55857. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  55858. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  55859. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  55860. }
  55861. else {
  55862. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  55863. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  55864. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  55865. }
  55866. dataOffset += dataLength;
  55867. width *= 0.5;
  55868. height *= 0.5;
  55869. width = Math.max(1.0, width);
  55870. height = Math.max(1.0, height);
  55871. }
  55872. }
  55873. };
  55874. return DDSTools;
  55875. }());
  55876. Internals.DDSTools = DDSTools;
  55877. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  55878. })(BABYLON || (BABYLON = {}));
  55879. //# sourceMappingURL=babylon.dds.js.map
  55880. var BABYLON;
  55881. (function (BABYLON) {
  55882. var Internals;
  55883. (function (Internals) {
  55884. /**
  55885. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  55886. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  55887. */
  55888. var KhronosTextureContainer = (function () {
  55889. /**
  55890. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  55891. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  55892. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  55893. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  55894. */
  55895. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  55896. this.arrayBuffer = arrayBuffer;
  55897. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  55898. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  55899. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  55900. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  55901. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  55902. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  55903. BABYLON.Tools.Error("texture missing KTX identifier");
  55904. return;
  55905. }
  55906. // load the reset of the header in native 32 bit int
  55907. var header = new Int32Array(this.arrayBuffer, 12, 13);
  55908. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  55909. var oppositeEndianess = header[0] === 0x01020304;
  55910. // read all the header elements in order they exist in the file, without modification (sans endainness)
  55911. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  55912. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  55913. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  55914. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  55915. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  55916. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  55917. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  55918. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  55919. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  55920. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  55921. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  55922. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  55923. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  55924. if (this.glType !== 0) {
  55925. BABYLON.Tools.Error("only compressed formats currently supported");
  55926. return;
  55927. }
  55928. else {
  55929. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  55930. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  55931. }
  55932. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  55933. BABYLON.Tools.Error("only 2D textures currently supported");
  55934. return;
  55935. }
  55936. if (this.numberOfArrayElements !== 0) {
  55937. BABYLON.Tools.Error("texture arrays not currently supported");
  55938. return;
  55939. }
  55940. if (this.numberOfFaces !== facesExpected) {
  55941. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  55942. return;
  55943. }
  55944. // we now have a completely validated file, so could use existence of loadType as success
  55945. // would need to make this more elaborate & adjust checks above to support more than one load type
  55946. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  55947. }
  55948. // not as fast hardware based, but will probably never need to use
  55949. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  55950. return ((val & 0xFF) << 24)
  55951. | ((val & 0xFF00) << 8)
  55952. | ((val >> 8) & 0xFF00)
  55953. | ((val >> 24) & 0xFF);
  55954. };
  55955. /**
  55956. * It is assumed that the texture has already been created & is currently bound
  55957. */
  55958. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  55959. switch (this.loadType) {
  55960. case KhronosTextureContainer.COMPRESSED_2D:
  55961. this._upload2DCompressedLevels(gl, loadMipmaps);
  55962. break;
  55963. case KhronosTextureContainer.TEX_2D:
  55964. case KhronosTextureContainer.COMPRESSED_3D:
  55965. case KhronosTextureContainer.TEX_3D:
  55966. }
  55967. };
  55968. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  55969. // initialize width & height for level 1
  55970. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  55971. var width = this.pixelWidth;
  55972. var height = this.pixelHeight;
  55973. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  55974. for (var level = 0; level < mipmapCount; level++) {
  55975. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  55976. for (var face = 0; face < this.numberOfFaces; face++) {
  55977. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  55978. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  55979. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  55980. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  55981. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  55982. }
  55983. width = Math.max(1.0, width * 0.5);
  55984. height = Math.max(1.0, height * 0.5);
  55985. }
  55986. };
  55987. return KhronosTextureContainer;
  55988. }());
  55989. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  55990. // load types
  55991. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  55992. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  55993. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  55994. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  55995. Internals.KhronosTextureContainer = KhronosTextureContainer;
  55996. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  55997. })(BABYLON || (BABYLON = {}));
  55998. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  55999. var BABYLON;
  56000. (function (BABYLON) {
  56001. var Debug;
  56002. (function (Debug) {
  56003. /**
  56004. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  56005. */
  56006. var SkeletonViewer = (function () {
  56007. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  56008. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  56009. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  56010. this.skeleton = skeleton;
  56011. this.mesh = mesh;
  56012. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  56013. this.renderingGroupId = renderingGroupId;
  56014. this.color = BABYLON.Color3.White();
  56015. this._debugLines = [];
  56016. this._isEnabled = false;
  56017. this._scene = scene;
  56018. this.update();
  56019. this._renderFunction = this.update.bind(this);
  56020. }
  56021. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  56022. get: function () {
  56023. return this._isEnabled;
  56024. },
  56025. set: function (value) {
  56026. if (this._isEnabled === value) {
  56027. return;
  56028. }
  56029. this._isEnabled = value;
  56030. if (value) {
  56031. this._scene.registerBeforeRender(this._renderFunction);
  56032. }
  56033. else {
  56034. this._scene.unregisterBeforeRender(this._renderFunction);
  56035. }
  56036. },
  56037. enumerable: true,
  56038. configurable: true
  56039. });
  56040. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  56041. if (x === void 0) { x = 0; }
  56042. if (y === void 0) { y = 0; }
  56043. if (z === void 0) { z = 0; }
  56044. var tmat = BABYLON.Tmp.Matrix[0];
  56045. var parentBone = bone.getParent();
  56046. tmat.copyFrom(bone.getLocalMatrix());
  56047. if (x !== 0 || y !== 0 || z !== 0) {
  56048. var tmat2 = BABYLON.Tmp.Matrix[1];
  56049. BABYLON.Matrix.IdentityToRef(tmat2);
  56050. tmat2.m[12] = x;
  56051. tmat2.m[13] = y;
  56052. tmat2.m[14] = z;
  56053. tmat2.multiplyToRef(tmat, tmat);
  56054. }
  56055. if (parentBone) {
  56056. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  56057. }
  56058. tmat.multiplyToRef(meshMat, tmat);
  56059. position.x = tmat.m[12];
  56060. position.y = tmat.m[13];
  56061. position.z = tmat.m[14];
  56062. };
  56063. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  56064. var len = bones.length;
  56065. for (var i = 0; i < len; i++) {
  56066. var bone = bones[i];
  56067. var points = this._debugLines[i];
  56068. if (!points) {
  56069. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  56070. this._debugLines[i] = points;
  56071. }
  56072. this._getBonePosition(points[0], bone, meshMat);
  56073. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  56074. }
  56075. };
  56076. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  56077. var len = bones.length;
  56078. var boneNum = 0;
  56079. for (var i = len - 1; i >= 0; i--) {
  56080. var childBone = bones[i];
  56081. var parentBone = childBone.getParent();
  56082. if (!parentBone) {
  56083. continue;
  56084. }
  56085. var points = this._debugLines[boneNum];
  56086. if (!points) {
  56087. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  56088. this._debugLines[boneNum] = points;
  56089. }
  56090. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  56091. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  56092. boneNum++;
  56093. }
  56094. };
  56095. SkeletonViewer.prototype.update = function () {
  56096. if (this.autoUpdateBonesMatrices) {
  56097. this.skeleton.computeAbsoluteTransforms();
  56098. }
  56099. if (this.skeleton.bones[0].length === undefined) {
  56100. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  56101. }
  56102. else {
  56103. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  56104. }
  56105. if (!this._debugMesh) {
  56106. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  56107. this._debugMesh.renderingGroupId = this.renderingGroupId;
  56108. }
  56109. else {
  56110. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  56111. }
  56112. this._debugMesh.color = this.color;
  56113. };
  56114. SkeletonViewer.prototype.dispose = function () {
  56115. if (this._debugMesh) {
  56116. this.isEnabled = false;
  56117. this._debugMesh.dispose();
  56118. this._debugMesh = null;
  56119. }
  56120. };
  56121. return SkeletonViewer;
  56122. }());
  56123. Debug.SkeletonViewer = SkeletonViewer;
  56124. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  56125. })(BABYLON || (BABYLON = {}));
  56126. //# sourceMappingURL=babylon.skeletonViewer.js.map
  56127. var BABYLON;
  56128. (function (BABYLON) {
  56129. var Debug;
  56130. (function (Debug) {
  56131. var AxesViewer = (function () {
  56132. function AxesViewer(scene, scaleLines) {
  56133. if (scaleLines === void 0) { scaleLines = 1; }
  56134. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  56135. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  56136. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  56137. this.scaleLines = 1;
  56138. this.scaleLines = scaleLines;
  56139. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  56140. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  56141. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  56142. this._xmesh.renderingGroupId = 2;
  56143. this._ymesh.renderingGroupId = 2;
  56144. this._zmesh.renderingGroupId = 2;
  56145. this._xmesh.material.checkReadyOnlyOnce = true;
  56146. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  56147. this._ymesh.material.checkReadyOnlyOnce = true;
  56148. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  56149. this._zmesh.material.checkReadyOnlyOnce = true;
  56150. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  56151. this.scene = scene;
  56152. }
  56153. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  56154. var scaleLines = this.scaleLines;
  56155. var point1 = this._xline[0];
  56156. var point2 = this._xline[1];
  56157. point1.x = position.x;
  56158. point1.y = position.y;
  56159. point1.z = position.z;
  56160. point2.x = point1.x + xaxis.x * scaleLines;
  56161. point2.y = point1.y + xaxis.y * scaleLines;
  56162. point2.z = point1.z + xaxis.z * scaleLines;
  56163. BABYLON.Mesh.CreateLines(null, this._xline, null, null, this._xmesh);
  56164. point1 = this._yline[0];
  56165. point2 = this._yline[1];
  56166. point1.x = position.x;
  56167. point1.y = position.y;
  56168. point1.z = position.z;
  56169. point2.x = point1.x + yaxis.x * scaleLines;
  56170. point2.y = point1.y + yaxis.y * scaleLines;
  56171. point2.z = point1.z + yaxis.z * scaleLines;
  56172. BABYLON.Mesh.CreateLines(null, this._yline, null, null, this._ymesh);
  56173. point1 = this._zline[0];
  56174. point2 = this._zline[1];
  56175. point1.x = position.x;
  56176. point1.y = position.y;
  56177. point1.z = position.z;
  56178. point2.x = point1.x + zaxis.x * scaleLines;
  56179. point2.y = point1.y + zaxis.y * scaleLines;
  56180. point2.z = point1.z + zaxis.z * scaleLines;
  56181. BABYLON.Mesh.CreateLines(null, this._zline, null, null, this._zmesh);
  56182. };
  56183. AxesViewer.prototype.dispose = function () {
  56184. if (this._xmesh) {
  56185. this._xmesh.dispose();
  56186. this._ymesh.dispose();
  56187. this._zmesh.dispose();
  56188. this._xmesh = null;
  56189. this._ymesh = null;
  56190. this._zmesh = null;
  56191. this._xline = null;
  56192. this._yline = null;
  56193. this._zline = null;
  56194. this.scene = null;
  56195. }
  56196. };
  56197. return AxesViewer;
  56198. }());
  56199. Debug.AxesViewer = AxesViewer;
  56200. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  56201. })(BABYLON || (BABYLON = {}));
  56202. //# sourceMappingURL=babylon.axesViewer.js.map
  56203. var BABYLON;
  56204. (function (BABYLON) {
  56205. var Debug;
  56206. (function (Debug) {
  56207. var BoneAxesViewer = (function (_super) {
  56208. __extends(BoneAxesViewer, _super);
  56209. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  56210. if (scaleLines === void 0) { scaleLines = 1; }
  56211. var _this = _super.call(this, scene, scaleLines) || this;
  56212. _this.pos = BABYLON.Vector3.Zero();
  56213. _this.xaxis = BABYLON.Vector3.Zero();
  56214. _this.yaxis = BABYLON.Vector3.Zero();
  56215. _this.zaxis = BABYLON.Vector3.Zero();
  56216. _this.mesh = mesh;
  56217. _this.bone = bone;
  56218. return _this;
  56219. }
  56220. BoneAxesViewer.prototype.update = function () {
  56221. var bone = this.bone;
  56222. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  56223. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  56224. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  56225. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  56226. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  56227. };
  56228. BoneAxesViewer.prototype.dispose = function () {
  56229. if (this.pos) {
  56230. this.pos = null;
  56231. this.xaxis = null;
  56232. this.yaxis = null;
  56233. this.zaxis = null;
  56234. this.mesh = null;
  56235. this.bone = null;
  56236. _super.prototype.dispose.call(this);
  56237. }
  56238. };
  56239. return BoneAxesViewer;
  56240. }(Debug.AxesViewer));
  56241. Debug.BoneAxesViewer = BoneAxesViewer;
  56242. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  56243. })(BABYLON || (BABYLON = {}));
  56244. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  56245. var BABYLON;
  56246. (function (BABYLON) {
  56247. var RayHelper = (function () {
  56248. function RayHelper(ray) {
  56249. this.ray = ray;
  56250. }
  56251. RayHelper.CreateAndShow = function (ray, scene, color) {
  56252. var helper = new RayHelper(ray);
  56253. helper.show(scene, color);
  56254. return helper;
  56255. };
  56256. RayHelper.prototype.show = function (scene, color) {
  56257. if (!this._renderFunction) {
  56258. var ray = this.ray;
  56259. this._renderFunction = this._render.bind(this);
  56260. this._scene = scene;
  56261. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  56262. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  56263. this._scene.registerBeforeRender(this._renderFunction);
  56264. }
  56265. if (color) {
  56266. this._renderLine.color.copyFrom(color);
  56267. }
  56268. };
  56269. RayHelper.prototype.hide = function () {
  56270. if (this._renderFunction) {
  56271. this._scene.unregisterBeforeRender(this._renderFunction);
  56272. this._scene = null;
  56273. this._renderFunction = null;
  56274. this._renderLine.dispose();
  56275. this._renderLine = null;
  56276. this._renderPoints = null;
  56277. }
  56278. };
  56279. RayHelper.prototype._render = function () {
  56280. var ray = this.ray;
  56281. var point = this._renderPoints[1];
  56282. var len = Math.min(ray.length, 1000000);
  56283. point.copyFrom(ray.direction);
  56284. point.scaleInPlace(len);
  56285. point.addInPlace(ray.origin);
  56286. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  56287. };
  56288. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  56289. this._attachedToMesh = mesh;
  56290. var ray = this.ray;
  56291. if (!ray.direction) {
  56292. ray.direction = BABYLON.Vector3.Zero();
  56293. }
  56294. if (!ray.origin) {
  56295. ray.origin = BABYLON.Vector3.Zero();
  56296. }
  56297. if (length) {
  56298. ray.length = length;
  56299. }
  56300. if (!meshSpaceOrigin) {
  56301. meshSpaceOrigin = BABYLON.Vector3.Zero();
  56302. }
  56303. if (!meshSpaceDirection) {
  56304. // -1 so that this will work with Mesh.lookAt
  56305. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  56306. }
  56307. if (!this._meshSpaceDirection) {
  56308. this._meshSpaceDirection = meshSpaceDirection.clone();
  56309. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  56310. }
  56311. else {
  56312. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  56313. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  56314. }
  56315. if (!this._updateToMeshFunction) {
  56316. this._updateToMeshFunction = this._updateToMesh.bind(this);
  56317. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  56318. }
  56319. this._updateToMesh();
  56320. };
  56321. RayHelper.prototype.detachFromMesh = function () {
  56322. if (this._attachedToMesh) {
  56323. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  56324. this._attachedToMesh = null;
  56325. this._updateToMeshFunction = null;
  56326. }
  56327. };
  56328. RayHelper.prototype._updateToMesh = function () {
  56329. var ray = this.ray;
  56330. if (this._attachedToMesh._isDisposed) {
  56331. this.detachFromMesh();
  56332. return;
  56333. }
  56334. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  56335. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  56336. };
  56337. RayHelper.prototype.dispose = function () {
  56338. this.hide();
  56339. this.detachFromMesh();
  56340. this.ray = null;
  56341. };
  56342. return RayHelper;
  56343. }());
  56344. BABYLON.RayHelper = RayHelper;
  56345. })(BABYLON || (BABYLON = {}));
  56346. //# sourceMappingURL=babylon.rayHelper.js.map
  56347. var BABYLON;
  56348. (function (BABYLON) {
  56349. var DebugLayer = (function () {
  56350. function DebugLayer(scene) {
  56351. this._scene = scene;
  56352. }
  56353. /** Creates the inspector window. */
  56354. DebugLayer.prototype._createInspector = function (config) {
  56355. if (config === void 0) { config = {}; }
  56356. var popup = config.popup || false;
  56357. var initialTab = config.initialTab || 0;
  56358. var parentElement = config.parentElement || null;
  56359. if (!this._inspector) {
  56360. this._inspector = new INSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  56361. } // else nothing to do,; instance is already existing
  56362. };
  56363. DebugLayer.prototype.isVisible = function () {
  56364. if (!this._inspector) {
  56365. return false;
  56366. }
  56367. return true;
  56368. };
  56369. DebugLayer.prototype.hide = function () {
  56370. if (this._inspector) {
  56371. try {
  56372. this._inspector.dispose();
  56373. }
  56374. catch (e) {
  56375. // If the inspector has been removed directly from the inspector tool
  56376. }
  56377. this._inspector = null;
  56378. }
  56379. };
  56380. DebugLayer.prototype.show = function (config) {
  56381. if (config === void 0) { config = {}; }
  56382. if (typeof INSPECTOR == 'undefined') {
  56383. // Load inspector and add it to the DOM
  56384. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  56385. }
  56386. else {
  56387. // Otherwise creates the inspector
  56388. this._createInspector(config);
  56389. }
  56390. };
  56391. return DebugLayer;
  56392. }());
  56393. // Get protocol used - http or https
  56394. DebugLayer.InspectorURL = window.location.href.split('/')[0] + '//www.babylonjs.com/babylon.inspector.bundle.js';
  56395. BABYLON.DebugLayer = DebugLayer;
  56396. })(BABYLON || (BABYLON = {}));
  56397. //# sourceMappingURL=babylon.debugLayer.js.map
  56398. var BABYLON;
  56399. (function (BABYLON) {
  56400. var BoundingBoxRenderer = (function () {
  56401. function BoundingBoxRenderer(scene) {
  56402. this.frontColor = new BABYLON.Color3(1, 1, 1);
  56403. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  56404. this.showBackLines = true;
  56405. this.renderList = new BABYLON.SmartArray(32);
  56406. this._vertexBuffers = {};
  56407. this._scene = scene;
  56408. }
  56409. BoundingBoxRenderer.prototype._prepareRessources = function () {
  56410. if (this._colorShader) {
  56411. return;
  56412. }
  56413. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  56414. attributes: [BABYLON.VertexBuffer.PositionKind],
  56415. uniforms: ["worldViewProjection", "color"]
  56416. });
  56417. var engine = this._scene.getEngine();
  56418. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  56419. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  56420. 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]);
  56421. };
  56422. BoundingBoxRenderer.prototype.reset = function () {
  56423. this.renderList.reset();
  56424. };
  56425. BoundingBoxRenderer.prototype.render = function () {
  56426. if (this.renderList.length === 0) {
  56427. return;
  56428. }
  56429. this._prepareRessources();
  56430. if (!this._colorShader.isReady()) {
  56431. return;
  56432. }
  56433. var engine = this._scene.getEngine();
  56434. engine.setDepthWrite(false);
  56435. this._colorShader._preBind();
  56436. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  56437. var boundingBox = this.renderList.data[boundingBoxIndex];
  56438. var min = boundingBox.minimum;
  56439. var max = boundingBox.maximum;
  56440. var diff = max.subtract(min);
  56441. var median = min.add(diff.scale(0.5));
  56442. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  56443. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  56444. .multiply(boundingBox.getWorldMatrix());
  56445. // VBOs
  56446. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  56447. if (this.showBackLines) {
  56448. // Back
  56449. engine.setDepthFunctionToGreaterOrEqual();
  56450. this._scene.resetCachedMaterial();
  56451. this._colorShader.setColor4("color", this.backColor.toColor4());
  56452. this._colorShader.bind(worldMatrix);
  56453. // Draw order
  56454. engine.draw(false, 0, 24);
  56455. }
  56456. // Front
  56457. engine.setDepthFunctionToLess();
  56458. this._scene.resetCachedMaterial();
  56459. this._colorShader.setColor4("color", this.frontColor.toColor4());
  56460. this._colorShader.bind(worldMatrix);
  56461. // Draw order
  56462. engine.draw(false, 0, 24);
  56463. }
  56464. this._colorShader.unbind();
  56465. engine.setDepthFunctionToLessOrEqual();
  56466. engine.setDepthWrite(true);
  56467. };
  56468. BoundingBoxRenderer.prototype.dispose = function () {
  56469. if (!this._colorShader) {
  56470. return;
  56471. }
  56472. this.renderList.dispose();
  56473. this._colorShader.dispose();
  56474. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  56475. if (buffer) {
  56476. buffer.dispose();
  56477. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  56478. }
  56479. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  56480. };
  56481. return BoundingBoxRenderer;
  56482. }());
  56483. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  56484. })(BABYLON || (BABYLON = {}));
  56485. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  56486. var BABYLON;
  56487. (function (BABYLON) {
  56488. var MorphTarget = (function () {
  56489. function MorphTarget(name, influence) {
  56490. if (influence === void 0) { influence = 0; }
  56491. this.name = name;
  56492. this.onInfluenceChanged = new BABYLON.Observable();
  56493. this.influence = influence;
  56494. }
  56495. Object.defineProperty(MorphTarget.prototype, "influence", {
  56496. get: function () {
  56497. return this._influence;
  56498. },
  56499. set: function (influence) {
  56500. if (this._influence === influence) {
  56501. return;
  56502. }
  56503. var previous = this._influence;
  56504. this._influence = influence;
  56505. if (this.onInfluenceChanged.hasObservers) {
  56506. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  56507. }
  56508. },
  56509. enumerable: true,
  56510. configurable: true
  56511. });
  56512. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  56513. get: function () {
  56514. return this._normals !== undefined;
  56515. },
  56516. enumerable: true,
  56517. configurable: true
  56518. });
  56519. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  56520. get: function () {
  56521. return this._tangents !== undefined;
  56522. },
  56523. enumerable: true,
  56524. configurable: true
  56525. });
  56526. MorphTarget.prototype.setPositions = function (data) {
  56527. this._positions = new Float32Array(data);
  56528. };
  56529. MorphTarget.prototype.getPositions = function () {
  56530. return this._positions;
  56531. };
  56532. MorphTarget.prototype.setNormals = function (data) {
  56533. this._normals = new Float32Array(data);
  56534. };
  56535. MorphTarget.prototype.getNormals = function () {
  56536. return this._normals;
  56537. };
  56538. MorphTarget.prototype.setTangents = function (data) {
  56539. this._tangents = new Float32Array(data);
  56540. };
  56541. MorphTarget.prototype.getTangents = function () {
  56542. return this._tangents;
  56543. };
  56544. /**
  56545. * Serializes the current target into a Serialization object.
  56546. * Returns the serialized object.
  56547. */
  56548. MorphTarget.prototype.serialize = function () {
  56549. var serializationObject = {};
  56550. serializationObject.name = this.name;
  56551. serializationObject.influence = this.influence;
  56552. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  56553. if (this.hasNormals) {
  56554. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  56555. }
  56556. if (this.hasTangents) {
  56557. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  56558. }
  56559. return serializationObject;
  56560. };
  56561. // Statics
  56562. MorphTarget.Parse = function (serializationObject) {
  56563. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  56564. result.setPositions(serializationObject.positions);
  56565. if (serializationObject.normals) {
  56566. result.setNormals(serializationObject.normals);
  56567. }
  56568. if (serializationObject.tangents) {
  56569. result.setTangents(serializationObject.tangents);
  56570. }
  56571. return result;
  56572. };
  56573. MorphTarget.FromMesh = function (mesh, name, influence) {
  56574. if (!name) {
  56575. name = mesh.name;
  56576. }
  56577. var result = new MorphTarget(name, influence);
  56578. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  56579. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  56580. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  56581. }
  56582. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  56583. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  56584. }
  56585. return result;
  56586. };
  56587. return MorphTarget;
  56588. }());
  56589. BABYLON.MorphTarget = MorphTarget;
  56590. })(BABYLON || (BABYLON = {}));
  56591. //# sourceMappingURL=babylon.morphTarget.js.map
  56592. var BABYLON;
  56593. (function (BABYLON) {
  56594. var MorphTargetManager = (function () {
  56595. function MorphTargetManager(scene) {
  56596. this._targets = new Array();
  56597. this._targetObservable = new Array();
  56598. this._activeTargets = new BABYLON.SmartArray(16);
  56599. this._supportsNormals = false;
  56600. this._supportsTangents = false;
  56601. this._vertexCount = 0;
  56602. this._uniqueId = 0;
  56603. if (!scene) {
  56604. scene = BABYLON.Engine.LastCreatedScene;
  56605. }
  56606. this._scene = scene;
  56607. this._scene.morphTargetManagers.push(this);
  56608. this._uniqueId = scene.getUniqueId();
  56609. }
  56610. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  56611. get: function () {
  56612. return this._uniqueId;
  56613. },
  56614. enumerable: true,
  56615. configurable: true
  56616. });
  56617. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  56618. get: function () {
  56619. return this._vertexCount;
  56620. },
  56621. enumerable: true,
  56622. configurable: true
  56623. });
  56624. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  56625. get: function () {
  56626. return this._supportsNormals;
  56627. },
  56628. enumerable: true,
  56629. configurable: true
  56630. });
  56631. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  56632. get: function () {
  56633. return this._supportsTangents;
  56634. },
  56635. enumerable: true,
  56636. configurable: true
  56637. });
  56638. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  56639. get: function () {
  56640. return this._activeTargets.length;
  56641. },
  56642. enumerable: true,
  56643. configurable: true
  56644. });
  56645. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  56646. get: function () {
  56647. return this._influences;
  56648. },
  56649. enumerable: true,
  56650. configurable: true
  56651. });
  56652. MorphTargetManager.prototype.getActiveTarget = function (index) {
  56653. return this._activeTargets.data[index];
  56654. };
  56655. MorphTargetManager.prototype.addTarget = function (target) {
  56656. var _this = this;
  56657. if (this._vertexCount) {
  56658. if (this._vertexCount !== target.getPositions().length / 3) {
  56659. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  56660. return;
  56661. }
  56662. }
  56663. this._targets.push(target);
  56664. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  56665. _this._syncActiveTargets(needUpdate);
  56666. }));
  56667. this._syncActiveTargets(true);
  56668. };
  56669. MorphTargetManager.prototype.removeTarget = function (target) {
  56670. var index = this._targets.indexOf(target);
  56671. if (index >= 0) {
  56672. this._targets.splice(index, 1);
  56673. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  56674. this._vertexCount = 0;
  56675. this._syncActiveTargets(true);
  56676. }
  56677. };
  56678. /**
  56679. * Serializes the current manager into a Serialization object.
  56680. * Returns the serialized object.
  56681. */
  56682. MorphTargetManager.prototype.serialize = function () {
  56683. var serializationObject = {};
  56684. serializationObject.id = this.uniqueId;
  56685. serializationObject.targets = [];
  56686. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  56687. var target = _a[_i];
  56688. serializationObject.targets.push(target.serialize());
  56689. }
  56690. return serializationObject;
  56691. };
  56692. MorphTargetManager.prototype._onInfluenceChanged = function (needUpdate) {
  56693. this._syncActiveTargets(needUpdate);
  56694. };
  56695. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  56696. this._activeTargets.reset();
  56697. var tempInfluences = [];
  56698. this._supportsNormals = true;
  56699. this._supportsTangents = true;
  56700. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  56701. var target = _a[_i];
  56702. if (target.influence > 0) {
  56703. this._activeTargets.push(target);
  56704. tempInfluences.push(target.influence);
  56705. this._supportsNormals = this._supportsNormals && target.hasNormals;
  56706. this._supportsTangents = this._supportsTangents && target.hasTangents;
  56707. if (this._vertexCount === 0) {
  56708. this._vertexCount = target.getPositions().length / 3;
  56709. }
  56710. }
  56711. }
  56712. this._influences = new Float32Array(tempInfluences);
  56713. if (needUpdate) {
  56714. // Flag meshes as dirty to resync with the active targets
  56715. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  56716. var mesh = _c[_b];
  56717. if (mesh.morphTargetManager === this) {
  56718. mesh._syncGeometryWithMorphTargetManager();
  56719. }
  56720. }
  56721. }
  56722. };
  56723. // Statics
  56724. MorphTargetManager.Parse = function (serializationObject, scene) {
  56725. var result = new MorphTargetManager(scene);
  56726. result._uniqueId = serializationObject.id;
  56727. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  56728. var targetData = _a[_i];
  56729. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  56730. }
  56731. return result;
  56732. };
  56733. return MorphTargetManager;
  56734. }());
  56735. BABYLON.MorphTargetManager = MorphTargetManager;
  56736. })(BABYLON || (BABYLON = {}));
  56737. //# sourceMappingURL=babylon.morphTargetManager.js.map
  56738. var BABYLON;
  56739. (function (BABYLON) {
  56740. /**
  56741. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  56742. * It can help converting any input color in a desired output one. This can then be used to create effects
  56743. * from sepia, black and white to sixties or futuristic rendering...
  56744. *
  56745. * The only supported format is currently 3dl.
  56746. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  56747. */
  56748. var ColorGradingTexture = (function (_super) {
  56749. __extends(ColorGradingTexture, _super);
  56750. /**
  56751. * Instantiates a ColorGradingTexture from the following parameters.
  56752. *
  56753. * @param url The location of the color gradind data (currently only supporting 3dl)
  56754. * @param scene The scene the texture will be used in
  56755. */
  56756. function ColorGradingTexture(url, scene) {
  56757. var _this = _super.call(this, scene) || this;
  56758. if (!url) {
  56759. return _this;
  56760. }
  56761. _this._textureMatrix = BABYLON.Matrix.Identity();
  56762. _this.name = url;
  56763. _this.url = url;
  56764. _this.hasAlpha = false;
  56765. _this.isCube = false;
  56766. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56767. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56768. _this.anisotropicFilteringLevel = 1;
  56769. _this._texture = _this._getFromCache(url, true);
  56770. if (!_this._texture) {
  56771. if (!scene.useDelayedTextureLoading) {
  56772. _this.loadTexture();
  56773. }
  56774. else {
  56775. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  56776. }
  56777. }
  56778. return _this;
  56779. }
  56780. /**
  56781. * Returns the texture matrix used in most of the material.
  56782. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  56783. */
  56784. ColorGradingTexture.prototype.getTextureMatrix = function () {
  56785. return this._textureMatrix;
  56786. };
  56787. /**
  56788. * Occurs when the file being loaded is a .3dl LUT file.
  56789. */
  56790. ColorGradingTexture.prototype.load3dlTexture = function () {
  56791. var _this = this;
  56792. var mipLevels = 0;
  56793. var floatArrayView = null;
  56794. var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  56795. this._texture = texture;
  56796. var callback = function (text) {
  56797. var data;
  56798. var tempData;
  56799. var line;
  56800. var lines = text.split('\n');
  56801. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  56802. var maxColor = 0;
  56803. for (var i = 0; i < lines.length; i++) {
  56804. line = lines[i];
  56805. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  56806. continue;
  56807. if (line.indexOf('#') === 0)
  56808. continue;
  56809. var words = line.split(" ");
  56810. if (size === 0) {
  56811. // Number of space + one
  56812. size = words.length;
  56813. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  56814. tempData = new Float32Array(size * size * size * 4);
  56815. continue;
  56816. }
  56817. if (size != 0) {
  56818. var r = Math.max(parseInt(words[0]), 0);
  56819. var g = Math.max(parseInt(words[1]), 0);
  56820. var b = Math.max(parseInt(words[2]), 0);
  56821. maxColor = Math.max(r, maxColor);
  56822. maxColor = Math.max(g, maxColor);
  56823. maxColor = Math.max(b, maxColor);
  56824. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  56825. tempData[pixelStorageIndex + 0] = r;
  56826. tempData[pixelStorageIndex + 1] = g;
  56827. tempData[pixelStorageIndex + 2] = b;
  56828. tempData[pixelStorageIndex + 3] = 0;
  56829. pixelIndexSlice++;
  56830. if (pixelIndexSlice % size == 0) {
  56831. pixelIndexH++;
  56832. pixelIndexSlice = 0;
  56833. if (pixelIndexH % size == 0) {
  56834. pixelIndexW++;
  56835. pixelIndexH = 0;
  56836. }
  56837. }
  56838. }
  56839. }
  56840. for (var i = 0; i < tempData.length; i++) {
  56841. var value = tempData[i];
  56842. data[i] = (value / maxColor * 255);
  56843. }
  56844. _this.getScene().getEngine().updateTextureSize(texture, size * size, size);
  56845. _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  56846. };
  56847. BABYLON.Tools.LoadFile(this.url, callback);
  56848. return this._texture;
  56849. };
  56850. /**
  56851. * Starts the loading process of the texture.
  56852. */
  56853. ColorGradingTexture.prototype.loadTexture = function () {
  56854. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  56855. this.load3dlTexture();
  56856. }
  56857. };
  56858. /**
  56859. * Clones the color gradind texture.
  56860. */
  56861. ColorGradingTexture.prototype.clone = function () {
  56862. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  56863. // Base texture
  56864. newTexture.level = this.level;
  56865. return newTexture;
  56866. };
  56867. /**
  56868. * Called during delayed load for textures.
  56869. */
  56870. ColorGradingTexture.prototype.delayLoad = function () {
  56871. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  56872. return;
  56873. }
  56874. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  56875. this._texture = this._getFromCache(this.url, true);
  56876. if (!this._texture) {
  56877. this.loadTexture();
  56878. }
  56879. };
  56880. /**
  56881. * Binds the color grading to the shader.
  56882. * @param colorGrading The texture to bind
  56883. * @param effect The effect to bind to
  56884. */
  56885. ColorGradingTexture.Bind = function (colorGrading, effect) {
  56886. effect.setTexture("cameraColorGrading2DSampler", colorGrading);
  56887. var x = colorGrading.level; // Texture Level
  56888. var y = colorGrading.getSize().height; // Texture Size example with 8
  56889. var z = y - 1.0; // SizeMinusOne 8 - 1
  56890. var w = 1 / y; // Space of 1 slice 1 / 8
  56891. effect.setFloat4("vCameraColorGradingInfos", x, y, z, w);
  56892. var slicePixelSizeU = w / y; // Space of 1 pixel in U direction, e.g. 1/64
  56893. 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
  56894. 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
  56895. 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
  56896. var z2 = 0.5 * slicePixelSizeU; // Offset of lookup range in U to align sample position with texel centre, for example 0.5/64
  56897. var w2 = 0.5 * slicePixelSizeV; // Offset of lookup range in V to align sample position with texel centre, for example 0.5/8
  56898. effect.setFloat4("vCameraColorGradingScaleOffset", x2, y2, z2, w2);
  56899. };
  56900. /**
  56901. * Prepare the list of uniforms associated with the ColorGrading effects.
  56902. * @param uniformsList The list of uniforms used in the effect
  56903. * @param samplersList The list of samplers used in the effect
  56904. */
  56905. ColorGradingTexture.PrepareUniformsAndSamplers = function (uniformsList, samplersList) {
  56906. uniformsList.push("vCameraColorGradingInfos", "vCameraColorGradingScaleOffset");
  56907. samplersList.push("cameraColorGrading2DSampler");
  56908. };
  56909. /**
  56910. * Parses a color grading texture serialized by Babylon.
  56911. * @param parsedTexture The texture information being parsedTexture
  56912. * @param scene The scene to load the texture in
  56913. * @param rootUrl The root url of the data assets to load
  56914. * @return A color gradind texture
  56915. */
  56916. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  56917. var texture = null;
  56918. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  56919. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  56920. texture.name = parsedTexture.name;
  56921. texture.level = parsedTexture.level;
  56922. }
  56923. return texture;
  56924. };
  56925. /**
  56926. * Serializes the LUT texture to json format.
  56927. */
  56928. ColorGradingTexture.prototype.serialize = function () {
  56929. if (!this.name) {
  56930. return null;
  56931. }
  56932. var serializationObject = {};
  56933. serializationObject.name = this.name;
  56934. serializationObject.level = this.level;
  56935. serializationObject.customType = "BABYLON.ColorGradingTexture";
  56936. return serializationObject;
  56937. };
  56938. return ColorGradingTexture;
  56939. }(BABYLON.BaseTexture));
  56940. /**
  56941. * Empty line regex stored for GC.
  56942. */
  56943. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  56944. BABYLON.ColorGradingTexture = ColorGradingTexture;
  56945. })(BABYLON || (BABYLON = {}));
  56946. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  56947. var BABYLON;
  56948. (function (BABYLON) {
  56949. /**
  56950. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  56951. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  56952. * 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;
  56953. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  56954. */
  56955. var ColorCurves = (function () {
  56956. function ColorCurves() {
  56957. this._dirty = true;
  56958. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  56959. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  56960. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  56961. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  56962. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  56963. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  56964. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  56965. this._globalHue = 30;
  56966. this._globalDensity = 0;
  56967. this._globalSaturation = 0;
  56968. this._globalExposure = 0;
  56969. this._highlightsHue = 30;
  56970. this._highlightsDensity = 0;
  56971. this._highlightsSaturation = 0;
  56972. this._highlightsExposure = 0;
  56973. this._midtonesHue = 30;
  56974. this._midtonesDensity = 0;
  56975. this._midtonesSaturation = 0;
  56976. this._midtonesExposure = 0;
  56977. this._shadowsHue = 30;
  56978. this._shadowsDensity = 0;
  56979. this._shadowsSaturation = 0;
  56980. this._shadowsExposure = 0;
  56981. }
  56982. Object.defineProperty(ColorCurves.prototype, "GlobalHue", {
  56983. /**
  56984. * Gets the global Hue value.
  56985. * 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).
  56986. */
  56987. get: function () {
  56988. return this._globalHue;
  56989. },
  56990. /**
  56991. * Sets the global Hue value.
  56992. * 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).
  56993. */
  56994. set: function (value) {
  56995. this._globalHue = value;
  56996. this._dirty = true;
  56997. },
  56998. enumerable: true,
  56999. configurable: true
  57000. });
  57001. Object.defineProperty(ColorCurves.prototype, "GlobalDensity", {
  57002. /**
  57003. * Gets the global Density value.
  57004. * 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.
  57005. * Values less than zero provide a filter of opposite hue.
  57006. */
  57007. get: function () {
  57008. return this._globalDensity;
  57009. },
  57010. /**
  57011. * Sets the global Density value.
  57012. * 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.
  57013. * Values less than zero provide a filter of opposite hue.
  57014. */
  57015. set: function (value) {
  57016. this._globalDensity = value;
  57017. this._dirty = true;
  57018. },
  57019. enumerable: true,
  57020. configurable: true
  57021. });
  57022. Object.defineProperty(ColorCurves.prototype, "GlobalSaturation", {
  57023. /**
  57024. * Gets the global Saturation value.
  57025. * 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.
  57026. */
  57027. get: function () {
  57028. return this._globalSaturation;
  57029. },
  57030. /**
  57031. * Sets the global Saturation value.
  57032. * 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.
  57033. */
  57034. set: function (value) {
  57035. this._globalSaturation = value;
  57036. this._dirty = true;
  57037. },
  57038. enumerable: true,
  57039. configurable: true
  57040. });
  57041. Object.defineProperty(ColorCurves.prototype, "HighlightsHue", {
  57042. /**
  57043. * Gets the highlights Hue value.
  57044. * 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).
  57045. */
  57046. get: function () {
  57047. return this._highlightsHue;
  57048. },
  57049. /**
  57050. * Sets the highlights Hue value.
  57051. * 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).
  57052. */
  57053. set: function (value) {
  57054. this._highlightsHue = value;
  57055. this._dirty = true;
  57056. },
  57057. enumerable: true,
  57058. configurable: true
  57059. });
  57060. Object.defineProperty(ColorCurves.prototype, "HighlightsDensity", {
  57061. /**
  57062. * Gets the highlights Density value.
  57063. * 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.
  57064. * Values less than zero provide a filter of opposite hue.
  57065. */
  57066. get: function () {
  57067. return this._highlightsDensity;
  57068. },
  57069. /**
  57070. * Sets the highlights Density value.
  57071. * 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.
  57072. * Values less than zero provide a filter of opposite hue.
  57073. */
  57074. set: function (value) {
  57075. this._highlightsDensity = value;
  57076. this._dirty = true;
  57077. },
  57078. enumerable: true,
  57079. configurable: true
  57080. });
  57081. Object.defineProperty(ColorCurves.prototype, "HighlightsSaturation", {
  57082. /**
  57083. * Gets the highlights Saturation value.
  57084. * 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.
  57085. */
  57086. get: function () {
  57087. return this._highlightsSaturation;
  57088. },
  57089. /**
  57090. * Sets the highlights Saturation value.
  57091. * 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.
  57092. */
  57093. set: function (value) {
  57094. this._highlightsSaturation = value;
  57095. this._dirty = true;
  57096. },
  57097. enumerable: true,
  57098. configurable: true
  57099. });
  57100. Object.defineProperty(ColorCurves.prototype, "HighlightsExposure", {
  57101. /**
  57102. * Gets the highlights Exposure value.
  57103. * 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.
  57104. */
  57105. get: function () {
  57106. return this._highlightsExposure;
  57107. },
  57108. /**
  57109. * Sets the highlights Exposure value.
  57110. * 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.
  57111. */
  57112. set: function (value) {
  57113. this._highlightsExposure = value;
  57114. this._dirty = true;
  57115. },
  57116. enumerable: true,
  57117. configurable: true
  57118. });
  57119. Object.defineProperty(ColorCurves.prototype, "MidtonesHue", {
  57120. /**
  57121. * Gets the midtones Hue value.
  57122. * 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).
  57123. */
  57124. get: function () {
  57125. return this._midtonesHue;
  57126. },
  57127. /**
  57128. * Sets the midtones Hue value.
  57129. * 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).
  57130. */
  57131. set: function (value) {
  57132. this._midtonesHue = value;
  57133. this._dirty = true;
  57134. },
  57135. enumerable: true,
  57136. configurable: true
  57137. });
  57138. Object.defineProperty(ColorCurves.prototype, "MidtonesDensity", {
  57139. /**
  57140. * Gets the midtones Density value.
  57141. * 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.
  57142. * Values less than zero provide a filter of opposite hue.
  57143. */
  57144. get: function () {
  57145. return this._midtonesDensity;
  57146. },
  57147. /**
  57148. * Sets the midtones Density value.
  57149. * 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.
  57150. * Values less than zero provide a filter of opposite hue.
  57151. */
  57152. set: function (value) {
  57153. this._midtonesDensity = value;
  57154. this._dirty = true;
  57155. },
  57156. enumerable: true,
  57157. configurable: true
  57158. });
  57159. Object.defineProperty(ColorCurves.prototype, "MidtonesSaturation", {
  57160. /**
  57161. * Gets the midtones Saturation value.
  57162. * 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.
  57163. */
  57164. get: function () {
  57165. return this._midtonesSaturation;
  57166. },
  57167. /**
  57168. * Sets the midtones Saturation value.
  57169. * 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.
  57170. */
  57171. set: function (value) {
  57172. this._midtonesSaturation = value;
  57173. this._dirty = true;
  57174. },
  57175. enumerable: true,
  57176. configurable: true
  57177. });
  57178. Object.defineProperty(ColorCurves.prototype, "MidtonesExposure", {
  57179. /**
  57180. * Gets the midtones Exposure value.
  57181. * 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.
  57182. */
  57183. get: function () {
  57184. return this._midtonesExposure;
  57185. },
  57186. /**
  57187. * Sets the midtones Exposure value.
  57188. * 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.
  57189. */
  57190. set: function (value) {
  57191. this._midtonesExposure = value;
  57192. this._dirty = true;
  57193. },
  57194. enumerable: true,
  57195. configurable: true
  57196. });
  57197. Object.defineProperty(ColorCurves.prototype, "ShadowsHue", {
  57198. /**
  57199. * Gets the shadows Hue value.
  57200. * 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).
  57201. */
  57202. get: function () {
  57203. return this._shadowsHue;
  57204. },
  57205. /**
  57206. * Sets the shadows Hue value.
  57207. * 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).
  57208. */
  57209. set: function (value) {
  57210. this._shadowsHue = value;
  57211. this._dirty = true;
  57212. },
  57213. enumerable: true,
  57214. configurable: true
  57215. });
  57216. Object.defineProperty(ColorCurves.prototype, "ShadowsDensity", {
  57217. /**
  57218. * Gets the shadows Density value.
  57219. * 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.
  57220. * Values less than zero provide a filter of opposite hue.
  57221. */
  57222. get: function () {
  57223. return this._shadowsDensity;
  57224. },
  57225. /**
  57226. * Sets the shadows Density value.
  57227. * 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.
  57228. * Values less than zero provide a filter of opposite hue.
  57229. */
  57230. set: function (value) {
  57231. this._shadowsDensity = value;
  57232. this._dirty = true;
  57233. },
  57234. enumerable: true,
  57235. configurable: true
  57236. });
  57237. Object.defineProperty(ColorCurves.prototype, "ShadowsSaturation", {
  57238. /**
  57239. * Gets the shadows Saturation value.
  57240. * 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.
  57241. */
  57242. get: function () {
  57243. return this._shadowsSaturation;
  57244. },
  57245. /**
  57246. * Sets the shadows Saturation value.
  57247. * 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.
  57248. */
  57249. set: function (value) {
  57250. this._shadowsSaturation = value;
  57251. this._dirty = true;
  57252. },
  57253. enumerable: true,
  57254. configurable: true
  57255. });
  57256. Object.defineProperty(ColorCurves.prototype, "ShadowsExposure", {
  57257. /**
  57258. * Gets the shadows Exposure value.
  57259. * 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.
  57260. */
  57261. get: function () {
  57262. return this._shadowsExposure;
  57263. },
  57264. /**
  57265. * Sets the shadows Exposure value.
  57266. * 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.
  57267. */
  57268. set: function (value) {
  57269. this._shadowsExposure = value;
  57270. this._dirty = true;
  57271. },
  57272. enumerable: true,
  57273. configurable: true
  57274. });
  57275. /**
  57276. * Binds the color curves to the shader.
  57277. * @param colorCurves The color curve to bind
  57278. * @param effect The effect to bind to
  57279. */
  57280. ColorCurves.Bind = function (colorCurves, effect) {
  57281. if (colorCurves._dirty) {
  57282. colorCurves._dirty = false;
  57283. // Fill in global info.
  57284. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  57285. // Compute highlights info.
  57286. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  57287. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  57288. // Compute midtones info.
  57289. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  57290. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  57291. // Compute shadows info.
  57292. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  57293. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  57294. // Compute deltas (neutral is midtones).
  57295. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  57296. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  57297. }
  57298. effect.setFloat4("vCameraColorCurvePositive", colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  57299. effect.setFloat4("vCameraColorCurveNeutral", colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  57300. effect.setFloat4("vCameraColorCurveNegative", colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  57301. };
  57302. /**
  57303. * Prepare the list of uniforms associated with the ColorCurves effects.
  57304. * @param uniformsList The list of uniforms used in the effect
  57305. */
  57306. ColorCurves.PrepareUniforms = function (uniformsList) {
  57307. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  57308. };
  57309. /**
  57310. * Returns color grading data based on a hue, density, saturation and exposure value.
  57311. * @param filterHue The hue of the color filter.
  57312. * @param filterDensity The density of the color filter.
  57313. * @param saturation The saturation.
  57314. * @param exposure The exposure.
  57315. * @param result The result data container.
  57316. */
  57317. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  57318. if (hue == null) {
  57319. return;
  57320. }
  57321. hue = ColorCurves.clamp(hue, 0, 360);
  57322. density = ColorCurves.clamp(density, -100, 100);
  57323. saturation = ColorCurves.clamp(saturation, -100, 100);
  57324. exposure = ColorCurves.clamp(exposure, -100, 100);
  57325. // Remap the slider/config filter density with non-linear mapping and also scale by half
  57326. // so that the maximum filter density is only 50% control. This provides fine control
  57327. // for small values and reasonable range.
  57328. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  57329. density *= 0.5;
  57330. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  57331. if (density < 0) {
  57332. density *= -1;
  57333. hue = (hue + 180) % 360;
  57334. }
  57335. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  57336. result.scaleToRef(2, result);
  57337. result.a = 1 + 0.01 * saturation;
  57338. };
  57339. /**
  57340. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  57341. * @param value The input slider value in range [-100,100].
  57342. * @returns Adjusted value.
  57343. */
  57344. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  57345. value /= 100;
  57346. var x = Math.abs(value);
  57347. x = Math.pow(x, 2);
  57348. if (value < 0) {
  57349. x *= -1;
  57350. }
  57351. x *= 100;
  57352. return x;
  57353. };
  57354. /**
  57355. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  57356. * @param hue The hue (H) input.
  57357. * @param saturation The saturation (S) input.
  57358. * @param brightness The brightness (B) input.
  57359. * @result An RGBA color represented as Vector4.
  57360. */
  57361. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  57362. var h = ColorCurves.clamp(hue, 0, 360);
  57363. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  57364. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  57365. if (s === 0) {
  57366. result.r = v;
  57367. result.g = v;
  57368. result.b = v;
  57369. }
  57370. else {
  57371. // sector 0 to 5
  57372. h /= 60;
  57373. var i = Math.floor(h);
  57374. // fractional part of h
  57375. var f = h - i;
  57376. var p = v * (1 - s);
  57377. var q = v * (1 - s * f);
  57378. var t = v * (1 - s * (1 - f));
  57379. switch (i) {
  57380. case 0:
  57381. result.r = v;
  57382. result.g = t;
  57383. result.b = p;
  57384. break;
  57385. case 1:
  57386. result.r = q;
  57387. result.g = v;
  57388. result.b = p;
  57389. break;
  57390. case 2:
  57391. result.r = p;
  57392. result.g = v;
  57393. result.b = t;
  57394. break;
  57395. case 3:
  57396. result.r = p;
  57397. result.g = q;
  57398. result.b = v;
  57399. break;
  57400. case 4:
  57401. result.r = t;
  57402. result.g = p;
  57403. result.b = v;
  57404. break;
  57405. default:
  57406. result.r = v;
  57407. result.g = p;
  57408. result.b = q;
  57409. break;
  57410. }
  57411. }
  57412. result.a = 1;
  57413. };
  57414. /**
  57415. * Returns a value clamped between min and max
  57416. * @param value The value to clamp
  57417. * @param min The minimum of value
  57418. * @param max The maximum of value
  57419. * @returns The clamped value.
  57420. */
  57421. ColorCurves.clamp = function (value, min, max) {
  57422. return Math.min(Math.max(value, min), max);
  57423. };
  57424. /**
  57425. * Clones the current color curve instance.
  57426. * @return The cloned curves
  57427. */
  57428. ColorCurves.prototype.clone = function () {
  57429. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  57430. };
  57431. /**
  57432. * Serializes the current color curve instance to a json representation.
  57433. * @return a JSON representation
  57434. */
  57435. ColorCurves.prototype.serialize = function () {
  57436. return BABYLON.SerializationHelper.Serialize(this);
  57437. };
  57438. /**
  57439. * Parses the color curve from a json representation.
  57440. * @param source the JSON source to parse
  57441. * @return The parsed curves
  57442. */
  57443. ColorCurves.Parse = function (source) {
  57444. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  57445. };
  57446. return ColorCurves;
  57447. }());
  57448. __decorate([
  57449. BABYLON.serialize()
  57450. ], ColorCurves.prototype, "_globalHue", void 0);
  57451. __decorate([
  57452. BABYLON.serialize()
  57453. ], ColorCurves.prototype, "_globalDensity", void 0);
  57454. __decorate([
  57455. BABYLON.serialize()
  57456. ], ColorCurves.prototype, "_globalSaturation", void 0);
  57457. __decorate([
  57458. BABYLON.serialize()
  57459. ], ColorCurves.prototype, "_globalExposure", void 0);
  57460. __decorate([
  57461. BABYLON.serialize()
  57462. ], ColorCurves.prototype, "_highlightsHue", void 0);
  57463. __decorate([
  57464. BABYLON.serialize()
  57465. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  57466. __decorate([
  57467. BABYLON.serialize()
  57468. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  57469. __decorate([
  57470. BABYLON.serialize()
  57471. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  57472. __decorate([
  57473. BABYLON.serialize()
  57474. ], ColorCurves.prototype, "_midtonesHue", void 0);
  57475. __decorate([
  57476. BABYLON.serialize()
  57477. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  57478. __decorate([
  57479. BABYLON.serialize()
  57480. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  57481. __decorate([
  57482. BABYLON.serialize()
  57483. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  57484. BABYLON.ColorCurves = ColorCurves;
  57485. })(BABYLON || (BABYLON = {}));
  57486. //# sourceMappingURL=babylon.colorCurves.js.map
  57487. var BABYLON;
  57488. (function (BABYLON) {
  57489. var Octree = (function () {
  57490. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  57491. if (maxDepth === void 0) { maxDepth = 2; }
  57492. this.maxDepth = maxDepth;
  57493. this.dynamicContent = new Array();
  57494. this._maxBlockCapacity = maxBlockCapacity || 64;
  57495. this._selectionContent = new BABYLON.SmartArray(1024);
  57496. this._creationFunc = creationFunc;
  57497. }
  57498. // Methods
  57499. Octree.prototype.update = function (worldMin, worldMax, entries) {
  57500. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  57501. };
  57502. Octree.prototype.addMesh = function (entry) {
  57503. for (var index = 0; index < this.blocks.length; index++) {
  57504. var block = this.blocks[index];
  57505. block.addEntry(entry);
  57506. }
  57507. };
  57508. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  57509. this._selectionContent.reset();
  57510. for (var index = 0; index < this.blocks.length; index++) {
  57511. var block = this.blocks[index];
  57512. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  57513. }
  57514. if (allowDuplicate) {
  57515. this._selectionContent.concat(this.dynamicContent);
  57516. }
  57517. else {
  57518. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  57519. }
  57520. return this._selectionContent;
  57521. };
  57522. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  57523. this._selectionContent.reset();
  57524. for (var index = 0; index < this.blocks.length; index++) {
  57525. var block = this.blocks[index];
  57526. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  57527. }
  57528. if (allowDuplicate) {
  57529. this._selectionContent.concat(this.dynamicContent);
  57530. }
  57531. else {
  57532. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  57533. }
  57534. return this._selectionContent;
  57535. };
  57536. Octree.prototype.intersectsRay = function (ray) {
  57537. this._selectionContent.reset();
  57538. for (var index = 0; index < this.blocks.length; index++) {
  57539. var block = this.blocks[index];
  57540. block.intersectsRay(ray, this._selectionContent);
  57541. }
  57542. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  57543. return this._selectionContent;
  57544. };
  57545. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  57546. target.blocks = new Array();
  57547. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  57548. // Segmenting space
  57549. for (var x = 0; x < 2; x++) {
  57550. for (var y = 0; y < 2; y++) {
  57551. for (var z = 0; z < 2; z++) {
  57552. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  57553. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  57554. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  57555. block.addEntries(entries);
  57556. target.blocks.push(block);
  57557. }
  57558. }
  57559. }
  57560. };
  57561. return Octree;
  57562. }());
  57563. Octree.CreationFuncForMeshes = function (entry, block) {
  57564. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  57565. block.entries.push(entry);
  57566. }
  57567. };
  57568. Octree.CreationFuncForSubMeshes = function (entry, block) {
  57569. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  57570. block.entries.push(entry);
  57571. }
  57572. };
  57573. BABYLON.Octree = Octree;
  57574. })(BABYLON || (BABYLON = {}));
  57575. //# sourceMappingURL=babylon.octree.js.map
  57576. var BABYLON;
  57577. (function (BABYLON) {
  57578. var OctreeBlock = (function () {
  57579. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  57580. this.entries = new Array();
  57581. this._boundingVectors = new Array();
  57582. this._capacity = capacity;
  57583. this._depth = depth;
  57584. this._maxDepth = maxDepth;
  57585. this._creationFunc = creationFunc;
  57586. this._minPoint = minPoint;
  57587. this._maxPoint = maxPoint;
  57588. this._boundingVectors.push(minPoint.clone());
  57589. this._boundingVectors.push(maxPoint.clone());
  57590. this._boundingVectors.push(minPoint.clone());
  57591. this._boundingVectors[2].x = maxPoint.x;
  57592. this._boundingVectors.push(minPoint.clone());
  57593. this._boundingVectors[3].y = maxPoint.y;
  57594. this._boundingVectors.push(minPoint.clone());
  57595. this._boundingVectors[4].z = maxPoint.z;
  57596. this._boundingVectors.push(maxPoint.clone());
  57597. this._boundingVectors[5].z = minPoint.z;
  57598. this._boundingVectors.push(maxPoint.clone());
  57599. this._boundingVectors[6].x = minPoint.x;
  57600. this._boundingVectors.push(maxPoint.clone());
  57601. this._boundingVectors[7].y = minPoint.y;
  57602. }
  57603. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  57604. // Property
  57605. get: function () {
  57606. return this._capacity;
  57607. },
  57608. enumerable: true,
  57609. configurable: true
  57610. });
  57611. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  57612. get: function () {
  57613. return this._minPoint;
  57614. },
  57615. enumerable: true,
  57616. configurable: true
  57617. });
  57618. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  57619. get: function () {
  57620. return this._maxPoint;
  57621. },
  57622. enumerable: true,
  57623. configurable: true
  57624. });
  57625. // Methods
  57626. OctreeBlock.prototype.addEntry = function (entry) {
  57627. if (this.blocks) {
  57628. for (var index = 0; index < this.blocks.length; index++) {
  57629. var block = this.blocks[index];
  57630. block.addEntry(entry);
  57631. }
  57632. return;
  57633. }
  57634. this._creationFunc(entry, this);
  57635. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  57636. this.createInnerBlocks();
  57637. }
  57638. };
  57639. OctreeBlock.prototype.addEntries = function (entries) {
  57640. for (var index = 0; index < entries.length; index++) {
  57641. var mesh = entries[index];
  57642. this.addEntry(mesh);
  57643. }
  57644. };
  57645. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  57646. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  57647. if (this.blocks) {
  57648. for (var index = 0; index < this.blocks.length; index++) {
  57649. var block = this.blocks[index];
  57650. block.select(frustumPlanes, selection, allowDuplicate);
  57651. }
  57652. return;
  57653. }
  57654. if (allowDuplicate) {
  57655. selection.concat(this.entries);
  57656. }
  57657. else {
  57658. selection.concatWithNoDuplicate(this.entries);
  57659. }
  57660. }
  57661. };
  57662. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  57663. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  57664. if (this.blocks) {
  57665. for (var index = 0; index < this.blocks.length; index++) {
  57666. var block = this.blocks[index];
  57667. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  57668. }
  57669. return;
  57670. }
  57671. if (allowDuplicate) {
  57672. selection.concat(this.entries);
  57673. }
  57674. else {
  57675. selection.concatWithNoDuplicate(this.entries);
  57676. }
  57677. }
  57678. };
  57679. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  57680. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  57681. if (this.blocks) {
  57682. for (var index = 0; index < this.blocks.length; index++) {
  57683. var block = this.blocks[index];
  57684. block.intersectsRay(ray, selection);
  57685. }
  57686. return;
  57687. }
  57688. selection.concatWithNoDuplicate(this.entries);
  57689. }
  57690. };
  57691. OctreeBlock.prototype.createInnerBlocks = function () {
  57692. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  57693. };
  57694. return OctreeBlock;
  57695. }());
  57696. BABYLON.OctreeBlock = OctreeBlock;
  57697. })(BABYLON || (BABYLON = {}));
  57698. //# sourceMappingURL=babylon.octreeBlock.js.map
  57699. var BABYLON;
  57700. (function (BABYLON) {
  57701. var SIMDVector3 = (function () {
  57702. function SIMDVector3() {
  57703. }
  57704. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  57705. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD(vector.x, vector.y, vector.z, transformation, result);
  57706. };
  57707. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  57708. var m = transformation.m;
  57709. var m0 = SIMD.Float32x4.load(m, 0);
  57710. var m1 = SIMD.Float32x4.load(m, 4);
  57711. var m2 = SIMD.Float32x4.load(m, 8);
  57712. var m3 = SIMD.Float32x4.load(m, 12);
  57713. 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));
  57714. r = SIMD.Float32x4.div(r, SIMD.Float32x4.swizzle(r, 3, 3, 3, 3));
  57715. result.x = SIMD.Float32x4.extractLane(r, 0);
  57716. result.y = SIMD.Float32x4.extractLane(r, 1);
  57717. result.z = SIMD.Float32x4.extractLane(r, 2);
  57718. };
  57719. return SIMDVector3;
  57720. }());
  57721. var SIMDMatrix = (function () {
  57722. function SIMDMatrix() {
  57723. }
  57724. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  57725. var tm = this.m;
  57726. var om = other.m;
  57727. var m0 = SIMD.Float32x4.load(om, 0);
  57728. var m1 = SIMD.Float32x4.load(om, 4);
  57729. var m2 = SIMD.Float32x4.load(om, 8);
  57730. var m3 = SIMD.Float32x4.load(om, 12);
  57731. for (var i = 0; i < 16; i += 4) {
  57732. 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)))));
  57733. }
  57734. return this;
  57735. };
  57736. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  57737. var src = this.m;
  57738. var dest = other.m;
  57739. // Load the 4 rows
  57740. var src0 = SIMD.Float32x4.load(src, 0);
  57741. var src1 = SIMD.Float32x4.load(src, 4);
  57742. var src2 = SIMD.Float32x4.load(src, 8);
  57743. var src3 = SIMD.Float32x4.load(src, 12);
  57744. // Transpose the source matrix. Sort of. Not a true transpose operation
  57745. var tmp1 = SIMD.Float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  57746. var row1 = SIMD.Float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  57747. var row0 = SIMD.Float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  57748. row1 = SIMD.Float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  57749. tmp1 = SIMD.Float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  57750. var row3 = SIMD.Float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  57751. var row2 = SIMD.Float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  57752. row3 = SIMD.Float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  57753. // This is a true transposition, but it will lead to an incorrect result
  57754. //tmp1 = shuffle(src0, src1, 0, 1, 4, 5);
  57755. //tmp2 = shuffle(src2, src3, 0, 1, 4, 5);
  57756. //row0 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  57757. //row1 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  57758. //tmp1 = shuffle(src0, src1, 2, 3, 6, 7);
  57759. //tmp2 = shuffle(src2, src3, 2, 3, 6, 7);
  57760. //row2 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  57761. //row3 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  57762. // ----
  57763. tmp1 = SIMD.Float32x4.mul(row2, row3);
  57764. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  57765. var minor0 = SIMD.Float32x4.mul(row1, tmp1);
  57766. var minor1 = SIMD.Float32x4.mul(row0, tmp1);
  57767. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  57768. minor0 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row1, tmp1), minor0);
  57769. minor1 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor1);
  57770. minor1 = SIMD.Float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  57771. // ----
  57772. tmp1 = SIMD.Float32x4.mul(row1, row2);
  57773. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  57774. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor0);
  57775. var minor3 = SIMD.Float32x4.mul(row0, tmp1);
  57776. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  57777. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row3, tmp1));
  57778. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor3);
  57779. minor3 = SIMD.Float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  57780. // ----
  57781. tmp1 = SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  57782. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  57783. row2 = SIMD.Float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  57784. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor0);
  57785. var minor2 = SIMD.Float32x4.mul(row0, tmp1);
  57786. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  57787. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row2, tmp1));
  57788. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor2);
  57789. minor2 = SIMD.Float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  57790. // ----
  57791. tmp1 = SIMD.Float32x4.mul(row0, row1);
  57792. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  57793. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor2);
  57794. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row2, tmp1), minor3);
  57795. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  57796. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row3, tmp1), minor2);
  57797. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row2, tmp1));
  57798. // ----
  57799. tmp1 = SIMD.Float32x4.mul(row0, row3);
  57800. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  57801. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row2, tmp1));
  57802. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor2);
  57803. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  57804. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor1);
  57805. minor2 = SIMD.Float32x4.sub(minor2, SIMD.Float32x4.mul(row1, tmp1));
  57806. // ----
  57807. tmp1 = SIMD.Float32x4.mul(row0, row2);
  57808. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  57809. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor1);
  57810. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row1, tmp1));
  57811. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  57812. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row3, tmp1));
  57813. minor3 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor3);
  57814. // Compute determinant
  57815. var det = SIMD.Float32x4.mul(row0, minor0);
  57816. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  57817. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  57818. tmp1 = SIMD.Float32x4.reciprocalApproximation(det);
  57819. det = SIMD.Float32x4.sub(SIMD.Float32x4.add(tmp1, tmp1), SIMD.Float32x4.mul(det, SIMD.Float32x4.mul(tmp1, tmp1)));
  57820. det = SIMD.Float32x4.swizzle(det, 0, 0, 0, 0);
  57821. // These shuffles aren't necessary if the faulty transposition is done
  57822. // up at the top of this function.
  57823. //minor0 =SIMD.Float32x4.swizzle(minor0, 2, 1, 0, 3);
  57824. //minor1 =SIMD.Float32x4.swizzle(minor1, 2, 1, 0, 3);
  57825. //minor2 =SIMD.Float32x4.swizzle(minor2, 2, 1, 0, 3);
  57826. //minor3 =SIMD.Float32x4.swizzle(minor3, 2, 1, 0, 3);
  57827. // Compute final values by multiplying with 1/det
  57828. SIMD.Float32x4.store(dest, 0, SIMD.Float32x4.mul(det, minor0));
  57829. SIMD.Float32x4.store(dest, 4, SIMD.Float32x4.mul(det, minor1));
  57830. SIMD.Float32x4.store(dest, 8, minor2 = SIMD.Float32x4.mul(det, minor2));
  57831. SIMD.Float32x4.store(dest, 12, SIMD.Float32x4.mul(det, minor3));
  57832. return this;
  57833. };
  57834. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  57835. var out = result.m;
  57836. var center = SIMD.Float32x4(targetRef.x, targetRef.y, targetRef.z, 0.0);
  57837. var eye = SIMD.Float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0.0);
  57838. var up = SIMD.Float32x4(upRef.x, upRef.y, upRef.z, 0.0);
  57839. // cc.kmVec3Subtract(f, pCenter, pEye);
  57840. var f = SIMD.Float32x4.sub(center, eye);
  57841. // cc.kmVec3Normalize(f, f);
  57842. var tmp = SIMD.Float32x4.mul(f, f);
  57843. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  57844. f = SIMD.Float32x4.mul(f, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  57845. // cc.kmVec3Assign(up, pUp);
  57846. // cc.kmVec3Normalize(up, up);
  57847. tmp = SIMD.Float32x4.mul(up, up);
  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. up = SIMD.Float32x4.mul(up, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  57850. // cc.kmVec3Cross(s, f, up);
  57851. 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)));
  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. // cc.kmVec3Cross(u, s, f);
  57857. 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)));
  57858. // cc.kmVec3Normalize(s, s);
  57859. tmp = SIMD.Float32x4.mul(s, s);
  57860. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  57861. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  57862. var zero = SIMD.Float32x4.splat(0.0);
  57863. s = SIMD.Float32x4.neg(s);
  57864. var tmp01 = SIMD.Float32x4.shuffle(s, u, 0, 1, 4, 5);
  57865. var tmp23 = SIMD.Float32x4.shuffle(f, zero, 0, 1, 4, 5);
  57866. var a0 = SIMD.Float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  57867. var a1 = SIMD.Float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  57868. 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);
  57869. var a3 = SIMD.Float32x4(0.0, 0.0, 0.0, 1.0);
  57870. var b = SIMD.Float32x4(1.0, 0.0, 0.0, 0.0);
  57871. 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)))));
  57872. b = SIMD.Float32x4(0.0, 1.0, 0.0, 0.0);
  57873. 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)))));
  57874. b = SIMD.Float32x4(0.0, 0.0, 1.0, 0.0);
  57875. 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)))));
  57876. b = SIMD.Float32x4.replaceLane(SIMD.Float32x4.neg(eye), 3, 1.0);
  57877. 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)))));
  57878. };
  57879. return SIMDMatrix;
  57880. }());
  57881. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  57882. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  57883. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  57884. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  57885. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  57886. var SIMDHelper = (function () {
  57887. function SIMDHelper() {
  57888. }
  57889. Object.defineProperty(SIMDHelper, "IsEnabled", {
  57890. get: function () {
  57891. return SIMDHelper._isEnabled;
  57892. },
  57893. enumerable: true,
  57894. configurable: true
  57895. });
  57896. SIMDHelper.DisableSIMD = function () {
  57897. // Replace functions
  57898. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  57899. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  57900. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  57901. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  57902. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  57903. SIMDHelper._isEnabled = false;
  57904. };
  57905. SIMDHelper.EnableSIMD = function () {
  57906. if (self.SIMD === undefined) {
  57907. return;
  57908. }
  57909. // check if polyfills needed
  57910. if (!self.Math.fround) {
  57911. self.Math.fround = (function (array) { return function (x) {
  57912. return array[0] = x, array[0];
  57913. }; })(new Float32Array(1));
  57914. }
  57915. if (!self.Math.imul) {
  57916. self.Math.imul = function (a, b) {
  57917. var ah = (a >>> 16) & 0xffff;
  57918. var al = a & 0xffff;
  57919. var bh = (b >>> 16) & 0xffff;
  57920. var bl = b & 0xffff;
  57921. // the shift by 0 fixes the sign on the high part
  57922. // the final |0 converts the unsigned value into a signed value
  57923. return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);
  57924. };
  57925. }
  57926. // Replace functions
  57927. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  57928. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  57929. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  57930. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  57931. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  57932. SIMDHelper._isEnabled = true;
  57933. };
  57934. return SIMDHelper;
  57935. }());
  57936. SIMDHelper._isEnabled = false;
  57937. BABYLON.SIMDHelper = SIMDHelper;
  57938. })(BABYLON || (BABYLON = {}));
  57939. //# sourceMappingURL=babylon.math.SIMD.js.map
  57940. var BABYLON;
  57941. (function (BABYLON) {
  57942. var VRDistortionCorrectionPostProcess = (function (_super) {
  57943. __extends(VRDistortionCorrectionPostProcess, _super);
  57944. //ANY
  57945. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  57946. var _this = _super.call(this, name, "vrDistortionCorrection", [
  57947. 'LensCenter',
  57948. 'Scale',
  57949. 'ScaleIn',
  57950. 'HmdWarpParam'
  57951. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null) || this;
  57952. _this._isRightEye = isRightEye;
  57953. _this._distortionFactors = vrMetrics.distortionK;
  57954. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  57955. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  57956. _this.onSizeChangedObservable.add(function () {
  57957. _this.aspectRatio = _this.width * .5 / _this.height;
  57958. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  57959. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  57960. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  57961. });
  57962. _this.onApplyObservable.add(function (effect) {
  57963. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  57964. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  57965. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  57966. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  57967. });
  57968. return _this;
  57969. }
  57970. return VRDistortionCorrectionPostProcess;
  57971. }(BABYLON.PostProcess));
  57972. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  57973. })(BABYLON || (BABYLON = {}));
  57974. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  57975. var BABYLON;
  57976. (function (BABYLON) {
  57977. var AnaglyphPostProcess = (function (_super) {
  57978. __extends(AnaglyphPostProcess, _super);
  57979. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  57980. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  57981. _this._passedProcess = rigCameras[0]._rigPostProcess;
  57982. _this.onApplyObservable.add(function (effect) {
  57983. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  57984. });
  57985. return _this;
  57986. }
  57987. return AnaglyphPostProcess;
  57988. }(BABYLON.PostProcess));
  57989. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  57990. })(BABYLON || (BABYLON = {}));
  57991. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  57992. var BABYLON;
  57993. (function (BABYLON) {
  57994. var StereoscopicInterlacePostProcess = (function (_super) {
  57995. __extends(StereoscopicInterlacePostProcess, _super);
  57996. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  57997. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  57998. _this._passedProcess = rigCameras[0]._rigPostProcess;
  57999. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  58000. _this.onSizeChangedObservable.add(function () {
  58001. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  58002. });
  58003. _this.onApplyObservable.add(function (effect) {
  58004. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  58005. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  58006. });
  58007. return _this;
  58008. }
  58009. return StereoscopicInterlacePostProcess;
  58010. }(BABYLON.PostProcess));
  58011. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  58012. })(BABYLON || (BABYLON = {}));
  58013. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  58014. var BABYLON;
  58015. (function (BABYLON) {
  58016. var FreeCameraDeviceOrientationInput = (function () {
  58017. function FreeCameraDeviceOrientationInput() {
  58018. var _this = this;
  58019. this._screenOrientationAngle = 0;
  58020. this._screenQuaternion = new BABYLON.Quaternion();
  58021. this._alpha = 0;
  58022. this._beta = 0;
  58023. this._gamma = 0;
  58024. this._orientationChanged = function () {
  58025. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  58026. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  58027. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  58028. };
  58029. this._deviceOrientation = function (evt) {
  58030. _this._alpha = evt.alpha;
  58031. _this._beta = evt.beta;
  58032. _this._gamma = evt.gamma;
  58033. };
  58034. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  58035. this._orientationChanged();
  58036. }
  58037. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  58038. get: function () {
  58039. return this._camera;
  58040. },
  58041. set: function (camera) {
  58042. this._camera = camera;
  58043. if (!this._camera.rotationQuaternion)
  58044. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  58045. },
  58046. enumerable: true,
  58047. configurable: true
  58048. });
  58049. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  58050. window.addEventListener("orientationchange", this._orientationChanged);
  58051. window.addEventListener("deviceorientation", this._deviceOrientation);
  58052. //In certain cases, the attach control is called AFTER orientation was changed,
  58053. //So this is needed.
  58054. this._orientationChanged();
  58055. };
  58056. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  58057. window.removeEventListener("orientationchange", this._orientationChanged);
  58058. window.removeEventListener("deviceorientation", this._deviceOrientation);
  58059. };
  58060. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  58061. //if no device orientation provided, don't update the rotation.
  58062. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  58063. if (!this._alpha)
  58064. return;
  58065. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  58066. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  58067. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  58068. //Mirror on XY Plane
  58069. this._camera.rotationQuaternion.z *= -1;
  58070. this._camera.rotationQuaternion.w *= -1;
  58071. };
  58072. FreeCameraDeviceOrientationInput.prototype.getTypeName = function () {
  58073. return "FreeCameraDeviceOrientationInput";
  58074. };
  58075. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  58076. return "deviceOrientation";
  58077. };
  58078. return FreeCameraDeviceOrientationInput;
  58079. }());
  58080. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  58081. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  58082. })(BABYLON || (BABYLON = {}));
  58083. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  58084. var BABYLON;
  58085. (function (BABYLON) {
  58086. var ArcRotateCameraVRDeviceOrientationInput = (function () {
  58087. function ArcRotateCameraVRDeviceOrientationInput() {
  58088. this.alphaCorrection = 1;
  58089. this.betaCorrection = 1;
  58090. this.gammaCorrection = 1;
  58091. this._alpha = 0;
  58092. this._beta = 0;
  58093. this._gamma = 0;
  58094. this._dirty = false;
  58095. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  58096. }
  58097. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  58098. this.camera.attachControl(element, noPreventDefault);
  58099. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  58100. };
  58101. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  58102. var camera = this.camera;
  58103. this._alpha = +evt.alpha | 0;
  58104. this._beta = +evt.beta | 0;
  58105. this._gamma = +evt.gamma | 0;
  58106. this._dirty = true;
  58107. };
  58108. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  58109. if (this._dirty) {
  58110. this._dirty = false;
  58111. if (this._gamma < 0) {
  58112. this._gamma = 180 + this._gamma;
  58113. }
  58114. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  58115. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  58116. }
  58117. };
  58118. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  58119. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  58120. };
  58121. ArcRotateCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
  58122. return "ArcRotateCameraVRDeviceOrientationInput";
  58123. };
  58124. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  58125. return "VRDeviceOrientation";
  58126. };
  58127. return ArcRotateCameraVRDeviceOrientationInput;
  58128. }());
  58129. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  58130. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  58131. })(BABYLON || (BABYLON = {}));
  58132. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  58133. var BABYLON;
  58134. (function (BABYLON) {
  58135. var VRCameraMetrics = (function () {
  58136. function VRCameraMetrics() {
  58137. this.compensateDistortion = true;
  58138. }
  58139. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  58140. get: function () {
  58141. return this.hResolution / (2 * this.vResolution);
  58142. },
  58143. enumerable: true,
  58144. configurable: true
  58145. });
  58146. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  58147. get: function () {
  58148. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  58149. },
  58150. enumerable: true,
  58151. configurable: true
  58152. });
  58153. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  58154. get: function () {
  58155. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  58156. var h = (4 * meters) / this.hScreenSize;
  58157. return BABYLON.Matrix.Translation(h, 0, 0);
  58158. },
  58159. enumerable: true,
  58160. configurable: true
  58161. });
  58162. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  58163. get: function () {
  58164. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  58165. var h = (4 * meters) / this.hScreenSize;
  58166. return BABYLON.Matrix.Translation(-h, 0, 0);
  58167. },
  58168. enumerable: true,
  58169. configurable: true
  58170. });
  58171. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  58172. get: function () {
  58173. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  58174. },
  58175. enumerable: true,
  58176. configurable: true
  58177. });
  58178. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  58179. get: function () {
  58180. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  58181. },
  58182. enumerable: true,
  58183. configurable: true
  58184. });
  58185. VRCameraMetrics.GetDefault = function () {
  58186. var result = new VRCameraMetrics();
  58187. result.hResolution = 1280;
  58188. result.vResolution = 800;
  58189. result.hScreenSize = 0.149759993;
  58190. result.vScreenSize = 0.0935999975;
  58191. result.vScreenCenter = 0.0467999987;
  58192. result.eyeToScreenDistance = 0.0410000011;
  58193. result.lensSeparationDistance = 0.0635000020;
  58194. result.interpupillaryDistance = 0.0640000030;
  58195. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  58196. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  58197. result.postProcessScaleFactor = 1.714605507808412;
  58198. result.lensCenterOffset = 0.151976421;
  58199. return result;
  58200. };
  58201. return VRCameraMetrics;
  58202. }());
  58203. BABYLON.VRCameraMetrics = VRCameraMetrics;
  58204. })(BABYLON || (BABYLON = {}));
  58205. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  58206. var BABYLON;
  58207. (function (BABYLON) {
  58208. var WebVRFreeCamera = (function (_super) {
  58209. __extends(WebVRFreeCamera, _super);
  58210. function WebVRFreeCamera(name, position, scene, webVROptions) {
  58211. if (webVROptions === void 0) { webVROptions = {}; }
  58212. var _this = _super.call(this, name, position, scene) || this;
  58213. _this.webVROptions = webVROptions;
  58214. _this._vrDevice = null;
  58215. _this.rawPose = null;
  58216. _this._vrEnabled = false;
  58217. _this._specsVersion = 1.1;
  58218. _this._attached = false;
  58219. _this._positionOffset = BABYLON.Vector3.Zero();
  58220. _this._descendants = [];
  58221. _this.devicePosition = BABYLON.Vector3.Zero();
  58222. _this.deviceScaleFactor = 1;
  58223. _this.controllers = [];
  58224. _this.rigParenting = true; // should the rig cameras be used as parent instead of this camera.
  58225. //legacy support - the compensation boolean was removed.
  58226. if (arguments.length === 5) {
  58227. _this.webVROptions = arguments[4];
  58228. }
  58229. // default webVR options
  58230. if (_this.webVROptions.trackPosition == undefined) {
  58231. _this.webVROptions.trackPosition = true;
  58232. }
  58233. if (_this.webVROptions.controllerMeshes == undefined) {
  58234. _this.webVROptions.controllerMeshes = true;
  58235. }
  58236. if (_this.webVROptions.defaultLightningOnControllers == undefined) {
  58237. _this.webVROptions.defaultLightningOnControllers = true;
  58238. }
  58239. _this.rotationQuaternion = new BABYLON.Quaternion();
  58240. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  58241. if (_this.webVROptions && _this.webVROptions.positionScale) {
  58242. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  58243. }
  58244. //enable VR
  58245. _this.getEngine().initWebVR();
  58246. if (!_this.getEngine().vrDisplaysPromise) {
  58247. BABYLON.Tools.Error("WebVR is not enabled on your browser");
  58248. }
  58249. else {
  58250. //check specs version
  58251. if (!window.VRFrameData) {
  58252. _this._specsVersion = 1.0;
  58253. _this._frameData = {};
  58254. }
  58255. else {
  58256. _this._frameData = new VRFrameData();
  58257. }
  58258. _this.getEngine().vrDisplaysPromise.then(function (devices) {
  58259. if (devices.length > 0) {
  58260. _this._vrEnabled = true;
  58261. if (_this.webVROptions.displayName) {
  58262. var found = devices.some(function (device) {
  58263. if (device.displayName === _this.webVROptions.displayName) {
  58264. _this._vrDevice = device;
  58265. return true;
  58266. }
  58267. else {
  58268. return false;
  58269. }
  58270. });
  58271. if (!found) {
  58272. _this._vrDevice = devices[0];
  58273. BABYLON.Tools.Warn("Display " + _this.webVROptions.displayName + " was not found. Using " + _this._vrDevice.displayName);
  58274. }
  58275. }
  58276. else {
  58277. //choose the first one
  58278. _this._vrDevice = devices[0];
  58279. }
  58280. //reset the rig parameters.
  58281. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  58282. if (_this._attached) {
  58283. _this.getEngine().enableVR(_this._vrDevice);
  58284. }
  58285. }
  58286. else {
  58287. BABYLON.Tools.Error("No WebVR devices found!");
  58288. }
  58289. });
  58290. }
  58291. // try to attach the controllers, if found.
  58292. _this.initControllers();
  58293. /**
  58294. * The idea behind the following lines:
  58295. * objects that have the camera as parent should actually have the rig cameras as a parent.
  58296. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  58297. * the second will not show it correctly.
  58298. *
  58299. * To solve this - each object that has the camera as parent will be added to a protected array.
  58300. * When the rig camera renders, it will take this array and set all of those to be its children.
  58301. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  58302. * Amazing!
  58303. */
  58304. scene.onBeforeCameraRenderObservable.add(function (camera) {
  58305. if (camera.parent === _this && _this.rigParenting) {
  58306. _this._descendants = _this.getDescendants(true, function (n) {
  58307. // don't take the cameras or the controllers!
  58308. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  58309. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  58310. return !isController && !isRigCamera;
  58311. });
  58312. _this._descendants.forEach(function (node) {
  58313. node.parent = camera;
  58314. });
  58315. }
  58316. });
  58317. scene.onAfterCameraRenderObservable.add(function (camera) {
  58318. if (camera.parent === _this && _this.rigParenting) {
  58319. _this._descendants.forEach(function (node) {
  58320. node.parent = _this;
  58321. });
  58322. }
  58323. });
  58324. return _this;
  58325. }
  58326. Object.defineProperty(WebVRFreeCamera.prototype, "onControllersAttached", {
  58327. set: function (callback) {
  58328. this._onControllersAttached = callback;
  58329. // after setting - if the controllers are already set, execute the callback.
  58330. if (this.controllers.length >= 2) {
  58331. callback(this.controllers);
  58332. }
  58333. },
  58334. enumerable: true,
  58335. configurable: true
  58336. });
  58337. WebVRFreeCamera.prototype.getLeftCamera = function () {
  58338. return this._rigCameras[0];
  58339. };
  58340. WebVRFreeCamera.prototype.getRightCamera = function () {
  58341. return this._rigCameras[1];
  58342. };
  58343. WebVRFreeCamera.prototype.getLeftTarget = function () {
  58344. return this._rigCameras[0].getTarget();
  58345. };
  58346. WebVRFreeCamera.prototype.getRightTarget = function () {
  58347. return this._rigCameras[1].getTarget();
  58348. };
  58349. WebVRFreeCamera.prototype._checkInputs = function () {
  58350. if (this._vrEnabled) {
  58351. if (this._specsVersion === 1.1) {
  58352. this._vrDevice.getFrameData(this._frameData);
  58353. }
  58354. else {
  58355. //backwards comp
  58356. var pose = this._vrDevice.getPose();
  58357. this._frameData.pose = pose;
  58358. // calculate view and projection matrix
  58359. }
  58360. this.updateFromDevice(this._frameData.pose);
  58361. }
  58362. _super.prototype._checkInputs.call(this);
  58363. };
  58364. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  58365. if (poseData && poseData.orientation) {
  58366. this.rawPose = poseData;
  58367. this.deviceRotationQuaternion.copyFromFloats(this.rawPose.orientation[0], this.rawPose.orientation[1], -this.rawPose.orientation[2], -this.rawPose.orientation[3]);
  58368. if (this.getScene().useRightHandedSystem) {
  58369. this.deviceRotationQuaternion.z *= -1;
  58370. this.deviceRotationQuaternion.w *= -1;
  58371. }
  58372. if (this.webVROptions.trackPosition && this.rawPose.position) {
  58373. this.devicePosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  58374. if (this.getScene().useRightHandedSystem) {
  58375. this.devicePosition.z *= -1;
  58376. }
  58377. }
  58378. }
  58379. };
  58380. /**
  58381. * WebVR's attach control will start broadcasting frames to the device.
  58382. * Note that in certain browsers (chrome for example) this function must be called
  58383. * within a user-interaction callback. Example:
  58384. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  58385. *
  58386. * @param {HTMLElement} element
  58387. * @param {boolean} [noPreventDefault]
  58388. *
  58389. * @memberOf WebVRFreeCamera
  58390. */
  58391. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  58392. _super.prototype.attachControl.call(this, element, noPreventDefault);
  58393. this._attached = true;
  58394. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  58395. if (this._vrEnabled) {
  58396. this.getEngine().enableVR(this._vrDevice);
  58397. }
  58398. };
  58399. WebVRFreeCamera.prototype.detachControl = function (element) {
  58400. _super.prototype.detachControl.call(this, element);
  58401. this._vrEnabled = false;
  58402. this._attached = false;
  58403. this.getEngine().disableVR();
  58404. };
  58405. WebVRFreeCamera.prototype.getClassName = function () {
  58406. return "WebVRFreeCamera";
  58407. };
  58408. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  58409. //uses the vrDisplay's "resetPose()".
  58410. //pitch and roll won't be affected.
  58411. this._vrDevice.resetPose();
  58412. };
  58413. WebVRFreeCamera.prototype._updateRigCameras = function () {
  58414. var camLeft = this._rigCameras[0];
  58415. var camRight = this._rigCameras[1];
  58416. camLeft.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  58417. camRight.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  58418. camLeft.position.copyFrom(this.devicePosition);
  58419. camRight.position.copyFrom(this.devicePosition);
  58420. };
  58421. /**
  58422. * This function is called by the two RIG cameras.
  58423. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  58424. */
  58425. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  58426. var _this = this;
  58427. //WebVR 1.0
  58428. if (this._cameraRigParams["specs"] === 1.0) {
  58429. this._updateCameraRotationMatrix();
  58430. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  58431. // Computing target and final matrix
  58432. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  58433. if (this.getScene().useRightHandedSystem) {
  58434. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._webvrViewMatrix);
  58435. }
  58436. else {
  58437. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._webvrViewMatrix);
  58438. }
  58439. //now move the eye in the right direction
  58440. var eyeParams = this._cameraRigParams["eyeParameters"];
  58441. var offset = eyeParams.offset;
  58442. // it will actually always be 0, but just in case
  58443. if (this.getScene().useRightHandedSystem) {
  58444. offset[2] *= -1;
  58445. }
  58446. BABYLON.Matrix.TranslationToRef(-offset[0], offset[1], -offset[2], BABYLON.Tmp.Matrix[0]);
  58447. this._webvrViewMatrix.multiplyToRef(BABYLON.Tmp.Matrix[0], this._webvrViewMatrix);
  58448. }
  58449. else {
  58450. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  58451. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  58452. if (!this.getScene().useRightHandedSystem) {
  58453. [2, 6, 8, 9, 14].forEach(function (num) {
  58454. _this._webvrViewMatrix.m[num] *= -1;
  58455. });
  58456. }
  58457. // update the camera rotation matrix
  58458. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  58459. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  58460. // Computing target and final matrix
  58461. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  58462. }
  58463. var parentCamera = this._cameraRigParams["parentCamera"];
  58464. // should the view matrix be updated with scale and position offset?
  58465. if (parentCamera.deviceScaleFactor !== 1) {
  58466. this._webvrViewMatrix.invert();
  58467. // scale the position, if set
  58468. if (parentCamera.deviceScaleFactor) {
  58469. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  58470. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  58471. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  58472. }
  58473. this._webvrViewMatrix.invert();
  58474. }
  58475. return this._webvrViewMatrix;
  58476. };
  58477. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  58478. var _this = this;
  58479. if (this._cameraRigParams["specs"] === 1.0) {
  58480. var eyeParams = this._cameraRigParams["eyeParameters"];
  58481. // deprecated!!
  58482. BABYLON.Matrix.PerspectiveFovWebVRToRef(eyeParams.fieldOfView, 0.1, 1000, this._projectionMatrix, this.getScene().useRightHandedSystem);
  58483. }
  58484. else {
  58485. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  58486. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  58487. //babylon compatible matrix
  58488. if (!this.getScene().useRightHandedSystem) {
  58489. [8, 9, 10, 11].forEach(function (num) {
  58490. _this._projectionMatrix.m[num] *= -1;
  58491. });
  58492. }
  58493. }
  58494. return this._projectionMatrix;
  58495. };
  58496. WebVRFreeCamera.prototype.initControllers = function () {
  58497. var _this = this;
  58498. this.controllers = [];
  58499. new BABYLON.Gamepads(function (gp) {
  58500. if (gp.type === BABYLON.Gamepad.POSE_ENABLED) {
  58501. var webVrController = gp;
  58502. if (_this.webVROptions.controllerMeshes) {
  58503. webVrController.initControllerMesh(_this.getScene(), function (loadedMesh) {
  58504. if (_this.webVROptions.defaultLightningOnControllers) {
  58505. if (!_this._lightOnControllers) {
  58506. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  58507. }
  58508. loadedMesh.getChildren().forEach(function (mesh) {
  58509. _this._lightOnControllers.includedOnlyMeshes.push(mesh);
  58510. });
  58511. }
  58512. });
  58513. }
  58514. webVrController.attachToPoseControlledCamera(_this);
  58515. // since this is async - sanity check. Is the controller already stored?
  58516. if (_this.controllers.indexOf(webVrController) === -1) {
  58517. //add to the controllers array
  58518. _this.controllers.push(webVrController);
  58519. //did we find enough controllers? Great! let the developer know.
  58520. if (_this._onControllersAttached && _this.controllers.length >= 2) {
  58521. _this._onControllersAttached(_this.controllers);
  58522. }
  58523. }
  58524. }
  58525. });
  58526. };
  58527. return WebVRFreeCamera;
  58528. }(BABYLON.FreeCamera));
  58529. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  58530. })(BABYLON || (BABYLON = {}));
  58531. //# sourceMappingURL=babylon.webVRCamera.js.map
  58532. /// <reference path="babylon.freeCamera.ts" />
  58533. var BABYLON;
  58534. (function (BABYLON) {
  58535. // We're mainly based on the logic defined into the FreeCamera code
  58536. var DeviceOrientationCamera = (function (_super) {
  58537. __extends(DeviceOrientationCamera, _super);
  58538. function DeviceOrientationCamera(name, position, scene) {
  58539. var _this = _super.call(this, name, position, scene) || this;
  58540. _this._quaternionCache = new BABYLON.Quaternion();
  58541. _this.inputs.addDeviceOrientation();
  58542. return _this;
  58543. }
  58544. DeviceOrientationCamera.prototype.getClassName = function () {
  58545. return "DeviceOrientationCamera";
  58546. };
  58547. DeviceOrientationCamera.prototype._checkInputs = function () {
  58548. _super.prototype._checkInputs.call(this);
  58549. this._quaternionCache.copyFrom(this.rotationQuaternion);
  58550. if (this._initialQuaternion) {
  58551. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  58552. }
  58553. };
  58554. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  58555. var _this = this;
  58556. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  58557. //can only work if this camera has a rotation quaternion already.
  58558. if (!this.rotationQuaternion)
  58559. return;
  58560. if (!this._initialQuaternion) {
  58561. this._initialQuaternion = new BABYLON.Quaternion();
  58562. }
  58563. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  58564. ['x', 'y', 'z'].forEach(function (axisName) {
  58565. if (!axis[axisName]) {
  58566. _this._initialQuaternion[axisName] = 0;
  58567. }
  58568. else {
  58569. _this._initialQuaternion[axisName] *= -1;
  58570. }
  58571. });
  58572. this._initialQuaternion.normalize();
  58573. //force rotation update
  58574. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  58575. };
  58576. return DeviceOrientationCamera;
  58577. }(BABYLON.FreeCamera));
  58578. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  58579. })(BABYLON || (BABYLON = {}));
  58580. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  58581. var BABYLON;
  58582. (function (BABYLON) {
  58583. var VRDeviceOrientationFreeCamera = (function (_super) {
  58584. __extends(VRDeviceOrientationFreeCamera, _super);
  58585. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  58586. if (compensateDistortion === void 0) { compensateDistortion = true; }
  58587. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  58588. var _this = _super.call(this, name, position, scene) || this;
  58589. vrCameraMetrics.compensateDistortion = compensateDistortion;
  58590. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  58591. return _this;
  58592. }
  58593. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  58594. return "VRDeviceOrientationFreeCamera";
  58595. };
  58596. return VRDeviceOrientationFreeCamera;
  58597. }(BABYLON.DeviceOrientationCamera));
  58598. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  58599. var VRDeviceOrientationGamepadCamera = (function (_super) {
  58600. __extends(VRDeviceOrientationGamepadCamera, _super);
  58601. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  58602. if (compensateDistortion === void 0) { compensateDistortion = true; }
  58603. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  58604. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  58605. _this.inputs.addGamepad();
  58606. return _this;
  58607. }
  58608. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  58609. return "VRDeviceOrientationGamepadCamera";
  58610. };
  58611. return VRDeviceOrientationGamepadCamera;
  58612. }(VRDeviceOrientationFreeCamera));
  58613. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  58614. var VRDeviceOrientationArcRotateCamera = (function (_super) {
  58615. __extends(VRDeviceOrientationArcRotateCamera, _super);
  58616. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  58617. if (compensateDistortion === void 0) { compensateDistortion = true; }
  58618. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  58619. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  58620. vrCameraMetrics.compensateDistortion = compensateDistortion;
  58621. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  58622. _this.inputs.addVRDeviceOrientation();
  58623. return _this;
  58624. }
  58625. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  58626. return "VRDeviceOrientationArcRotateCamera";
  58627. };
  58628. return VRDeviceOrientationArcRotateCamera;
  58629. }(BABYLON.ArcRotateCamera));
  58630. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  58631. })(BABYLON || (BABYLON = {}));
  58632. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  58633. /// <reference path="babylon.freeCamera.ts" />
  58634. /// <reference path="babylon.arcRotateCamera.ts" />
  58635. /// <reference path="babylon.gamepadCamera.ts" />
  58636. /// <reference path="babylon.universalCamera.ts" />
  58637. var BABYLON;
  58638. (function (BABYLON) {
  58639. var AnaglyphFreeCamera = (function (_super) {
  58640. __extends(AnaglyphFreeCamera, _super);
  58641. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  58642. var _this = _super.call(this, name, position, scene) || this;
  58643. _this.interaxialDistance = interaxialDistance;
  58644. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  58645. return _this;
  58646. }
  58647. AnaglyphFreeCamera.prototype.getClassName = function () {
  58648. return "AnaglyphFreeCamera";
  58649. };
  58650. return AnaglyphFreeCamera;
  58651. }(BABYLON.FreeCamera));
  58652. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  58653. var AnaglyphArcRotateCamera = (function (_super) {
  58654. __extends(AnaglyphArcRotateCamera, _super);
  58655. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  58656. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  58657. _this.interaxialDistance = interaxialDistance;
  58658. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  58659. return _this;
  58660. }
  58661. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  58662. return "AnaglyphArcRotateCamera";
  58663. };
  58664. return AnaglyphArcRotateCamera;
  58665. }(BABYLON.ArcRotateCamera));
  58666. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  58667. var AnaglyphGamepadCamera = (function (_super) {
  58668. __extends(AnaglyphGamepadCamera, _super);
  58669. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  58670. var _this = _super.call(this, name, position, scene) || this;
  58671. _this.interaxialDistance = interaxialDistance;
  58672. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  58673. return _this;
  58674. }
  58675. AnaglyphGamepadCamera.prototype.getClassName = function () {
  58676. return "AnaglyphGamepadCamera";
  58677. };
  58678. return AnaglyphGamepadCamera;
  58679. }(BABYLON.GamepadCamera));
  58680. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  58681. var AnaglyphUniversalCamera = (function (_super) {
  58682. __extends(AnaglyphUniversalCamera, _super);
  58683. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  58684. var _this = _super.call(this, name, position, scene) || this;
  58685. _this.interaxialDistance = interaxialDistance;
  58686. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  58687. return _this;
  58688. }
  58689. AnaglyphUniversalCamera.prototype.getClassName = function () {
  58690. return "AnaglyphUniversalCamera";
  58691. };
  58692. return AnaglyphUniversalCamera;
  58693. }(BABYLON.UniversalCamera));
  58694. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  58695. var StereoscopicFreeCamera = (function (_super) {
  58696. __extends(StereoscopicFreeCamera, _super);
  58697. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  58698. var _this = _super.call(this, name, position, scene) || this;
  58699. _this.interaxialDistance = interaxialDistance;
  58700. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  58701. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  58702. return _this;
  58703. }
  58704. StereoscopicFreeCamera.prototype.getClassName = function () {
  58705. return "StereoscopicFreeCamera";
  58706. };
  58707. return StereoscopicFreeCamera;
  58708. }(BABYLON.FreeCamera));
  58709. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  58710. var StereoscopicArcRotateCamera = (function (_super) {
  58711. __extends(StereoscopicArcRotateCamera, _super);
  58712. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  58713. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  58714. _this.interaxialDistance = interaxialDistance;
  58715. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  58716. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  58717. return _this;
  58718. }
  58719. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  58720. return "StereoscopicArcRotateCamera";
  58721. };
  58722. return StereoscopicArcRotateCamera;
  58723. }(BABYLON.ArcRotateCamera));
  58724. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  58725. var StereoscopicGamepadCamera = (function (_super) {
  58726. __extends(StereoscopicGamepadCamera, _super);
  58727. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  58728. var _this = _super.call(this, name, position, scene) || this;
  58729. _this.interaxialDistance = interaxialDistance;
  58730. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  58731. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  58732. return _this;
  58733. }
  58734. StereoscopicGamepadCamera.prototype.getClassName = function () {
  58735. return "StereoscopicGamepadCamera";
  58736. };
  58737. return StereoscopicGamepadCamera;
  58738. }(BABYLON.GamepadCamera));
  58739. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  58740. var StereoscopicUniversalCamera = (function (_super) {
  58741. __extends(StereoscopicUniversalCamera, _super);
  58742. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  58743. var _this = _super.call(this, name, position, scene) || this;
  58744. _this.interaxialDistance = interaxialDistance;
  58745. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  58746. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  58747. return _this;
  58748. }
  58749. StereoscopicUniversalCamera.prototype.getClassName = function () {
  58750. return "StereoscopicUniversalCamera";
  58751. };
  58752. return StereoscopicUniversalCamera;
  58753. }(BABYLON.UniversalCamera));
  58754. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  58755. })(BABYLON || (BABYLON = {}));
  58756. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  58757. // Mainly based on these 2 articles :
  58758. // 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
  58759. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  58760. var BABYLON;
  58761. (function (BABYLON) {
  58762. var JoystickAxis;
  58763. (function (JoystickAxis) {
  58764. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  58765. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  58766. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  58767. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  58768. var VirtualJoystick = (function () {
  58769. function VirtualJoystick(leftJoystick) {
  58770. var _this = this;
  58771. if (leftJoystick) {
  58772. this._leftJoystick = true;
  58773. }
  58774. else {
  58775. this._leftJoystick = false;
  58776. }
  58777. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  58778. VirtualJoystick._globalJoystickIndex++;
  58779. // By default left & right arrow keys are moving the X
  58780. // and up & down keys are moving the Y
  58781. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  58782. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  58783. this.reverseLeftRight = false;
  58784. this.reverseUpDown = false;
  58785. // collections of pointers
  58786. this._touches = new BABYLON.StringDictionary();
  58787. this.deltaPosition = BABYLON.Vector3.Zero();
  58788. this._joystickSensibility = 25;
  58789. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  58790. this._rotationSpeed = 25;
  58791. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  58792. this._rotateOnAxisRelativeToMesh = false;
  58793. this._onResize = function (evt) {
  58794. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  58795. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  58796. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  58797. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  58798. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  58799. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  58800. };
  58801. // injecting a canvas element on top of the canvas 3D game
  58802. if (!VirtualJoystick.vjCanvas) {
  58803. window.addEventListener("resize", this._onResize, false);
  58804. VirtualJoystick.vjCanvas = document.createElement("canvas");
  58805. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  58806. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  58807. VirtualJoystick.vjCanvas.width = window.innerWidth;
  58808. VirtualJoystick.vjCanvas.height = window.innerHeight;
  58809. VirtualJoystick.vjCanvas.style.width = "100%";
  58810. VirtualJoystick.vjCanvas.style.height = "100%";
  58811. VirtualJoystick.vjCanvas.style.position = "absolute";
  58812. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  58813. VirtualJoystick.vjCanvas.style.top = "0px";
  58814. VirtualJoystick.vjCanvas.style.left = "0px";
  58815. VirtualJoystick.vjCanvas.style.zIndex = "5";
  58816. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  58817. // Support for jQuery PEP polyfill
  58818. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  58819. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  58820. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  58821. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  58822. document.body.appendChild(VirtualJoystick.vjCanvas);
  58823. }
  58824. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  58825. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  58826. this.pressed = false;
  58827. // default joystick color
  58828. this._joystickColor = "cyan";
  58829. this._joystickPointerID = -1;
  58830. // current joystick position
  58831. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  58832. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  58833. // origin joystick position
  58834. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  58835. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  58836. this._onPointerDownHandlerRef = function (evt) {
  58837. _this._onPointerDown(evt);
  58838. };
  58839. this._onPointerMoveHandlerRef = function (evt) {
  58840. _this._onPointerMove(evt);
  58841. };
  58842. this._onPointerOutHandlerRef = function (evt) {
  58843. _this._onPointerUp(evt);
  58844. };
  58845. this._onPointerUpHandlerRef = function (evt) {
  58846. _this._onPointerUp(evt);
  58847. };
  58848. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  58849. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  58850. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  58851. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  58852. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  58853. evt.preventDefault(); // Disables system menu
  58854. }, false);
  58855. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  58856. }
  58857. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  58858. this._joystickSensibility = newJoystickSensibility;
  58859. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  58860. };
  58861. VirtualJoystick.prototype._onPointerDown = function (e) {
  58862. var positionOnScreenCondition;
  58863. e.preventDefault();
  58864. if (this._leftJoystick === true) {
  58865. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  58866. }
  58867. else {
  58868. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  58869. }
  58870. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  58871. // First contact will be dedicated to the virtual joystick
  58872. this._joystickPointerID = e.pointerId;
  58873. this._joystickPointerStartPos.x = e.clientX;
  58874. this._joystickPointerStartPos.y = e.clientY;
  58875. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  58876. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  58877. this._deltaJoystickVector.x = 0;
  58878. this._deltaJoystickVector.y = 0;
  58879. this.pressed = true;
  58880. this._touches.add(e.pointerId.toString(), e);
  58881. }
  58882. else {
  58883. // You can only trigger the action buttons with a joystick declared
  58884. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  58885. this._action();
  58886. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  58887. }
  58888. }
  58889. };
  58890. VirtualJoystick.prototype._onPointerMove = function (e) {
  58891. // If the current pointer is the one associated to the joystick (first touch contact)
  58892. if (this._joystickPointerID == e.pointerId) {
  58893. this._joystickPointerPos.x = e.clientX;
  58894. this._joystickPointerPos.y = e.clientY;
  58895. this._deltaJoystickVector = this._joystickPointerPos.clone();
  58896. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  58897. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  58898. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  58899. switch (this._axisTargetedByLeftAndRight) {
  58900. case JoystickAxis.X:
  58901. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  58902. break;
  58903. case JoystickAxis.Y:
  58904. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  58905. break;
  58906. case JoystickAxis.Z:
  58907. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  58908. break;
  58909. }
  58910. var directionUpDown = this.reverseUpDown ? 1 : -1;
  58911. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  58912. switch (this._axisTargetedByUpAndDown) {
  58913. case JoystickAxis.X:
  58914. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  58915. break;
  58916. case JoystickAxis.Y:
  58917. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  58918. break;
  58919. case JoystickAxis.Z:
  58920. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  58921. break;
  58922. }
  58923. }
  58924. else {
  58925. var data = this._touches.get(e.pointerId.toString());
  58926. if (data) {
  58927. data.x = e.clientX;
  58928. data.y = e.clientY;
  58929. }
  58930. }
  58931. };
  58932. VirtualJoystick.prototype._onPointerUp = function (e) {
  58933. if (this._joystickPointerID == e.pointerId) {
  58934. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  58935. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  58936. this._joystickPointerID = -1;
  58937. this.pressed = false;
  58938. }
  58939. else {
  58940. var touch = this._touches.get(e.pointerId.toString());
  58941. if (touch) {
  58942. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  58943. }
  58944. }
  58945. this._deltaJoystickVector.x = 0;
  58946. this._deltaJoystickVector.y = 0;
  58947. this._touches.remove(e.pointerId.toString());
  58948. };
  58949. /**
  58950. * Change the color of the virtual joystick
  58951. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  58952. */
  58953. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  58954. this._joystickColor = newColor;
  58955. };
  58956. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  58957. this._action = action;
  58958. };
  58959. // Define which axis you'd like to control for left & right
  58960. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  58961. switch (axis) {
  58962. case JoystickAxis.X:
  58963. case JoystickAxis.Y:
  58964. case JoystickAxis.Z:
  58965. this._axisTargetedByLeftAndRight = axis;
  58966. break;
  58967. default:
  58968. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  58969. break;
  58970. }
  58971. };
  58972. // Define which axis you'd like to control for up & down
  58973. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  58974. switch (axis) {
  58975. case JoystickAxis.X:
  58976. case JoystickAxis.Y:
  58977. case JoystickAxis.Z:
  58978. this._axisTargetedByUpAndDown = axis;
  58979. break;
  58980. default:
  58981. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  58982. break;
  58983. }
  58984. };
  58985. VirtualJoystick.prototype._clearCanvas = function () {
  58986. if (this._leftJoystick) {
  58987. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  58988. }
  58989. else {
  58990. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  58991. }
  58992. };
  58993. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  58994. var _this = this;
  58995. if (this.pressed) {
  58996. this._touches.forEach(function (key, touch) {
  58997. if (touch.pointerId === _this._joystickPointerID) {
  58998. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  58999. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  59000. VirtualJoystick.vjCanvasContext.beginPath();
  59001. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  59002. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  59003. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 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.lineWidth = 2;
  59009. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  59010. VirtualJoystick.vjCanvasContext.stroke();
  59011. VirtualJoystick.vjCanvasContext.closePath();
  59012. VirtualJoystick.vjCanvasContext.beginPath();
  59013. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  59014. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  59015. VirtualJoystick.vjCanvasContext.stroke();
  59016. VirtualJoystick.vjCanvasContext.closePath();
  59017. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  59018. }
  59019. else {
  59020. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  59021. VirtualJoystick.vjCanvasContext.beginPath();
  59022. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  59023. VirtualJoystick.vjCanvasContext.beginPath();
  59024. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  59025. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  59026. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  59027. VirtualJoystick.vjCanvasContext.stroke();
  59028. VirtualJoystick.vjCanvasContext.closePath();
  59029. touch.prevX = touch.x;
  59030. touch.prevY = touch.y;
  59031. }
  59032. ;
  59033. });
  59034. }
  59035. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  59036. };
  59037. VirtualJoystick.prototype.releaseCanvas = function () {
  59038. if (VirtualJoystick.vjCanvas) {
  59039. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  59040. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  59041. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  59042. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  59043. window.removeEventListener("resize", this._onResize);
  59044. document.body.removeChild(VirtualJoystick.vjCanvas);
  59045. VirtualJoystick.vjCanvas = null;
  59046. }
  59047. };
  59048. return VirtualJoystick;
  59049. }());
  59050. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  59051. VirtualJoystick._globalJoystickIndex = 0;
  59052. BABYLON.VirtualJoystick = VirtualJoystick;
  59053. })(BABYLON || (BABYLON = {}));
  59054. //# sourceMappingURL=babylon.virtualJoystick.js.map
  59055. var BABYLON;
  59056. (function (BABYLON) {
  59057. // We're mainly based on the logic defined into the FreeCamera code
  59058. var VirtualJoysticksCamera = (function (_super) {
  59059. __extends(VirtualJoysticksCamera, _super);
  59060. function VirtualJoysticksCamera(name, position, scene) {
  59061. var _this = _super.call(this, name, position, scene) || this;
  59062. _this.inputs.addVirtualJoystick();
  59063. return _this;
  59064. }
  59065. VirtualJoysticksCamera.prototype.getClassName = function () {
  59066. return "VirtualJoysticksCamera";
  59067. };
  59068. return VirtualJoysticksCamera;
  59069. }(BABYLON.FreeCamera));
  59070. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  59071. })(BABYLON || (BABYLON = {}));
  59072. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  59073. var BABYLON;
  59074. (function (BABYLON) {
  59075. var FreeCameraVirtualJoystickInput = (function () {
  59076. function FreeCameraVirtualJoystickInput() {
  59077. }
  59078. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  59079. return this._leftjoystick;
  59080. };
  59081. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  59082. return this._rightjoystick;
  59083. };
  59084. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  59085. if (this._leftjoystick) {
  59086. var camera = this.camera;
  59087. var speed = camera._computeLocalCameraSpeed() * 50;
  59088. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  59089. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  59090. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  59091. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  59092. if (!this._leftjoystick.pressed) {
  59093. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  59094. }
  59095. if (!this._rightjoystick.pressed) {
  59096. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  59097. }
  59098. }
  59099. };
  59100. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  59101. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  59102. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  59103. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  59104. this._leftjoystick.setJoystickSensibility(0.15);
  59105. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  59106. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  59107. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  59108. this._rightjoystick.reverseUpDown = true;
  59109. this._rightjoystick.setJoystickSensibility(0.05);
  59110. this._rightjoystick.setJoystickColor("yellow");
  59111. };
  59112. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  59113. this._leftjoystick.releaseCanvas();
  59114. this._rightjoystick.releaseCanvas();
  59115. };
  59116. FreeCameraVirtualJoystickInput.prototype.getTypeName = function () {
  59117. return "FreeCameraVirtualJoystickInput";
  59118. };
  59119. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  59120. return "virtualJoystick";
  59121. };
  59122. return FreeCameraVirtualJoystickInput;
  59123. }());
  59124. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  59125. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  59126. })(BABYLON || (BABYLON = {}));
  59127. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  59128. var BABYLON;
  59129. (function (BABYLON) {
  59130. var SimplificationSettings = (function () {
  59131. function SimplificationSettings(quality, distance, optimizeMesh) {
  59132. this.quality = quality;
  59133. this.distance = distance;
  59134. this.optimizeMesh = optimizeMesh;
  59135. }
  59136. return SimplificationSettings;
  59137. }());
  59138. BABYLON.SimplificationSettings = SimplificationSettings;
  59139. var SimplificationQueue = (function () {
  59140. function SimplificationQueue() {
  59141. this.running = false;
  59142. this._simplificationArray = [];
  59143. }
  59144. SimplificationQueue.prototype.addTask = function (task) {
  59145. this._simplificationArray.push(task);
  59146. };
  59147. SimplificationQueue.prototype.executeNext = function () {
  59148. var task = this._simplificationArray.pop();
  59149. if (task) {
  59150. this.running = true;
  59151. this.runSimplification(task);
  59152. }
  59153. else {
  59154. this.running = false;
  59155. }
  59156. };
  59157. SimplificationQueue.prototype.runSimplification = function (task) {
  59158. var _this = this;
  59159. if (task.parallelProcessing) {
  59160. //parallel simplifier
  59161. task.settings.forEach(function (setting) {
  59162. var simplifier = _this.getSimplifier(task);
  59163. simplifier.simplify(setting, function (newMesh) {
  59164. task.mesh.addLODLevel(setting.distance, newMesh);
  59165. newMesh.isVisible = true;
  59166. //check if it is the last
  59167. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  59168. //all done, run the success callback.
  59169. task.successCallback();
  59170. }
  59171. _this.executeNext();
  59172. });
  59173. });
  59174. }
  59175. else {
  59176. //single simplifier.
  59177. var simplifier = this.getSimplifier(task);
  59178. var runDecimation = function (setting, callback) {
  59179. simplifier.simplify(setting, function (newMesh) {
  59180. task.mesh.addLODLevel(setting.distance, newMesh);
  59181. newMesh.isVisible = true;
  59182. //run the next quality level
  59183. callback();
  59184. });
  59185. };
  59186. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  59187. runDecimation(task.settings[loop.index], function () {
  59188. loop.executeNext();
  59189. });
  59190. }, function () {
  59191. //execution ended, run the success callback.
  59192. if (task.successCallback) {
  59193. task.successCallback();
  59194. }
  59195. _this.executeNext();
  59196. });
  59197. }
  59198. };
  59199. SimplificationQueue.prototype.getSimplifier = function (task) {
  59200. switch (task.simplificationType) {
  59201. case SimplificationType.QUADRATIC:
  59202. default:
  59203. return new QuadraticErrorSimplification(task.mesh);
  59204. }
  59205. };
  59206. return SimplificationQueue;
  59207. }());
  59208. BABYLON.SimplificationQueue = SimplificationQueue;
  59209. /**
  59210. * The implemented types of simplification.
  59211. * At the moment only Quadratic Error Decimation is implemented.
  59212. */
  59213. var SimplificationType;
  59214. (function (SimplificationType) {
  59215. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  59216. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  59217. var DecimationTriangle = (function () {
  59218. function DecimationTriangle(vertices) {
  59219. this.vertices = vertices;
  59220. this.error = new Array(4);
  59221. this.deleted = false;
  59222. this.isDirty = false;
  59223. this.deletePending = false;
  59224. this.borderFactor = 0;
  59225. }
  59226. return DecimationTriangle;
  59227. }());
  59228. BABYLON.DecimationTriangle = DecimationTriangle;
  59229. var DecimationVertex = (function () {
  59230. function DecimationVertex(position, id) {
  59231. this.position = position;
  59232. this.id = id;
  59233. this.isBorder = true;
  59234. this.q = new QuadraticMatrix();
  59235. this.triangleCount = 0;
  59236. this.triangleStart = 0;
  59237. this.originalOffsets = [];
  59238. }
  59239. DecimationVertex.prototype.updatePosition = function (newPosition) {
  59240. this.position.copyFrom(newPosition);
  59241. };
  59242. return DecimationVertex;
  59243. }());
  59244. BABYLON.DecimationVertex = DecimationVertex;
  59245. var QuadraticMatrix = (function () {
  59246. function QuadraticMatrix(data) {
  59247. this.data = new Array(10);
  59248. for (var i = 0; i < 10; ++i) {
  59249. if (data && data[i]) {
  59250. this.data[i] = data[i];
  59251. }
  59252. else {
  59253. this.data[i] = 0;
  59254. }
  59255. }
  59256. }
  59257. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  59258. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  59259. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  59260. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  59261. return det;
  59262. };
  59263. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  59264. for (var i = 0; i < 10; ++i) {
  59265. this.data[i] += matrix.data[i];
  59266. }
  59267. };
  59268. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  59269. for (var i = 0; i < 10; ++i) {
  59270. this.data[i] += data[i];
  59271. }
  59272. };
  59273. QuadraticMatrix.prototype.add = function (matrix) {
  59274. var m = new QuadraticMatrix();
  59275. for (var i = 0; i < 10; ++i) {
  59276. m.data[i] = this.data[i] + matrix.data[i];
  59277. }
  59278. return m;
  59279. };
  59280. QuadraticMatrix.FromData = function (a, b, c, d) {
  59281. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  59282. };
  59283. //returning an array to avoid garbage collection
  59284. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  59285. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  59286. };
  59287. return QuadraticMatrix;
  59288. }());
  59289. BABYLON.QuadraticMatrix = QuadraticMatrix;
  59290. var Reference = (function () {
  59291. function Reference(vertexId, triangleId) {
  59292. this.vertexId = vertexId;
  59293. this.triangleId = triangleId;
  59294. }
  59295. return Reference;
  59296. }());
  59297. BABYLON.Reference = Reference;
  59298. /**
  59299. * An implementation of the Quadratic Error simplification algorithm.
  59300. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  59301. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  59302. * @author RaananW
  59303. */
  59304. var QuadraticErrorSimplification = (function () {
  59305. function QuadraticErrorSimplification(_mesh) {
  59306. this._mesh = _mesh;
  59307. this.initialized = false;
  59308. this.syncIterations = 5000;
  59309. this.aggressiveness = 7;
  59310. this.decimationIterations = 100;
  59311. this.boundingBoxEpsilon = BABYLON.Epsilon;
  59312. }
  59313. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  59314. var _this = this;
  59315. this.initDecimatedMesh();
  59316. //iterating through the submeshes array, one after the other.
  59317. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  59318. _this.initWithMesh(loop.index, function () {
  59319. _this.runDecimation(settings, loop.index, function () {
  59320. loop.executeNext();
  59321. });
  59322. }, settings.optimizeMesh);
  59323. }, function () {
  59324. setTimeout(function () {
  59325. successCallback(_this._reconstructedMesh);
  59326. }, 0);
  59327. });
  59328. };
  59329. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  59330. var _this = this;
  59331. var gCount = 0;
  59332. triangle.vertices.forEach(function (vertex) {
  59333. var count = 0;
  59334. var vPos = vertex.position;
  59335. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  59336. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  59337. ++count;
  59338. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  59339. ++count;
  59340. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  59341. ++count;
  59342. if (count > 1) {
  59343. ++gCount;
  59344. }
  59345. ;
  59346. });
  59347. if (gCount > 1) {
  59348. console.log(triangle, gCount);
  59349. }
  59350. return gCount > 1;
  59351. };
  59352. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  59353. var _this = this;
  59354. var targetCount = ~~(this.triangles.length * settings.quality);
  59355. var deletedTriangles = 0;
  59356. var triangleCount = this.triangles.length;
  59357. var iterationFunction = function (iteration, callback) {
  59358. setTimeout(function () {
  59359. if (iteration % 5 === 0) {
  59360. _this.updateMesh(iteration === 0);
  59361. }
  59362. for (var i = 0; i < _this.triangles.length; ++i) {
  59363. _this.triangles[i].isDirty = false;
  59364. }
  59365. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  59366. var trianglesIterator = function (i) {
  59367. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  59368. var t = _this.triangles[tIdx];
  59369. if (!t)
  59370. return;
  59371. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  59372. return;
  59373. }
  59374. for (var j = 0; j < 3; ++j) {
  59375. if (t.error[j] < threshold) {
  59376. var deleted0 = [];
  59377. var deleted1 = [];
  59378. var v0 = t.vertices[j];
  59379. var v1 = t.vertices[(j + 1) % 3];
  59380. if (v0.isBorder || v1.isBorder)
  59381. continue;
  59382. var p = BABYLON.Vector3.Zero();
  59383. var n = BABYLON.Vector3.Zero();
  59384. var uv = BABYLON.Vector2.Zero();
  59385. var color = new BABYLON.Color4(0, 0, 0, 1);
  59386. _this.calculateError(v0, v1, p, n, uv, color);
  59387. var delTr = [];
  59388. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  59389. continue;
  59390. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  59391. continue;
  59392. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  59393. continue;
  59394. var uniqueArray = [];
  59395. delTr.forEach(function (deletedT) {
  59396. if (uniqueArray.indexOf(deletedT) === -1) {
  59397. deletedT.deletePending = true;
  59398. uniqueArray.push(deletedT);
  59399. }
  59400. });
  59401. if (uniqueArray.length % 2 !== 0) {
  59402. continue;
  59403. }
  59404. v0.q = v1.q.add(v0.q);
  59405. v0.updatePosition(p);
  59406. var tStart = _this.references.length;
  59407. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  59408. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  59409. var tCount = _this.references.length - tStart;
  59410. if (tCount <= v0.triangleCount) {
  59411. if (tCount) {
  59412. for (var c = 0; c < tCount; c++) {
  59413. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  59414. }
  59415. }
  59416. }
  59417. else {
  59418. v0.triangleStart = tStart;
  59419. }
  59420. v0.triangleCount = tCount;
  59421. break;
  59422. }
  59423. }
  59424. };
  59425. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  59426. }, 0);
  59427. };
  59428. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  59429. if (triangleCount - deletedTriangles <= targetCount)
  59430. loop.breakLoop();
  59431. else {
  59432. iterationFunction(loop.index, function () {
  59433. loop.executeNext();
  59434. });
  59435. }
  59436. }, function () {
  59437. setTimeout(function () {
  59438. //reconstruct this part of the mesh
  59439. _this.reconstructMesh(submeshIndex);
  59440. successCallback();
  59441. }, 0);
  59442. });
  59443. };
  59444. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  59445. var _this = this;
  59446. this.vertices = [];
  59447. this.triangles = [];
  59448. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  59449. var indices = this._mesh.getIndices();
  59450. var submesh = this._mesh.subMeshes[submeshIndex];
  59451. var findInVertices = function (positionToSearch) {
  59452. if (optimizeMesh) {
  59453. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  59454. if (_this.vertices[ii].position.equals(positionToSearch)) {
  59455. return _this.vertices[ii];
  59456. }
  59457. }
  59458. }
  59459. return null;
  59460. };
  59461. var vertexReferences = [];
  59462. var vertexInit = function (i) {
  59463. var offset = i + submesh.verticesStart;
  59464. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  59465. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  59466. vertex.originalOffsets.push(offset);
  59467. if (vertex.id === _this.vertices.length) {
  59468. _this.vertices.push(vertex);
  59469. }
  59470. vertexReferences.push(vertex.id);
  59471. };
  59472. //var totalVertices = mesh.getTotalVertices();
  59473. var totalVertices = submesh.verticesCount;
  59474. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  59475. var indicesInit = function (i) {
  59476. var offset = (submesh.indexStart / 3) + i;
  59477. var pos = (offset * 3);
  59478. var i0 = indices[pos + 0];
  59479. var i1 = indices[pos + 1];
  59480. var i2 = indices[pos + 2];
  59481. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  59482. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  59483. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  59484. var triangle = new DecimationTriangle([v0, v1, v2]);
  59485. triangle.originalOffset = pos;
  59486. _this.triangles.push(triangle);
  59487. };
  59488. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  59489. _this.init(callback);
  59490. });
  59491. });
  59492. };
  59493. QuadraticErrorSimplification.prototype.init = function (callback) {
  59494. var _this = this;
  59495. var triangleInit1 = function (i) {
  59496. var t = _this.triangles[i];
  59497. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  59498. for (var j = 0; j < 3; j++) {
  59499. 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))));
  59500. }
  59501. };
  59502. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  59503. var triangleInit2 = function (i) {
  59504. var t = _this.triangles[i];
  59505. for (var j = 0; j < 3; ++j) {
  59506. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  59507. }
  59508. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  59509. };
  59510. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  59511. _this.initialized = true;
  59512. callback();
  59513. });
  59514. });
  59515. };
  59516. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  59517. var newTriangles = [];
  59518. var i;
  59519. for (i = 0; i < this.vertices.length; ++i) {
  59520. this.vertices[i].triangleCount = 0;
  59521. }
  59522. var t;
  59523. var j;
  59524. for (i = 0; i < this.triangles.length; ++i) {
  59525. if (!this.triangles[i].deleted) {
  59526. t = this.triangles[i];
  59527. for (j = 0; j < 3; ++j) {
  59528. t.vertices[j].triangleCount = 1;
  59529. }
  59530. newTriangles.push(t);
  59531. }
  59532. }
  59533. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  59534. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  59535. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  59536. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  59537. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  59538. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  59539. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  59540. var vertexCount = 0;
  59541. for (i = 0; i < this.vertices.length; ++i) {
  59542. var vertex = this.vertices[i];
  59543. vertex.id = vertexCount;
  59544. if (vertex.triangleCount) {
  59545. vertex.originalOffsets.forEach(function (originalOffset) {
  59546. newPositionData.push(vertex.position.x);
  59547. newPositionData.push(vertex.position.y);
  59548. newPositionData.push(vertex.position.z);
  59549. newNormalData.push(normalData[originalOffset * 3]);
  59550. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  59551. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  59552. if (uvs && uvs.length) {
  59553. newUVsData.push(uvs[(originalOffset * 2)]);
  59554. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  59555. }
  59556. else if (colorsData && colorsData.length) {
  59557. newColorsData.push(colorsData[(originalOffset * 4)]);
  59558. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  59559. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  59560. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  59561. }
  59562. ++vertexCount;
  59563. });
  59564. }
  59565. }
  59566. var startingIndex = this._reconstructedMesh.getTotalIndices();
  59567. var startingVertex = this._reconstructedMesh.getTotalVertices();
  59568. var submeshesArray = this._reconstructedMesh.subMeshes;
  59569. this._reconstructedMesh.subMeshes = [];
  59570. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  59571. var originalIndices = this._mesh.getIndices();
  59572. for (i = 0; i < newTriangles.length; ++i) {
  59573. t = newTriangles[i]; //now get the new referencing point for each vertex
  59574. [0, 1, 2].forEach(function (idx) {
  59575. var id = originalIndices[t.originalOffset + idx];
  59576. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  59577. if (offset < 0)
  59578. offset = 0;
  59579. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  59580. });
  59581. }
  59582. //overwriting the old vertex buffers and indices.
  59583. this._reconstructedMesh.setIndices(newIndicesArray);
  59584. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  59585. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  59586. if (newUVsData.length > 0)
  59587. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  59588. if (newColorsData.length > 0)
  59589. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  59590. //create submesh
  59591. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  59592. if (submeshIndex > 0) {
  59593. this._reconstructedMesh.subMeshes = [];
  59594. submeshesArray.forEach(function (submesh) {
  59595. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  59596. });
  59597. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  59598. }
  59599. };
  59600. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  59601. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  59602. this._reconstructedMesh.material = this._mesh.material;
  59603. this._reconstructedMesh.parent = this._mesh.parent;
  59604. this._reconstructedMesh.isVisible = false;
  59605. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  59606. };
  59607. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  59608. for (var i = 0; i < vertex1.triangleCount; ++i) {
  59609. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  59610. if (t.deleted)
  59611. continue;
  59612. var s = this.references[vertex1.triangleStart + i].vertexId;
  59613. var v1 = t.vertices[(s + 1) % 3];
  59614. var v2 = t.vertices[(s + 2) % 3];
  59615. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  59616. deletedArray[i] = true;
  59617. delTr.push(t);
  59618. continue;
  59619. }
  59620. var d1 = v1.position.subtract(point);
  59621. d1 = d1.normalize();
  59622. var d2 = v2.position.subtract(point);
  59623. d2 = d2.normalize();
  59624. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  59625. return true;
  59626. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  59627. deletedArray[i] = false;
  59628. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  59629. return true;
  59630. }
  59631. return false;
  59632. };
  59633. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  59634. var newDeleted = deletedTriangles;
  59635. for (var i = 0; i < vertex.triangleCount; ++i) {
  59636. var ref = this.references[vertex.triangleStart + i];
  59637. var t = this.triangles[ref.triangleId];
  59638. if (t.deleted)
  59639. continue;
  59640. if (deletedArray[i] && t.deletePending) {
  59641. t.deleted = true;
  59642. newDeleted++;
  59643. continue;
  59644. }
  59645. t.vertices[ref.vertexId] = origVertex;
  59646. t.isDirty = true;
  59647. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  59648. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  59649. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  59650. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  59651. this.references.push(ref);
  59652. }
  59653. return newDeleted;
  59654. };
  59655. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  59656. for (var i = 0; i < this.vertices.length; ++i) {
  59657. var vCount = [];
  59658. var vId = [];
  59659. var v = this.vertices[i];
  59660. var j;
  59661. for (j = 0; j < v.triangleCount; ++j) {
  59662. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  59663. for (var ii = 0; ii < 3; ii++) {
  59664. var ofs = 0;
  59665. var vv = triangle.vertices[ii];
  59666. while (ofs < vCount.length) {
  59667. if (vId[ofs] === vv.id)
  59668. break;
  59669. ++ofs;
  59670. }
  59671. if (ofs === vCount.length) {
  59672. vCount.push(1);
  59673. vId.push(vv.id);
  59674. }
  59675. else {
  59676. vCount[ofs]++;
  59677. }
  59678. }
  59679. }
  59680. for (j = 0; j < vCount.length; ++j) {
  59681. if (vCount[j] === 1) {
  59682. this.vertices[vId[j]].isBorder = true;
  59683. }
  59684. else {
  59685. this.vertices[vId[j]].isBorder = false;
  59686. }
  59687. }
  59688. }
  59689. };
  59690. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  59691. if (identifyBorders === void 0) { identifyBorders = false; }
  59692. var i;
  59693. if (!identifyBorders) {
  59694. var newTrianglesVector = [];
  59695. for (i = 0; i < this.triangles.length; ++i) {
  59696. if (!this.triangles[i].deleted) {
  59697. newTrianglesVector.push(this.triangles[i]);
  59698. }
  59699. }
  59700. this.triangles = newTrianglesVector;
  59701. }
  59702. for (i = 0; i < this.vertices.length; ++i) {
  59703. this.vertices[i].triangleCount = 0;
  59704. this.vertices[i].triangleStart = 0;
  59705. }
  59706. var t;
  59707. var j;
  59708. var v;
  59709. for (i = 0; i < this.triangles.length; ++i) {
  59710. t = this.triangles[i];
  59711. for (j = 0; j < 3; ++j) {
  59712. v = t.vertices[j];
  59713. v.triangleCount++;
  59714. }
  59715. }
  59716. var tStart = 0;
  59717. for (i = 0; i < this.vertices.length; ++i) {
  59718. this.vertices[i].triangleStart = tStart;
  59719. tStart += this.vertices[i].triangleCount;
  59720. this.vertices[i].triangleCount = 0;
  59721. }
  59722. var newReferences = new Array(this.triangles.length * 3);
  59723. for (i = 0; i < this.triangles.length; ++i) {
  59724. t = this.triangles[i];
  59725. for (j = 0; j < 3; ++j) {
  59726. v = t.vertices[j];
  59727. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  59728. v.triangleCount++;
  59729. }
  59730. }
  59731. this.references = newReferences;
  59732. if (identifyBorders) {
  59733. this.identifyBorder();
  59734. }
  59735. };
  59736. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  59737. var x = point.x;
  59738. var y = point.y;
  59739. var z = point.z;
  59740. 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
  59741. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  59742. };
  59743. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  59744. var q = vertex1.q.add(vertex2.q);
  59745. var border = vertex1.isBorder && vertex2.isBorder;
  59746. var error = 0;
  59747. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  59748. if (qDet !== 0 && !border) {
  59749. if (!pointResult) {
  59750. pointResult = BABYLON.Vector3.Zero();
  59751. }
  59752. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  59753. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  59754. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  59755. error = this.vertexError(q, pointResult);
  59756. }
  59757. else {
  59758. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  59759. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  59760. var error1 = this.vertexError(q, vertex1.position);
  59761. var error2 = this.vertexError(q, vertex2.position);
  59762. var error3 = this.vertexError(q, p3);
  59763. error = Math.min(error1, error2, error3);
  59764. if (error === error1) {
  59765. if (pointResult) {
  59766. pointResult.copyFrom(vertex1.position);
  59767. }
  59768. }
  59769. else if (error === error2) {
  59770. if (pointResult) {
  59771. pointResult.copyFrom(vertex2.position);
  59772. }
  59773. }
  59774. else {
  59775. if (pointResult) {
  59776. pointResult.copyFrom(p3);
  59777. }
  59778. }
  59779. }
  59780. return error;
  59781. };
  59782. return QuadraticErrorSimplification;
  59783. }());
  59784. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  59785. })(BABYLON || (BABYLON = {}));
  59786. //# sourceMappingURL=babylon.meshSimplification.js.map
  59787. var BABYLON;
  59788. (function (BABYLON) {
  59789. var Internals;
  59790. (function (Internals) {
  59791. var MeshLODLevel = (function () {
  59792. function MeshLODLevel(distance, mesh) {
  59793. this.distance = distance;
  59794. this.mesh = mesh;
  59795. }
  59796. return MeshLODLevel;
  59797. }());
  59798. Internals.MeshLODLevel = MeshLODLevel;
  59799. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  59800. })(BABYLON || (BABYLON = {}));
  59801. //# sourceMappingURL=babylon.meshLODLevel.js.map
  59802. var BABYLON;
  59803. (function (BABYLON) {
  59804. // Standard optimizations
  59805. var SceneOptimization = (function () {
  59806. function SceneOptimization(priority) {
  59807. if (priority === void 0) { priority = 0; }
  59808. this.priority = priority;
  59809. this.apply = function (scene) {
  59810. return true; // Return true if everything that can be done was applied
  59811. };
  59812. }
  59813. return SceneOptimization;
  59814. }());
  59815. BABYLON.SceneOptimization = SceneOptimization;
  59816. var TextureOptimization = (function (_super) {
  59817. __extends(TextureOptimization, _super);
  59818. function TextureOptimization(priority, maximumSize) {
  59819. if (priority === void 0) { priority = 0; }
  59820. if (maximumSize === void 0) { maximumSize = 1024; }
  59821. var _this = _super.call(this, priority) || this;
  59822. _this.priority = priority;
  59823. _this.maximumSize = maximumSize;
  59824. _this.apply = function (scene) {
  59825. var allDone = true;
  59826. for (var index = 0; index < scene.textures.length; index++) {
  59827. var texture = scene.textures[index];
  59828. if (!texture.canRescale) {
  59829. continue;
  59830. }
  59831. var currentSize = texture.getSize();
  59832. var maxDimension = Math.max(currentSize.width, currentSize.height);
  59833. if (maxDimension > _this.maximumSize) {
  59834. texture.scale(0.5);
  59835. allDone = false;
  59836. }
  59837. }
  59838. return allDone;
  59839. };
  59840. return _this;
  59841. }
  59842. return TextureOptimization;
  59843. }(SceneOptimization));
  59844. BABYLON.TextureOptimization = TextureOptimization;
  59845. var HardwareScalingOptimization = (function (_super) {
  59846. __extends(HardwareScalingOptimization, _super);
  59847. function HardwareScalingOptimization(priority, maximumScale) {
  59848. if (priority === void 0) { priority = 0; }
  59849. if (maximumScale === void 0) { maximumScale = 2; }
  59850. var _this = _super.call(this, priority) || this;
  59851. _this.priority = priority;
  59852. _this.maximumScale = maximumScale;
  59853. _this._currentScale = 1;
  59854. _this.apply = function (scene) {
  59855. _this._currentScale++;
  59856. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  59857. return _this._currentScale >= _this.maximumScale;
  59858. };
  59859. return _this;
  59860. }
  59861. return HardwareScalingOptimization;
  59862. }(SceneOptimization));
  59863. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  59864. var ShadowsOptimization = (function (_super) {
  59865. __extends(ShadowsOptimization, _super);
  59866. function ShadowsOptimization() {
  59867. var _this = _super !== null && _super.apply(this, arguments) || this;
  59868. _this.apply = function (scene) {
  59869. scene.shadowsEnabled = false;
  59870. return true;
  59871. };
  59872. return _this;
  59873. }
  59874. return ShadowsOptimization;
  59875. }(SceneOptimization));
  59876. BABYLON.ShadowsOptimization = ShadowsOptimization;
  59877. var PostProcessesOptimization = (function (_super) {
  59878. __extends(PostProcessesOptimization, _super);
  59879. function PostProcessesOptimization() {
  59880. var _this = _super !== null && _super.apply(this, arguments) || this;
  59881. _this.apply = function (scene) {
  59882. scene.postProcessesEnabled = false;
  59883. return true;
  59884. };
  59885. return _this;
  59886. }
  59887. return PostProcessesOptimization;
  59888. }(SceneOptimization));
  59889. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  59890. var LensFlaresOptimization = (function (_super) {
  59891. __extends(LensFlaresOptimization, _super);
  59892. function LensFlaresOptimization() {
  59893. var _this = _super !== null && _super.apply(this, arguments) || this;
  59894. _this.apply = function (scene) {
  59895. scene.lensFlaresEnabled = false;
  59896. return true;
  59897. };
  59898. return _this;
  59899. }
  59900. return LensFlaresOptimization;
  59901. }(SceneOptimization));
  59902. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  59903. var ParticlesOptimization = (function (_super) {
  59904. __extends(ParticlesOptimization, _super);
  59905. function ParticlesOptimization() {
  59906. var _this = _super !== null && _super.apply(this, arguments) || this;
  59907. _this.apply = function (scene) {
  59908. scene.particlesEnabled = false;
  59909. return true;
  59910. };
  59911. return _this;
  59912. }
  59913. return ParticlesOptimization;
  59914. }(SceneOptimization));
  59915. BABYLON.ParticlesOptimization = ParticlesOptimization;
  59916. var RenderTargetsOptimization = (function (_super) {
  59917. __extends(RenderTargetsOptimization, _super);
  59918. function RenderTargetsOptimization() {
  59919. var _this = _super !== null && _super.apply(this, arguments) || this;
  59920. _this.apply = function (scene) {
  59921. scene.renderTargetsEnabled = false;
  59922. return true;
  59923. };
  59924. return _this;
  59925. }
  59926. return RenderTargetsOptimization;
  59927. }(SceneOptimization));
  59928. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  59929. var MergeMeshesOptimization = (function (_super) {
  59930. __extends(MergeMeshesOptimization, _super);
  59931. function MergeMeshesOptimization() {
  59932. var _this = _super !== null && _super.apply(this, arguments) || this;
  59933. _this._canBeMerged = function (abstractMesh) {
  59934. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  59935. return false;
  59936. }
  59937. var mesh = abstractMesh;
  59938. if (!mesh.isVisible || !mesh.isEnabled()) {
  59939. return false;
  59940. }
  59941. if (mesh.instances.length > 0) {
  59942. return false;
  59943. }
  59944. if (mesh.skeleton || mesh.hasLODLevels) {
  59945. return false;
  59946. }
  59947. if (mesh.parent) {
  59948. return false;
  59949. }
  59950. return true;
  59951. };
  59952. _this.apply = function (scene, updateSelectionTree) {
  59953. var globalPool = scene.meshes.slice(0);
  59954. var globalLength = globalPool.length;
  59955. for (var index = 0; index < globalLength; index++) {
  59956. var currentPool = new Array();
  59957. var current = globalPool[index];
  59958. // Checks
  59959. if (!_this._canBeMerged(current)) {
  59960. continue;
  59961. }
  59962. currentPool.push(current);
  59963. // Find compatible meshes
  59964. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  59965. var otherMesh = globalPool[subIndex];
  59966. if (!_this._canBeMerged(otherMesh)) {
  59967. continue;
  59968. }
  59969. if (otherMesh.material !== current.material) {
  59970. continue;
  59971. }
  59972. if (otherMesh.checkCollisions !== current.checkCollisions) {
  59973. continue;
  59974. }
  59975. currentPool.push(otherMesh);
  59976. globalLength--;
  59977. globalPool.splice(subIndex, 1);
  59978. subIndex--;
  59979. }
  59980. if (currentPool.length < 2) {
  59981. continue;
  59982. }
  59983. // Merge meshes
  59984. BABYLON.Mesh.MergeMeshes(currentPool);
  59985. }
  59986. if (updateSelectionTree != undefined) {
  59987. if (updateSelectionTree) {
  59988. scene.createOrUpdateSelectionOctree();
  59989. }
  59990. }
  59991. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  59992. scene.createOrUpdateSelectionOctree();
  59993. }
  59994. return true;
  59995. };
  59996. return _this;
  59997. }
  59998. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  59999. get: function () {
  60000. return MergeMeshesOptimization._UpdateSelectionTree;
  60001. },
  60002. set: function (value) {
  60003. MergeMeshesOptimization._UpdateSelectionTree = value;
  60004. },
  60005. enumerable: true,
  60006. configurable: true
  60007. });
  60008. return MergeMeshesOptimization;
  60009. }(SceneOptimization));
  60010. MergeMeshesOptimization._UpdateSelectionTree = false;
  60011. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  60012. // Options
  60013. var SceneOptimizerOptions = (function () {
  60014. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  60015. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  60016. if (trackerDuration === void 0) { trackerDuration = 2000; }
  60017. this.targetFrameRate = targetFrameRate;
  60018. this.trackerDuration = trackerDuration;
  60019. this.optimizations = new Array();
  60020. }
  60021. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  60022. var result = new SceneOptimizerOptions(targetFrameRate);
  60023. var priority = 0;
  60024. result.optimizations.push(new MergeMeshesOptimization(priority));
  60025. result.optimizations.push(new ShadowsOptimization(priority));
  60026. result.optimizations.push(new LensFlaresOptimization(priority));
  60027. // Next priority
  60028. priority++;
  60029. result.optimizations.push(new PostProcessesOptimization(priority));
  60030. result.optimizations.push(new ParticlesOptimization(priority));
  60031. // Next priority
  60032. priority++;
  60033. result.optimizations.push(new TextureOptimization(priority, 1024));
  60034. return result;
  60035. };
  60036. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  60037. var result = new SceneOptimizerOptions(targetFrameRate);
  60038. var priority = 0;
  60039. result.optimizations.push(new MergeMeshesOptimization(priority));
  60040. result.optimizations.push(new ShadowsOptimization(priority));
  60041. result.optimizations.push(new LensFlaresOptimization(priority));
  60042. // Next priority
  60043. priority++;
  60044. result.optimizations.push(new PostProcessesOptimization(priority));
  60045. result.optimizations.push(new ParticlesOptimization(priority));
  60046. // Next priority
  60047. priority++;
  60048. result.optimizations.push(new TextureOptimization(priority, 512));
  60049. // Next priority
  60050. priority++;
  60051. result.optimizations.push(new RenderTargetsOptimization(priority));
  60052. // Next priority
  60053. priority++;
  60054. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  60055. return result;
  60056. };
  60057. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  60058. var result = new SceneOptimizerOptions(targetFrameRate);
  60059. var priority = 0;
  60060. result.optimizations.push(new MergeMeshesOptimization(priority));
  60061. result.optimizations.push(new ShadowsOptimization(priority));
  60062. result.optimizations.push(new LensFlaresOptimization(priority));
  60063. // Next priority
  60064. priority++;
  60065. result.optimizations.push(new PostProcessesOptimization(priority));
  60066. result.optimizations.push(new ParticlesOptimization(priority));
  60067. // Next priority
  60068. priority++;
  60069. result.optimizations.push(new TextureOptimization(priority, 256));
  60070. // Next priority
  60071. priority++;
  60072. result.optimizations.push(new RenderTargetsOptimization(priority));
  60073. // Next priority
  60074. priority++;
  60075. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  60076. return result;
  60077. };
  60078. return SceneOptimizerOptions;
  60079. }());
  60080. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  60081. // Scene optimizer tool
  60082. var SceneOptimizer = (function () {
  60083. function SceneOptimizer() {
  60084. }
  60085. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  60086. // TODO: add an epsilon
  60087. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  60088. if (onSuccess) {
  60089. onSuccess();
  60090. }
  60091. return;
  60092. }
  60093. // Apply current level of optimizations
  60094. var allDone = true;
  60095. var noOptimizationApplied = true;
  60096. for (var index = 0; index < options.optimizations.length; index++) {
  60097. var optimization = options.optimizations[index];
  60098. if (optimization.priority === currentPriorityLevel) {
  60099. noOptimizationApplied = false;
  60100. allDone = allDone && optimization.apply(scene);
  60101. }
  60102. }
  60103. // If no optimization was applied, this is a failure :(
  60104. if (noOptimizationApplied) {
  60105. if (onFailure) {
  60106. onFailure();
  60107. }
  60108. return;
  60109. }
  60110. // If all optimizations were done, move to next level
  60111. if (allDone) {
  60112. currentPriorityLevel++;
  60113. }
  60114. // Let's the system running for a specific amount of time before checking FPS
  60115. scene.executeWhenReady(function () {
  60116. setTimeout(function () {
  60117. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  60118. }, options.trackerDuration);
  60119. });
  60120. };
  60121. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  60122. if (!options) {
  60123. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  60124. }
  60125. // Let's the system running for a specific amount of time before checking FPS
  60126. scene.executeWhenReady(function () {
  60127. setTimeout(function () {
  60128. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  60129. }, options.trackerDuration);
  60130. });
  60131. };
  60132. return SceneOptimizer;
  60133. }());
  60134. BABYLON.SceneOptimizer = SceneOptimizer;
  60135. })(BABYLON || (BABYLON = {}));
  60136. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  60137. var BABYLON;
  60138. (function (BABYLON) {
  60139. var OutlineRenderer = (function () {
  60140. function OutlineRenderer(scene) {
  60141. this._scene = scene;
  60142. }
  60143. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  60144. var _this = this;
  60145. if (useOverlay === void 0) { useOverlay = false; }
  60146. var scene = this._scene;
  60147. var engine = this._scene.getEngine();
  60148. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  60149. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  60150. return;
  60151. }
  60152. var mesh = subMesh.getRenderingMesh();
  60153. var material = subMesh.getMaterial();
  60154. engine.enableEffect(this._effect);
  60155. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  60156. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  60157. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  60158. // Bones
  60159. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  60160. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  60161. }
  60162. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  60163. // Alpha test
  60164. if (material && material.needAlphaTesting()) {
  60165. var alphaTexture = material.getAlphaTestTexture();
  60166. this._effect.setTexture("diffuseSampler", alphaTexture);
  60167. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  60168. }
  60169. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  60170. };
  60171. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  60172. var defines = [];
  60173. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  60174. var mesh = subMesh.getMesh();
  60175. var material = subMesh.getMaterial();
  60176. // Alpha test
  60177. if (material && material.needAlphaTesting()) {
  60178. defines.push("#define ALPHATEST");
  60179. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  60180. attribs.push(BABYLON.VertexBuffer.UVKind);
  60181. defines.push("#define UV1");
  60182. }
  60183. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  60184. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  60185. defines.push("#define UV2");
  60186. }
  60187. }
  60188. // Bones
  60189. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  60190. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  60191. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  60192. if (mesh.numBoneInfluencers > 4) {
  60193. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  60194. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  60195. }
  60196. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  60197. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  60198. }
  60199. else {
  60200. defines.push("#define NUM_BONE_INFLUENCERS 0");
  60201. }
  60202. // Instances
  60203. if (useInstances) {
  60204. defines.push("#define INSTANCES");
  60205. attribs.push("world0");
  60206. attribs.push("world1");
  60207. attribs.push("world2");
  60208. attribs.push("world3");
  60209. }
  60210. // Get correct effect
  60211. var join = defines.join("\n");
  60212. if (this._cachedDefines !== join) {
  60213. this._cachedDefines = join;
  60214. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  60215. }
  60216. return this._effect.isReady();
  60217. };
  60218. return OutlineRenderer;
  60219. }());
  60220. BABYLON.OutlineRenderer = OutlineRenderer;
  60221. })(BABYLON || (BABYLON = {}));
  60222. //# sourceMappingURL=babylon.outlineRenderer.js.map
  60223. var BABYLON;
  60224. (function (BABYLON) {
  60225. var FaceAdjacencies = (function () {
  60226. function FaceAdjacencies() {
  60227. this.edges = new Array();
  60228. this.edgesConnectedCount = 0;
  60229. }
  60230. return FaceAdjacencies;
  60231. }());
  60232. var EdgesRenderer = (function () {
  60233. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  60234. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  60235. if (epsilon === void 0) { epsilon = 0.95; }
  60236. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  60237. this.edgesWidthScalerForOrthographic = 1000.0;
  60238. this.edgesWidthScalerForPerspective = 50.0;
  60239. this._linesPositions = new Array();
  60240. this._linesNormals = new Array();
  60241. this._linesIndices = new Array();
  60242. this._buffers = {};
  60243. this._checkVerticesInsteadOfIndices = false;
  60244. this._source = source;
  60245. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  60246. this._epsilon = epsilon;
  60247. this._prepareRessources();
  60248. this._generateEdgesLines();
  60249. }
  60250. EdgesRenderer.prototype._prepareRessources = function () {
  60251. if (this._lineShader) {
  60252. return;
  60253. }
  60254. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  60255. attributes: ["position", "normal"],
  60256. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  60257. });
  60258. this._lineShader.disableDepthWrite = true;
  60259. this._lineShader.backFaceCulling = false;
  60260. };
  60261. EdgesRenderer.prototype.dispose = function () {
  60262. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  60263. if (buffer) {
  60264. buffer.dispose();
  60265. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  60266. }
  60267. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  60268. if (buffer) {
  60269. buffer.dispose();
  60270. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  60271. }
  60272. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  60273. this._lineShader.dispose();
  60274. };
  60275. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  60276. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  60277. return 0;
  60278. }
  60279. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  60280. return 1;
  60281. }
  60282. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  60283. return 2;
  60284. }
  60285. return -1;
  60286. };
  60287. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  60288. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  60289. return 0;
  60290. }
  60291. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  60292. return 1;
  60293. }
  60294. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  60295. return 2;
  60296. }
  60297. return -1;
  60298. };
  60299. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  60300. var needToCreateLine;
  60301. if (edge === undefined) {
  60302. needToCreateLine = true;
  60303. }
  60304. else {
  60305. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  60306. needToCreateLine = dotProduct < this._epsilon;
  60307. }
  60308. if (needToCreateLine) {
  60309. var offset = this._linesPositions.length / 3;
  60310. var normal = p0.subtract(p1);
  60311. normal.normalize();
  60312. // Positions
  60313. this._linesPositions.push(p0.x);
  60314. this._linesPositions.push(p0.y);
  60315. this._linesPositions.push(p0.z);
  60316. this._linesPositions.push(p0.x);
  60317. this._linesPositions.push(p0.y);
  60318. this._linesPositions.push(p0.z);
  60319. this._linesPositions.push(p1.x);
  60320. this._linesPositions.push(p1.y);
  60321. this._linesPositions.push(p1.z);
  60322. this._linesPositions.push(p1.x);
  60323. this._linesPositions.push(p1.y);
  60324. this._linesPositions.push(p1.z);
  60325. // Normals
  60326. this._linesNormals.push(p1.x);
  60327. this._linesNormals.push(p1.y);
  60328. this._linesNormals.push(p1.z);
  60329. this._linesNormals.push(-1);
  60330. this._linesNormals.push(p1.x);
  60331. this._linesNormals.push(p1.y);
  60332. this._linesNormals.push(p1.z);
  60333. this._linesNormals.push(1);
  60334. this._linesNormals.push(p0.x);
  60335. this._linesNormals.push(p0.y);
  60336. this._linesNormals.push(p0.z);
  60337. this._linesNormals.push(-1);
  60338. this._linesNormals.push(p0.x);
  60339. this._linesNormals.push(p0.y);
  60340. this._linesNormals.push(p0.z);
  60341. this._linesNormals.push(1);
  60342. // Indices
  60343. this._linesIndices.push(offset);
  60344. this._linesIndices.push(offset + 1);
  60345. this._linesIndices.push(offset + 2);
  60346. this._linesIndices.push(offset);
  60347. this._linesIndices.push(offset + 2);
  60348. this._linesIndices.push(offset + 3);
  60349. }
  60350. };
  60351. EdgesRenderer.prototype._generateEdgesLines = function () {
  60352. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60353. var indices = this._source.getIndices();
  60354. // First let's find adjacencies
  60355. var adjacencies = new Array();
  60356. var faceNormals = new Array();
  60357. var index;
  60358. var faceAdjacencies;
  60359. // Prepare faces
  60360. for (index = 0; index < indices.length; index += 3) {
  60361. faceAdjacencies = new FaceAdjacencies();
  60362. var p0Index = indices[index];
  60363. var p1Index = indices[index + 1];
  60364. var p2Index = indices[index + 2];
  60365. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  60366. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  60367. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  60368. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  60369. faceNormal.normalize();
  60370. faceNormals.push(faceNormal);
  60371. adjacencies.push(faceAdjacencies);
  60372. }
  60373. // Scan
  60374. for (index = 0; index < adjacencies.length; index++) {
  60375. faceAdjacencies = adjacencies[index];
  60376. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  60377. var otherFaceAdjacencies = adjacencies[otherIndex];
  60378. if (faceAdjacencies.edgesConnectedCount === 3) {
  60379. break;
  60380. }
  60381. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  60382. continue;
  60383. }
  60384. var otherP0 = indices[otherIndex * 3];
  60385. var otherP1 = indices[otherIndex * 3 + 1];
  60386. var otherP2 = indices[otherIndex * 3 + 2];
  60387. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  60388. var otherEdgeIndex;
  60389. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  60390. continue;
  60391. }
  60392. switch (edgeIndex) {
  60393. case 0:
  60394. if (this._checkVerticesInsteadOfIndices) {
  60395. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  60396. }
  60397. else {
  60398. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  60399. }
  60400. break;
  60401. case 1:
  60402. if (this._checkVerticesInsteadOfIndices) {
  60403. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  60404. }
  60405. else {
  60406. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  60407. }
  60408. break;
  60409. case 2:
  60410. if (this._checkVerticesInsteadOfIndices) {
  60411. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  60412. }
  60413. else {
  60414. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  60415. }
  60416. break;
  60417. }
  60418. if (otherEdgeIndex === -1) {
  60419. continue;
  60420. }
  60421. faceAdjacencies.edges[edgeIndex] = otherIndex;
  60422. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  60423. faceAdjacencies.edgesConnectedCount++;
  60424. otherFaceAdjacencies.edgesConnectedCount++;
  60425. if (faceAdjacencies.edgesConnectedCount === 3) {
  60426. break;
  60427. }
  60428. }
  60429. }
  60430. }
  60431. // Create lines
  60432. for (index = 0; index < adjacencies.length; index++) {
  60433. // 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
  60434. var current = adjacencies[index];
  60435. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  60436. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  60437. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  60438. }
  60439. // Merge into a single mesh
  60440. var engine = this._source.getScene().getEngine();
  60441. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  60442. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  60443. this._ib = engine.createIndexBuffer(this._linesIndices);
  60444. this._indicesCount = this._linesIndices.length;
  60445. };
  60446. EdgesRenderer.prototype.render = function () {
  60447. if (!this._lineShader.isReady()) {
  60448. return;
  60449. }
  60450. var scene = this._source.getScene();
  60451. var engine = scene.getEngine();
  60452. this._lineShader._preBind();
  60453. // VBOs
  60454. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  60455. scene.resetCachedMaterial();
  60456. this._lineShader.setColor4("color", this._source.edgesColor);
  60457. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  60458. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  60459. }
  60460. else {
  60461. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  60462. }
  60463. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  60464. this._lineShader.bind(this._source.getWorldMatrix());
  60465. // Draw order
  60466. engine.draw(true, 0, this._indicesCount);
  60467. this._lineShader.unbind();
  60468. engine.setDepthWrite(true);
  60469. };
  60470. return EdgesRenderer;
  60471. }());
  60472. BABYLON.EdgesRenderer = EdgesRenderer;
  60473. })(BABYLON || (BABYLON = {}));
  60474. //# sourceMappingURL=babylon.edgesRenderer.js.map
  60475. /// <reference path="..\PostProcess\babylon.postProcess.ts" />
  60476. /// <reference path="..\Math\babylon.math.ts" />
  60477. var BABYLON;
  60478. (function (BABYLON) {
  60479. /**
  60480. * Special Glow Blur post process only blurring the alpha channel
  60481. * It enforces keeping the most luminous color in the color channel.
  60482. */
  60483. var GlowBlurPostProcess = (function (_super) {
  60484. __extends(GlowBlurPostProcess, _super);
  60485. function GlowBlurPostProcess(name, direction, blurWidth, options, camera, samplingMode, engine, reusable) {
  60486. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  60487. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  60488. _this.direction = direction;
  60489. _this.blurWidth = blurWidth;
  60490. _this.onApplyObservable.add(function (effect) {
  60491. effect.setFloat2("screenSize", _this.width, _this.height);
  60492. effect.setVector2("direction", _this.direction);
  60493. effect.setFloat("blurWidth", _this.blurWidth);
  60494. });
  60495. return _this;
  60496. }
  60497. return GlowBlurPostProcess;
  60498. }(BABYLON.PostProcess));
  60499. /**
  60500. * The highlight layer Helps adding a glow effect around a mesh.
  60501. *
  60502. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  60503. * glowy meshes to your scene.
  60504. *
  60505. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  60506. */
  60507. var HighlightLayer = (function () {
  60508. /**
  60509. * Instantiates a new highlight Layer and references it to the scene..
  60510. * @param name The name of the layer
  60511. * @param scene The scene to use the layer in
  60512. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  60513. */
  60514. function HighlightLayer(name, scene, options) {
  60515. this.name = name;
  60516. this._vertexBuffers = {};
  60517. this._mainTextureDesiredSize = { width: 0, height: 0 };
  60518. this._meshes = {};
  60519. this._maxSize = 0;
  60520. this._shouldRender = false;
  60521. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  60522. this._excludedMeshes = {};
  60523. /**
  60524. * Specifies whether or not the inner glow is ACTIVE in the layer.
  60525. */
  60526. this.innerGlow = true;
  60527. /**
  60528. * Specifies whether or not the outer glow is ACTIVE in the layer.
  60529. */
  60530. this.outerGlow = true;
  60531. /**
  60532. * Specifies wether the highlight layer is enabled or not.
  60533. */
  60534. this.isEnabled = true;
  60535. /**
  60536. * An event triggered when the highlight layer has been disposed.
  60537. * @type {BABYLON.Observable}
  60538. */
  60539. this.onDisposeObservable = new BABYLON.Observable();
  60540. /**
  60541. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  60542. * @type {BABYLON.Observable}
  60543. */
  60544. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  60545. /**
  60546. * An event triggered when the highlight layer is being blurred.
  60547. * @type {BABYLON.Observable}
  60548. */
  60549. this.onBeforeBlurObservable = new BABYLON.Observable();
  60550. /**
  60551. * An event triggered when the highlight layer has been blurred.
  60552. * @type {BABYLON.Observable}
  60553. */
  60554. this.onAfterBlurObservable = new BABYLON.Observable();
  60555. /**
  60556. * An event triggered when the glowing blurred texture is being merged in the scene.
  60557. * @type {BABYLON.Observable}
  60558. */
  60559. this.onBeforeComposeObservable = new BABYLON.Observable();
  60560. /**
  60561. * An event triggered when the glowing blurred texture has been merged in the scene.
  60562. * @type {BABYLON.Observable}
  60563. */
  60564. this.onAfterComposeObservable = new BABYLON.Observable();
  60565. /**
  60566. * An event triggered when the highlight layer changes its size.
  60567. * @type {BABYLON.Observable}
  60568. */
  60569. this.onSizeChangedObservable = new BABYLON.Observable();
  60570. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  60571. var engine = scene.getEngine();
  60572. this._engine = engine;
  60573. this._maxSize = this._engine.getCaps().maxTextureSize;
  60574. this._scene.highlightLayers.push(this);
  60575. // Warn on stencil.
  60576. if (!this._engine.isStencilEnable) {
  60577. 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 }");
  60578. }
  60579. // Adapt options
  60580. this._options = options || {
  60581. mainTextureRatio: 0.25,
  60582. blurTextureSizeRatio: 0.5,
  60583. blurHorizontalSize: 1,
  60584. blurVerticalSize: 1,
  60585. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE
  60586. };
  60587. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.25;
  60588. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 0.5;
  60589. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  60590. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  60591. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  60592. // VBO
  60593. var vertices = [];
  60594. vertices.push(1, 1);
  60595. vertices.push(-1, 1);
  60596. vertices.push(-1, -1);
  60597. vertices.push(1, -1);
  60598. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  60599. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  60600. // Indices
  60601. var indices = [];
  60602. indices.push(0);
  60603. indices.push(1);
  60604. indices.push(2);
  60605. indices.push(0);
  60606. indices.push(2);
  60607. indices.push(3);
  60608. this._indexBuffer = engine.createIndexBuffer(indices);
  60609. // Effect
  60610. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], "");
  60611. // Render target
  60612. this.setMainTextureSize();
  60613. // Create Textures and post processes
  60614. this.createTextureAndPostProcesses();
  60615. }
  60616. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  60617. /**
  60618. * Gets the horizontal size of the blur.
  60619. */
  60620. get: function () {
  60621. return this._horizontalBlurPostprocess.blurWidth;
  60622. },
  60623. /**
  60624. * Specifies the horizontal size of the blur.
  60625. */
  60626. set: function (value) {
  60627. this._horizontalBlurPostprocess.blurWidth = value;
  60628. },
  60629. enumerable: true,
  60630. configurable: true
  60631. });
  60632. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  60633. /**
  60634. * Gets the vertical size of the blur.
  60635. */
  60636. get: function () {
  60637. return this._verticalBlurPostprocess.blurWidth;
  60638. },
  60639. /**
  60640. * Specifies the vertical size of the blur.
  60641. */
  60642. set: function (value) {
  60643. this._verticalBlurPostprocess.blurWidth = value;
  60644. },
  60645. enumerable: true,
  60646. configurable: true
  60647. });
  60648. Object.defineProperty(HighlightLayer.prototype, "camera", {
  60649. /**
  60650. * Gets the camera attached to the layer.
  60651. */
  60652. get: function () {
  60653. return this._options.camera;
  60654. },
  60655. enumerable: true,
  60656. configurable: true
  60657. });
  60658. /**
  60659. * Creates the render target textures and post processes used in the highlight layer.
  60660. */
  60661. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  60662. var _this = this;
  60663. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  60664. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  60665. blurTextureWidth = BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize);
  60666. blurTextureHeight = BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize);
  60667. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  60668. width: this._mainTextureDesiredSize.width,
  60669. height: this._mainTextureDesiredSize.height
  60670. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  60671. this._mainTexture.activeCamera = this._options.camera;
  60672. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60673. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60674. this._mainTexture.anisotropicFilteringLevel = 1;
  60675. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  60676. this._mainTexture.renderParticles = false;
  60677. this._mainTexture.renderList = null;
  60678. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  60679. width: blurTextureWidth,
  60680. height: blurTextureHeight
  60681. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  60682. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60683. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60684. this._blurTexture.anisotropicFilteringLevel = 16;
  60685. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  60686. this._blurTexture.renderParticles = false;
  60687. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  60688. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  60689. effect.setTexture("textureSampler", _this._mainTexture);
  60690. });
  60691. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  60692. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  60693. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  60694. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  60695. });
  60696. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  60697. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  60698. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  60699. });
  60700. }
  60701. else {
  60702. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  60703. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  60704. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  60705. });
  60706. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  60707. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  60708. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  60709. });
  60710. }
  60711. this._mainTexture.onAfterUnbindObservable.add(function () {
  60712. _this.onBeforeBlurObservable.notifyObservers(_this);
  60713. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], _this._blurTexture.getInternalTexture());
  60714. _this.onAfterBlurObservable.notifyObservers(_this);
  60715. });
  60716. // Custom render function
  60717. var renderSubMesh = function (subMesh) {
  60718. var mesh = subMesh.getRenderingMesh();
  60719. var scene = _this._scene;
  60720. var engine = scene.getEngine();
  60721. // Culling
  60722. engine.setState(subMesh.getMaterial().backFaceCulling);
  60723. // Managing instances
  60724. var batch = mesh._getInstancesRenderList(subMesh._id);
  60725. if (batch.mustReturn) {
  60726. return;
  60727. }
  60728. // Excluded Mesh
  60729. if (_this._excludedMeshes[mesh.uniqueId]) {
  60730. return;
  60731. }
  60732. ;
  60733. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  60734. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  60735. var material = subMesh.getMaterial();
  60736. var emissiveTexture = null;
  60737. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  60738. emissiveTexture = material.emissiveTexture;
  60739. }
  60740. if (_this.isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  60741. engine.enableEffect(_this._glowMapGenerationEffect);
  60742. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  60743. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  60744. if (highlightLayerMesh) {
  60745. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  60746. }
  60747. else {
  60748. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  60749. }
  60750. // Alpha test
  60751. if (material && material.needAlphaTesting()) {
  60752. var alphaTexture = material.getAlphaTestTexture();
  60753. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  60754. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  60755. }
  60756. // Glow emissive only
  60757. if (emissiveTexture) {
  60758. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  60759. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  60760. }
  60761. // Bones
  60762. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  60763. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  60764. }
  60765. // Draw
  60766. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  60767. }
  60768. else {
  60769. // Need to reset refresh rate of the shadowMap
  60770. _this._mainTexture.resetRefreshCounter();
  60771. }
  60772. };
  60773. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  60774. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  60775. var index;
  60776. for (index = 0; index < opaqueSubMeshes.length; index++) {
  60777. renderSubMesh(opaqueSubMeshes.data[index]);
  60778. }
  60779. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  60780. renderSubMesh(alphaTestSubMeshes.data[index]);
  60781. }
  60782. for (index = 0; index < transparentSubMeshes.length; index++) {
  60783. renderSubMesh(transparentSubMeshes.data[index]);
  60784. }
  60785. };
  60786. this._mainTexture.onClearObservable.add(function (engine) {
  60787. engine.clear(HighlightLayer.neutralColor, true, true, true);
  60788. });
  60789. };
  60790. /**
  60791. * Checks for the readiness of the element composing the layer.
  60792. * @param subMesh the mesh to check for
  60793. * @param useInstances specify wether or not to use instances to render the mesh
  60794. * @param emissiveTexture the associated emissive texture used to generate the glow
  60795. * @return true if ready otherwise, false
  60796. */
  60797. HighlightLayer.prototype.isReady = function (subMesh, useInstances, emissiveTexture) {
  60798. if (!subMesh.getMaterial().isReady(subMesh.getMesh(), useInstances)) {
  60799. return false;
  60800. }
  60801. var defines = [];
  60802. var attribs = [BABYLON.VertexBuffer.PositionKind];
  60803. var mesh = subMesh.getMesh();
  60804. var material = subMesh.getMaterial();
  60805. var uv1 = false;
  60806. var uv2 = false;
  60807. // Alpha test
  60808. if (material && material.needAlphaTesting()) {
  60809. var alphaTexture = material.getAlphaTestTexture();
  60810. if (alphaTexture) {
  60811. defines.push("#define ALPHATEST");
  60812. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  60813. alphaTexture.coordinatesIndex === 1) {
  60814. defines.push("#define DIFFUSEUV2");
  60815. uv2 = true;
  60816. }
  60817. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  60818. defines.push("#define DIFFUSEUV1");
  60819. uv1 = true;
  60820. }
  60821. }
  60822. }
  60823. // Emissive
  60824. if (emissiveTexture) {
  60825. defines.push("#define EMISSIVE");
  60826. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  60827. emissiveTexture.coordinatesIndex === 1) {
  60828. defines.push("#define EMISSIVEUV2");
  60829. uv2 = true;
  60830. }
  60831. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  60832. defines.push("#define EMISSIVEUV1");
  60833. uv1 = true;
  60834. }
  60835. }
  60836. if (uv1) {
  60837. attribs.push(BABYLON.VertexBuffer.UVKind);
  60838. defines.push("#define UV1");
  60839. }
  60840. if (uv2) {
  60841. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  60842. defines.push("#define UV2");
  60843. }
  60844. // Bones
  60845. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  60846. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  60847. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  60848. if (mesh.numBoneInfluencers > 4) {
  60849. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  60850. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  60851. }
  60852. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  60853. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  60854. }
  60855. else {
  60856. defines.push("#define NUM_BONE_INFLUENCERS 0");
  60857. }
  60858. // Instances
  60859. if (useInstances) {
  60860. defines.push("#define INSTANCES");
  60861. attribs.push("world0");
  60862. attribs.push("world1");
  60863. attribs.push("world2");
  60864. attribs.push("world3");
  60865. }
  60866. // Get correct effect
  60867. var join = defines.join("\n");
  60868. if (this._cachedDefines !== join) {
  60869. this._cachedDefines = join;
  60870. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  60871. }
  60872. return this._glowMapGenerationEffect.isReady();
  60873. };
  60874. /**
  60875. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  60876. */
  60877. HighlightLayer.prototype.render = function () {
  60878. var currentEffect = this._glowMapMergeEffect;
  60879. // Check
  60880. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  60881. return;
  60882. var engine = this._scene.getEngine();
  60883. this.onBeforeComposeObservable.notifyObservers(this);
  60884. // Render
  60885. engine.enableEffect(currentEffect);
  60886. engine.setState(false);
  60887. // Cache
  60888. var previousStencilBuffer = engine.getStencilBuffer();
  60889. var previousStencilFunction = engine.getStencilFunction();
  60890. var previousStencilMask = engine.getStencilMask();
  60891. var previousAlphaMode = engine.getAlphaMode();
  60892. // Texture
  60893. currentEffect.setTexture("textureSampler", this._blurTexture);
  60894. // VBOs
  60895. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  60896. // Draw order
  60897. engine.setAlphaMode(this._options.alphaBlendingMode);
  60898. engine.setStencilMask(0x00);
  60899. engine.setStencilBuffer(true);
  60900. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  60901. if (this.outerGlow) {
  60902. currentEffect.setFloat("offset", 0);
  60903. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  60904. engine.draw(true, 0, 6);
  60905. }
  60906. if (this.innerGlow) {
  60907. currentEffect.setFloat("offset", 1);
  60908. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  60909. engine.draw(true, 0, 6);
  60910. }
  60911. // Restore Cache
  60912. engine.setStencilFunction(previousStencilFunction);
  60913. engine.setStencilMask(previousStencilMask);
  60914. engine.setAlphaMode(previousAlphaMode);
  60915. engine.setStencilBuffer(previousStencilBuffer);
  60916. this.onAfterComposeObservable.notifyObservers(this);
  60917. // Handle size changes.
  60918. var size = this._mainTexture.getSize();
  60919. this.setMainTextureSize();
  60920. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  60921. // Recreate RTT and post processes on size change.
  60922. this.onSizeChangedObservable.notifyObservers(this);
  60923. this.disposeTextureAndPostProcesses();
  60924. this.createTextureAndPostProcesses();
  60925. }
  60926. };
  60927. /**
  60928. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  60929. * @param mesh The mesh to exclude from the highlight layer
  60930. */
  60931. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  60932. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  60933. if (!meshExcluded) {
  60934. this._excludedMeshes[mesh.uniqueId] = {
  60935. mesh: mesh,
  60936. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  60937. mesh.getEngine().setStencilBuffer(false);
  60938. }),
  60939. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  60940. mesh.getEngine().setStencilBuffer(true);
  60941. }),
  60942. };
  60943. }
  60944. };
  60945. /**
  60946. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  60947. * @param mesh The mesh to highlight
  60948. */
  60949. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  60950. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  60951. if (meshExcluded) {
  60952. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  60953. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  60954. }
  60955. this._excludedMeshes[mesh.uniqueId] = undefined;
  60956. };
  60957. /**
  60958. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  60959. * @param mesh The mesh to highlight
  60960. * @param color The color of the highlight
  60961. * @param glowEmissiveOnly Extract the glow from the emissive texture
  60962. */
  60963. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  60964. var _this = this;
  60965. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  60966. var meshHighlight = this._meshes[mesh.uniqueId];
  60967. if (meshHighlight) {
  60968. meshHighlight.color = color;
  60969. }
  60970. else {
  60971. this._meshes[mesh.uniqueId] = {
  60972. mesh: mesh,
  60973. color: color,
  60974. // Lambda required for capture due to Observable this context
  60975. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  60976. if (_this._excludedMeshes[mesh.uniqueId]) {
  60977. _this.defaultStencilReference(mesh);
  60978. }
  60979. else {
  60980. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  60981. }
  60982. }),
  60983. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  60984. glowEmissiveOnly: glowEmissiveOnly
  60985. };
  60986. }
  60987. this._shouldRender = true;
  60988. };
  60989. /**
  60990. * Remove a mesh from the highlight layer in order to make it stop glowing.
  60991. * @param mesh The mesh to highlight
  60992. */
  60993. HighlightLayer.prototype.removeMesh = function (mesh) {
  60994. var meshHighlight = this._meshes[mesh.uniqueId];
  60995. if (meshHighlight) {
  60996. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  60997. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  60998. }
  60999. this._meshes[mesh.uniqueId] = undefined;
  61000. this._shouldRender = false;
  61001. for (var meshHighlightToCheck in this._meshes) {
  61002. if (meshHighlightToCheck) {
  61003. this._shouldRender = true;
  61004. break;
  61005. }
  61006. }
  61007. };
  61008. /**
  61009. * Returns true if the layer contains information to display, otherwise false.
  61010. */
  61011. HighlightLayer.prototype.shouldRender = function () {
  61012. return this.isEnabled && this._shouldRender;
  61013. };
  61014. /**
  61015. * Sets the main texture desired size which is the closest power of two
  61016. * of the engine canvas size.
  61017. */
  61018. HighlightLayer.prototype.setMainTextureSize = function () {
  61019. if (this._options.mainTextureFixedSize) {
  61020. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  61021. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  61022. }
  61023. else {
  61024. this._mainTextureDesiredSize.width = this._engine.getRenderingCanvas().width * this._options.mainTextureRatio;
  61025. this._mainTextureDesiredSize.height = this._engine.getRenderingCanvas().height * this._options.mainTextureRatio;
  61026. this._mainTextureDesiredSize.width = BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize);
  61027. this._mainTextureDesiredSize.height = BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize);
  61028. }
  61029. };
  61030. /**
  61031. * Force the stencil to the normal expected value for none glowing parts
  61032. */
  61033. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  61034. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  61035. };
  61036. /**
  61037. * Dispose only the render target textures and post process.
  61038. */
  61039. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  61040. this._blurTexture.dispose();
  61041. this._mainTexture.dispose();
  61042. this._downSamplePostprocess.dispose();
  61043. this._horizontalBlurPostprocess.dispose();
  61044. this._verticalBlurPostprocess.dispose();
  61045. };
  61046. /**
  61047. * Dispose the highlight layer and free resources.
  61048. */
  61049. HighlightLayer.prototype.dispose = function () {
  61050. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  61051. if (vertexBuffer) {
  61052. vertexBuffer.dispose();
  61053. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  61054. }
  61055. if (this._indexBuffer) {
  61056. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  61057. this._indexBuffer = null;
  61058. }
  61059. // Clean textures and post processes
  61060. this.disposeTextureAndPostProcesses();
  61061. // Clean mesh references
  61062. for (var id in this._meshes) {
  61063. var meshHighlight = this._meshes[id];
  61064. if (meshHighlight && meshHighlight.mesh) {
  61065. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  61066. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  61067. }
  61068. }
  61069. this._meshes = null;
  61070. for (var id in this._excludedMeshes) {
  61071. var meshHighlight = this._excludedMeshes[id];
  61072. if (meshHighlight) {
  61073. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  61074. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  61075. }
  61076. }
  61077. this._excludedMeshes = null;
  61078. // Remove from scene
  61079. var index = this._scene.highlightLayers.indexOf(this, 0);
  61080. if (index > -1) {
  61081. this._scene.highlightLayers.splice(index, 1);
  61082. }
  61083. // Callback
  61084. this.onDisposeObservable.notifyObservers(this);
  61085. this.onDisposeObservable.clear();
  61086. this.onBeforeRenderMainTextureObservable.clear();
  61087. this.onBeforeBlurObservable.clear();
  61088. this.onBeforeComposeObservable.clear();
  61089. this.onAfterComposeObservable.clear();
  61090. this.onSizeChangedObservable.clear();
  61091. };
  61092. return HighlightLayer;
  61093. }());
  61094. /**
  61095. * The neutral color used during the preparation of the glow effect.
  61096. * This is black by default as the blend operation is a blend operation.
  61097. */
  61098. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  61099. /**
  61100. * Stencil value used for glowing meshes.
  61101. */
  61102. HighlightLayer.glowingMeshStencilReference = 0x02;
  61103. /**
  61104. * Stencil value used for the other meshes in the scene.
  61105. */
  61106. HighlightLayer.normalMeshStencilReference = 0x01;
  61107. BABYLON.HighlightLayer = HighlightLayer;
  61108. })(BABYLON || (BABYLON = {}));
  61109. //# sourceMappingURL=babylon.highlightlayer.js.map
  61110. var BABYLON;
  61111. (function (BABYLON) {
  61112. var MeshAssetTask = (function () {
  61113. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  61114. this.name = name;
  61115. this.meshesNames = meshesNames;
  61116. this.rootUrl = rootUrl;
  61117. this.sceneFilename = sceneFilename;
  61118. this.isCompleted = false;
  61119. }
  61120. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  61121. var _this = this;
  61122. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  61123. _this.loadedMeshes = meshes;
  61124. _this.loadedParticleSystems = particleSystems;
  61125. _this.loadedSkeletons = skeletons;
  61126. _this.isCompleted = true;
  61127. if (_this.onSuccess) {
  61128. _this.onSuccess(_this);
  61129. }
  61130. onSuccess();
  61131. }, null, function () {
  61132. if (_this.onError) {
  61133. _this.onError(_this);
  61134. }
  61135. onError();
  61136. });
  61137. };
  61138. return MeshAssetTask;
  61139. }());
  61140. BABYLON.MeshAssetTask = MeshAssetTask;
  61141. var TextFileAssetTask = (function () {
  61142. function TextFileAssetTask(name, url) {
  61143. this.name = name;
  61144. this.url = url;
  61145. this.isCompleted = false;
  61146. }
  61147. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  61148. var _this = this;
  61149. BABYLON.Tools.LoadFile(this.url, function (data) {
  61150. _this.text = data;
  61151. _this.isCompleted = true;
  61152. if (_this.onSuccess) {
  61153. _this.onSuccess(_this);
  61154. }
  61155. onSuccess();
  61156. }, null, scene.database, false, function () {
  61157. if (_this.onError) {
  61158. _this.onError(_this);
  61159. }
  61160. onError();
  61161. });
  61162. };
  61163. return TextFileAssetTask;
  61164. }());
  61165. BABYLON.TextFileAssetTask = TextFileAssetTask;
  61166. var BinaryFileAssetTask = (function () {
  61167. function BinaryFileAssetTask(name, url) {
  61168. this.name = name;
  61169. this.url = url;
  61170. this.isCompleted = false;
  61171. }
  61172. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  61173. var _this = this;
  61174. BABYLON.Tools.LoadFile(this.url, function (data) {
  61175. _this.data = data;
  61176. _this.isCompleted = true;
  61177. if (_this.onSuccess) {
  61178. _this.onSuccess(_this);
  61179. }
  61180. onSuccess();
  61181. }, null, scene.database, true, function () {
  61182. if (_this.onError) {
  61183. _this.onError(_this);
  61184. }
  61185. onError();
  61186. });
  61187. };
  61188. return BinaryFileAssetTask;
  61189. }());
  61190. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  61191. var ImageAssetTask = (function () {
  61192. function ImageAssetTask(name, url) {
  61193. this.name = name;
  61194. this.url = url;
  61195. this.isCompleted = false;
  61196. }
  61197. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  61198. var _this = this;
  61199. var img = new Image();
  61200. BABYLON.Tools.SetCorsBehavior(this.url, img);
  61201. img.onload = function () {
  61202. _this.image = img;
  61203. _this.isCompleted = true;
  61204. if (_this.onSuccess) {
  61205. _this.onSuccess(_this);
  61206. }
  61207. onSuccess();
  61208. };
  61209. img.onerror = function () {
  61210. if (_this.onError) {
  61211. _this.onError(_this);
  61212. }
  61213. onError();
  61214. };
  61215. img.src = this.url;
  61216. };
  61217. return ImageAssetTask;
  61218. }());
  61219. BABYLON.ImageAssetTask = ImageAssetTask;
  61220. var TextureAssetTask = (function () {
  61221. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  61222. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  61223. this.name = name;
  61224. this.url = url;
  61225. this.noMipmap = noMipmap;
  61226. this.invertY = invertY;
  61227. this.samplingMode = samplingMode;
  61228. this.isCompleted = false;
  61229. }
  61230. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  61231. var _this = this;
  61232. var onload = function () {
  61233. _this.isCompleted = true;
  61234. if (_this.onSuccess) {
  61235. _this.onSuccess(_this);
  61236. }
  61237. onSuccess();
  61238. };
  61239. var onerror = function () {
  61240. if (_this.onError) {
  61241. _this.onError(_this);
  61242. }
  61243. onError();
  61244. };
  61245. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  61246. };
  61247. return TextureAssetTask;
  61248. }());
  61249. BABYLON.TextureAssetTask = TextureAssetTask;
  61250. var CubeTextureAssetTask = (function () {
  61251. function CubeTextureAssetTask(name, url, extensions, noMipmap, files) {
  61252. this.name = name;
  61253. this.url = url;
  61254. this.extensions = extensions;
  61255. this.noMipmap = noMipmap;
  61256. this.files = files;
  61257. this.isCompleted = false;
  61258. }
  61259. CubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  61260. var _this = this;
  61261. var onload = function () {
  61262. _this.isCompleted = true;
  61263. if (_this.onSuccess) {
  61264. _this.onSuccess(_this);
  61265. }
  61266. onSuccess();
  61267. };
  61268. var onerror = function () {
  61269. if (_this.onError) {
  61270. _this.onError(_this);
  61271. }
  61272. onError();
  61273. };
  61274. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  61275. };
  61276. return CubeTextureAssetTask;
  61277. }());
  61278. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  61279. var HDRCubeTextureAssetTask = (function () {
  61280. function HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  61281. if (noMipmap === void 0) { noMipmap = false; }
  61282. if (generateHarmonics === void 0) { generateHarmonics = true; }
  61283. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  61284. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  61285. this.name = name;
  61286. this.url = url;
  61287. this.size = size;
  61288. this.noMipmap = noMipmap;
  61289. this.generateHarmonics = generateHarmonics;
  61290. this.useInGammaSpace = useInGammaSpace;
  61291. this.usePMREMGenerator = usePMREMGenerator;
  61292. this.isCompleted = false;
  61293. }
  61294. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  61295. var _this = this;
  61296. var onload = function () {
  61297. _this.isCompleted = true;
  61298. if (_this.onSuccess) {
  61299. _this.onSuccess(_this);
  61300. }
  61301. onSuccess();
  61302. };
  61303. var onerror = function () {
  61304. if (_this.onError) {
  61305. _this.onError(_this);
  61306. }
  61307. onError();
  61308. };
  61309. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  61310. };
  61311. return HDRCubeTextureAssetTask;
  61312. }());
  61313. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  61314. var AssetsManager = (function () {
  61315. function AssetsManager(scene) {
  61316. this.tasks = new Array();
  61317. this.waitingTasksCount = 0;
  61318. this.useDefaultLoadingScreen = true;
  61319. this._scene = scene;
  61320. }
  61321. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  61322. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  61323. this.tasks.push(task);
  61324. return task;
  61325. };
  61326. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  61327. var task = new TextFileAssetTask(taskName, url);
  61328. this.tasks.push(task);
  61329. return task;
  61330. };
  61331. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  61332. var task = new BinaryFileAssetTask(taskName, url);
  61333. this.tasks.push(task);
  61334. return task;
  61335. };
  61336. AssetsManager.prototype.addImageTask = function (taskName, url) {
  61337. var task = new ImageAssetTask(taskName, url);
  61338. this.tasks.push(task);
  61339. return task;
  61340. };
  61341. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  61342. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  61343. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  61344. this.tasks.push(task);
  61345. return task;
  61346. };
  61347. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  61348. this.waitingTasksCount--;
  61349. if (this.waitingTasksCount === 0) {
  61350. if (this.onFinish) {
  61351. this.onFinish(this.tasks);
  61352. }
  61353. this._scene.getEngine().hideLoadingUI();
  61354. }
  61355. };
  61356. AssetsManager.prototype._runTask = function (task) {
  61357. var _this = this;
  61358. task.run(this._scene, function () {
  61359. if (_this.onTaskSuccess) {
  61360. _this.onTaskSuccess(task);
  61361. }
  61362. _this._decreaseWaitingTasksCount();
  61363. }, function () {
  61364. if (_this.onTaskError) {
  61365. _this.onTaskError(task);
  61366. }
  61367. _this._decreaseWaitingTasksCount();
  61368. });
  61369. };
  61370. AssetsManager.prototype.reset = function () {
  61371. this.tasks = new Array();
  61372. return this;
  61373. };
  61374. AssetsManager.prototype.load = function () {
  61375. this.waitingTasksCount = this.tasks.length;
  61376. if (this.waitingTasksCount === 0) {
  61377. if (this.onFinish) {
  61378. this.onFinish(this.tasks);
  61379. }
  61380. return this;
  61381. }
  61382. if (this.useDefaultLoadingScreen) {
  61383. this._scene.getEngine().displayLoadingUI();
  61384. }
  61385. for (var index = 0; index < this.tasks.length; index++) {
  61386. var task = this.tasks[index];
  61387. this._runTask(task);
  61388. }
  61389. return this;
  61390. };
  61391. return AssetsManager;
  61392. }());
  61393. BABYLON.AssetsManager = AssetsManager;
  61394. })(BABYLON || (BABYLON = {}));
  61395. //# sourceMappingURL=babylon.assetsManager.js.map
  61396. var BABYLON;
  61397. (function (BABYLON) {
  61398. var MapTexture = (function (_super) {
  61399. __extends(MapTexture, _super);
  61400. function MapTexture(name, scene, size, samplingMode, useMipMap, margin) {
  61401. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  61402. if (useMipMap === void 0) { useMipMap = false; }
  61403. if (margin === void 0) { margin = 0; }
  61404. var _this = _super.call(this, null, scene, !useMipMap, false, samplingMode) || this;
  61405. _this.name = name;
  61406. _this._size = size;
  61407. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61408. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61409. // Create the rectPackMap that will allocate portion of the texture
  61410. _this._rectPackingMap = new BABYLON.RectPackingMap(new BABYLON.Size(size.width, size.height), margin);
  61411. // Create the texture that will store the content
  61412. _this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: !_this.noMipmap, type: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT });
  61413. return _this;
  61414. }
  61415. /**
  61416. * Allocate a rectangle of a given size in the texture map
  61417. * @param size the size of the rectangle to allocation
  61418. * @return the PackedRect instance corresponding to the allocated rect or null is there was not enough space to allocate it.
  61419. */
  61420. MapTexture.prototype.allocateRect = function (size) {
  61421. return this._rectPackingMap.addRect(size);
  61422. };
  61423. /**
  61424. * Free a given rectangle from the texture map
  61425. * @param rectInfo the instance corresponding to the rect to free.
  61426. */
  61427. MapTexture.prototype.freeRect = function (rectInfo) {
  61428. if (rectInfo) {
  61429. rectInfo.freeContent();
  61430. }
  61431. };
  61432. Object.defineProperty(MapTexture.prototype, "freeSpace", {
  61433. /**
  61434. * Return the available space in the range of [O;1]. 0 being not space left at all, 1 being an empty texture map.
  61435. * This is the cumulated space, not the biggest available surface. Due to fragmentation you may not allocate a rect corresponding to this surface.
  61436. * @returns {}
  61437. */
  61438. get: function () {
  61439. return this._rectPackingMap.freeSpace;
  61440. },
  61441. enumerable: true,
  61442. configurable: true
  61443. });
  61444. /**
  61445. * Bind the texture to the rendering engine to render in the zone of a given rectangle.
  61446. * 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.
  61447. * Don't forget to call unbindTexture when you're done rendering
  61448. * @param rect the zone to render to
  61449. * @param clear true to clear the portion's color/depth data
  61450. */
  61451. MapTexture.prototype.bindTextureForRect = function (rect, clear) {
  61452. return this.bindTextureForPosSize(rect.pos, rect.contentSize, clear);
  61453. };
  61454. /**
  61455. * Bind the texture to the rendering engine to render in the zone of the given size at the given position.
  61456. * 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.
  61457. * Don't forget to call unbindTexture when you're done rendering
  61458. * @param pos the position into the texture
  61459. * @param size the portion to fit the clip space to
  61460. * @param clear true to clear the portion's color/depth data
  61461. */
  61462. MapTexture.prototype.bindTextureForPosSize = function (pos, size, clear) {
  61463. var engine = this.getScene().getEngine();
  61464. engine.bindFramebuffer(this._texture);
  61465. this._replacedViewport = engine.setDirectViewport(pos.x, pos.y, size.width, size.height);
  61466. if (clear) {
  61467. // We only want to clear the part of the texture we're binding to, only the scissor can help us to achieve that
  61468. engine.scissorClear(pos.x, pos.y, size.width, size.height, new BABYLON.Color4(0, 0, 0, 0));
  61469. }
  61470. };
  61471. /**
  61472. * Unbind the texture map from the rendering engine.
  61473. * Call this method when you're done rendering. A previous call to bindTextureForRect has to be made.
  61474. * @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.
  61475. */
  61476. MapTexture.prototype.unbindTexture = function (dumpForDebug) {
  61477. // Dump ?
  61478. if (dumpForDebug) {
  61479. BABYLON.Tools.DumpFramebuffer(this._size.width, this._size.height, this.getScene().getEngine());
  61480. }
  61481. var engine = this.getScene().getEngine();
  61482. if (this._replacedViewport) {
  61483. engine.setViewport(this._replacedViewport);
  61484. this._replacedViewport = null;
  61485. }
  61486. engine.unBindFramebuffer(this._texture);
  61487. };
  61488. Object.defineProperty(MapTexture.prototype, "canRescale", {
  61489. get: function () {
  61490. return false;
  61491. },
  61492. enumerable: true,
  61493. configurable: true
  61494. });
  61495. // Note, I don't know what behavior this method should have: clone the underlying texture/rectPackingMap or just reference them?
  61496. // Anyway, there's not much point to use this method for this kind of texture I guess
  61497. MapTexture.prototype.clone = function () {
  61498. return null;
  61499. };
  61500. return MapTexture;
  61501. }(BABYLON.Texture));
  61502. BABYLON.MapTexture = MapTexture;
  61503. })(BABYLON || (BABYLON = {}));
  61504. //# sourceMappingURL=babylon.mapTexture.js.map
  61505. var BABYLON;
  61506. (function (BABYLON) {
  61507. /**
  61508. * This class describe a rectangle that were added to the map.
  61509. * You have access to its coordinates either in pixel or normalized (UV)
  61510. */
  61511. var PackedRect = (function () {
  61512. function PackedRect(root, parent, pos, size) {
  61513. this._pos = pos;
  61514. this._size = size;
  61515. this._root = root;
  61516. this._parent = parent;
  61517. this._contentSize = null;
  61518. this._bottomNode = null;
  61519. this._leftNode = null;
  61520. this._initialSize = null;
  61521. this._rightNode = null;
  61522. }
  61523. Object.defineProperty(PackedRect.prototype, "pos", {
  61524. /**
  61525. * @returns the position of this node into the map
  61526. */
  61527. get: function () {
  61528. return this._pos;
  61529. },
  61530. enumerable: true,
  61531. configurable: true
  61532. });
  61533. Object.defineProperty(PackedRect.prototype, "contentSize", {
  61534. /**
  61535. * @returns the size of the rectangle this node handles
  61536. */
  61537. get: function () {
  61538. return this._contentSize;
  61539. },
  61540. enumerable: true,
  61541. configurable: true
  61542. });
  61543. /**
  61544. * Retrieve the inner position (considering the margin) and stores it into the res object
  61545. * @param res must be a valid Vector2 that will contain the inner position after this call
  61546. */
  61547. PackedRect.prototype.getInnerPosToRef = function (res) {
  61548. var m = this._root._margin;
  61549. res.x = this._pos.x + m;
  61550. res.y = this._pos.y + m;
  61551. };
  61552. /**
  61553. * Retrieve the inner size (considering the margin) and stores it into the res object
  61554. * @param res must be a valid Size that will contain the inner size after this call
  61555. */
  61556. PackedRect.prototype.getInnerSizeToRef = function (res) {
  61557. var m = this._root._margin;
  61558. res.width = this._contentSize.width - (m * 2);
  61559. res.height = this._contentSize.height - (m * 2);
  61560. };
  61561. Object.defineProperty(PackedRect.prototype, "UVs", {
  61562. /**
  61563. * Compute the UV of the top/left, top/right, bottom/right, bottom/left points of the rectangle this node handles into the map
  61564. * @returns And array of 4 Vector2, containing UV coordinates for the four corners of the Rectangle into the map
  61565. */
  61566. get: function () {
  61567. if (!this._contentSize) {
  61568. throw new Error("Can't compute UVs for this object because it's nor allocated");
  61569. }
  61570. return this.getUVsForCustomSize(this._contentSize);
  61571. },
  61572. enumerable: true,
  61573. configurable: true
  61574. });
  61575. /**
  61576. * You may have allocated the PackedRect using over-provisioning (you allocated more than you need in order to prevent frequent deallocations/reallocations)
  61577. * and then using only a part of the PackRect.
  61578. * This method will return the UVs for this part by given the custom size of what you really use
  61579. * @param customSize must be less/equal to the allocated size, UV will be compute from this
  61580. */
  61581. PackedRect.prototype.getUVsForCustomSize = function (customSize) {
  61582. var mainWidth = this._root._size.width;
  61583. var mainHeight = this._root._size.height;
  61584. var margin = this._root._margin;
  61585. var topLeft = new BABYLON.Vector2((this._pos.x + margin) / mainWidth, (this._pos.y + margin) / mainHeight);
  61586. var rightBottom = new BABYLON.Vector2((this._pos.x + customSize.width + margin - 1) / mainWidth, (this._pos.y + customSize.height + margin - 1) / mainHeight);
  61587. var uvs = new Array();
  61588. uvs.push(topLeft);
  61589. uvs.push(new BABYLON.Vector2(rightBottom.x, topLeft.y));
  61590. uvs.push(rightBottom);
  61591. uvs.push(new BABYLON.Vector2(topLeft.x, rightBottom.y));
  61592. return uvs;
  61593. };
  61594. /**
  61595. * Free this rectangle from the map.
  61596. * Call this method when you no longer need the rectangle to be in the map.
  61597. */
  61598. PackedRect.prototype.freeContent = function () {
  61599. if (!this.contentSize) {
  61600. return;
  61601. }
  61602. this._contentSize = null;
  61603. // If everything below is also free, reset the whole node, and attempt to reset parents if they also become free
  61604. this.attemptDefrag();
  61605. };
  61606. Object.defineProperty(PackedRect.prototype, "isUsed", {
  61607. get: function () {
  61608. return this._contentSize != null || this._leftNode != null;
  61609. },
  61610. enumerable: true,
  61611. configurable: true
  61612. });
  61613. PackedRect.prototype.findAndSplitNode = function (contentSize) {
  61614. var node = this.findNode(contentSize);
  61615. // Not enough space...
  61616. if (!node) {
  61617. return null;
  61618. }
  61619. node.splitNode(contentSize);
  61620. return node;
  61621. };
  61622. PackedRect.prototype.findNode = function (size) {
  61623. var resNode = null;
  61624. var margin = this._root._margin * 2;
  61625. // If this node is used, recurse to each of his subNodes to find an available one in its branch
  61626. if (this.isUsed) {
  61627. if (this._leftNode) {
  61628. resNode = this._leftNode.findNode(size);
  61629. }
  61630. if (!resNode && this._rightNode) {
  61631. resNode = this._rightNode.findNode(size);
  61632. }
  61633. if (!resNode && this._bottomNode) {
  61634. resNode = this._bottomNode.findNode(size);
  61635. }
  61636. }
  61637. else if (this._initialSize) {
  61638. if (((size.width + margin) <= this._initialSize.width) && ((size.height + margin) <= this._initialSize.height)) {
  61639. resNode = this;
  61640. }
  61641. else {
  61642. return null;
  61643. }
  61644. }
  61645. else if (((size.width + margin) <= this._size.width) && ((size.height + margin) <= this._size.height)) {
  61646. resNode = this;
  61647. }
  61648. return resNode;
  61649. };
  61650. PackedRect.prototype.splitNode = function (contentSize) {
  61651. var cs = PackedRect.TpsSize;
  61652. var margin = this._root._margin * 2;
  61653. cs.copyFrom(contentSize);
  61654. cs.width += margin;
  61655. cs.height += margin;
  61656. // 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)
  61657. if (!this._contentSize && this._initialSize) {
  61658. this._contentSize = cs.clone();
  61659. 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));
  61660. return this._leftNode.splitNode(contentSize);
  61661. }
  61662. else {
  61663. this._contentSize = cs.clone();
  61664. this._initialSize = cs.clone();
  61665. if (cs.width !== this._size.width) {
  61666. 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));
  61667. }
  61668. if (cs.height !== this._size.height) {
  61669. 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));
  61670. }
  61671. return this;
  61672. }
  61673. };
  61674. PackedRect.prototype.attemptDefrag = function () {
  61675. if (!this.isUsed && this.isRecursiveFree) {
  61676. this.clearNode();
  61677. if (this._parent) {
  61678. this._parent.attemptDefrag();
  61679. }
  61680. }
  61681. };
  61682. PackedRect.prototype.clearNode = function () {
  61683. this._initialSize = null;
  61684. this._rightNode = null;
  61685. this._bottomNode = null;
  61686. };
  61687. Object.defineProperty(PackedRect.prototype, "isRecursiveFree", {
  61688. get: function () {
  61689. return !this.contentSize && (!this._leftNode || this._leftNode.isRecursiveFree) && (!this._rightNode || this._rightNode.isRecursiveFree) && (!this._bottomNode || this._bottomNode.isRecursiveFree);
  61690. },
  61691. enumerable: true,
  61692. configurable: true
  61693. });
  61694. PackedRect.prototype.evalFreeSize = function (size) {
  61695. var levelSize = 0;
  61696. if (!this.isUsed) {
  61697. var margin = this._root._margin;
  61698. var is = this._initialSize;
  61699. if (is) {
  61700. levelSize = is.surface - (is.width * margin) - (is.height * margin);
  61701. }
  61702. else {
  61703. var size_1 = this._size;
  61704. levelSize = size_1.surface - (size_1.width * margin) - (size_1.height * margin);
  61705. }
  61706. }
  61707. if (this._rightNode) {
  61708. levelSize += this._rightNode.evalFreeSize(0);
  61709. }
  61710. if (this._bottomNode) {
  61711. levelSize += this._bottomNode.evalFreeSize(0);
  61712. }
  61713. return levelSize + size;
  61714. };
  61715. return PackedRect;
  61716. }());
  61717. PackedRect.TpsSize = BABYLON.Size.Zero();
  61718. BABYLON.PackedRect = PackedRect;
  61719. /**
  61720. * The purpose of this class is to pack several Rectangles into a big map, while trying to fit everything as optimally as possible.
  61721. * This class is typically used to build lightmaps, sprite map or to pack several little textures into a big one.
  61722. * 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.
  61723. * In case you need a margin around the allocated rect, specify the amount in the margin argument during construction.
  61724. * In such case you will have to rely on innerPositionToRef and innerSizeToRef calls to get the proper size
  61725. */
  61726. var RectPackingMap = (function (_super) {
  61727. __extends(RectPackingMap, _super);
  61728. /**
  61729. * Create an instance of the object with a dimension using the given size
  61730. * @param size The dimension of the rectangle that will contain all the sub ones.
  61731. * @param margin The margin (empty space) created (in pixels) around the allocated Rectangles
  61732. */
  61733. function RectPackingMap(size, margin) {
  61734. if (margin === void 0) { margin = 0; }
  61735. var _this = _super.call(this, null, null, BABYLON.Vector2.Zero(), size) || this;
  61736. _this._margin = margin;
  61737. _this._root = _this;
  61738. return _this;
  61739. }
  61740. /**
  61741. * Add a rectangle, finding the best location to store it into the map
  61742. * @param size the dimension of the rectangle to store
  61743. * @return the Node containing the rectangle information, or null if we couldn't find a free spot
  61744. */
  61745. RectPackingMap.prototype.addRect = function (size) {
  61746. var node = this.findAndSplitNode(size);
  61747. return node;
  61748. };
  61749. Object.defineProperty(RectPackingMap.prototype, "freeSpace", {
  61750. /**
  61751. * Return the current space free normalized between [0;1]
  61752. * @returns {}
  61753. */
  61754. get: function () {
  61755. var freeSize = 0;
  61756. freeSize = this.evalFreeSize(freeSize);
  61757. return freeSize / (this._size.width * this._size.height);
  61758. },
  61759. enumerable: true,
  61760. configurable: true
  61761. });
  61762. return RectPackingMap;
  61763. }(PackedRect));
  61764. BABYLON.RectPackingMap = RectPackingMap;
  61765. })(BABYLON || (BABYLON = {}));
  61766. //# sourceMappingURL=babylon.rectPackingMap.js.map
  61767. var BABYLON;
  61768. (function (BABYLON) {
  61769. var DynamicFloatArrayElementInfo = (function () {
  61770. function DynamicFloatArrayElementInfo() {
  61771. }
  61772. return DynamicFloatArrayElementInfo;
  61773. }());
  61774. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  61775. /**
  61776. * 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.
  61777. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  61778. * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
  61779. * 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.
  61780. * 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.
  61781. * 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".
  61782. */
  61783. var DynamicFloatArray = (function () {
  61784. /**
  61785. * Construct an instance of the dynamic float array
  61786. * @param stride size of one element in float (i.e. not bytes!)
  61787. * @param initialElementCount the number of available entries at construction
  61788. */
  61789. function DynamicFloatArray(stride, initialElementCount) {
  61790. this.compareValueOffset = null;
  61791. this.sortingAscending = true;
  61792. this._stride = stride;
  61793. this.buffer = new Float32Array(stride * initialElementCount);
  61794. this._lastUsed = 0;
  61795. this._firstFree = 0;
  61796. this._allEntries = new Array(initialElementCount);
  61797. this._freeEntries = new Array(initialElementCount);
  61798. for (var i = 0; i < initialElementCount; i++) {
  61799. var element = new DynamicFloatArrayElementInfo();
  61800. element.offset = i * stride;
  61801. this._allEntries[i] = element;
  61802. this._freeEntries[initialElementCount - i - 1] = element;
  61803. }
  61804. }
  61805. /**
  61806. * Allocate an element in the array.
  61807. * @return the element info instance that contains the offset into the main buffer of the element's location.
  61808. * Beware, this offset may change when you call pack()
  61809. */
  61810. DynamicFloatArray.prototype.allocElement = function () {
  61811. if (this._freeEntries.length === 0) {
  61812. this._growBuffer();
  61813. }
  61814. var el = this._freeEntries.pop();
  61815. this._lastUsed = Math.max(el.offset, this._lastUsed);
  61816. if (el.offset === this._firstFree) {
  61817. if (this._freeEntries.length > 0) {
  61818. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  61819. }
  61820. else {
  61821. this._firstFree += this._stride;
  61822. }
  61823. }
  61824. return el;
  61825. };
  61826. /**
  61827. * Free the element corresponding to the given element info
  61828. * @param elInfo the element that describe the allocated element
  61829. */
  61830. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  61831. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  61832. this._freeEntries.push(elInfo);
  61833. };
  61834. /**
  61835. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  61836. * 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().
  61837. * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  61838. */
  61839. DynamicFloatArray.prototype.pack = function () {
  61840. // no free slot? no need to pack
  61841. if (this._freeEntries.length === 0) {
  61842. return this.buffer;
  61843. }
  61844. // If the buffer is already packed the last used will always be lower than the first free
  61845. // 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.
  61846. if (this._lastUsed < this._firstFree) {
  61847. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  61848. return elementsBuffer_1;
  61849. }
  61850. var s = this._stride;
  61851. // 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
  61852. var lastFree = new DynamicFloatArrayElementInfo();
  61853. lastFree.offset = this.totalElementCount * s;
  61854. this._freeEntries.push(lastFree);
  61855. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  61856. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  61857. var firstFreeSlotOffset = sortedFree[0].offset;
  61858. var freeZoneSize = 1;
  61859. var occupiedZoneSize = (this.usedElementCount + 1) * s;
  61860. var prevOffset = sortedFree[0].offset;
  61861. for (var i = 1; i < sortedFree.length; i++) {
  61862. // 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
  61863. if (firstFreeSlotOffset >= occupiedZoneSize) {
  61864. break;
  61865. }
  61866. var curFree = sortedFree[i];
  61867. var curOffset = curFree.offset;
  61868. // Compute the distance between this offset and the previous
  61869. var distance = curOffset - prevOffset;
  61870. // If the distance is the stride size, they are adjacent, it good, move to the next
  61871. if (distance === s) {
  61872. // Free zone is one element bigger
  61873. ++freeZoneSize;
  61874. // as we're about to iterate to the next, the cur becomes the previous...
  61875. prevOffset = curOffset;
  61876. continue;
  61877. }
  61878. // Distance is bigger, which means there's x element between the previous free and this one
  61879. var usedRange = (distance / s) - 1;
  61880. // Two cases the free zone is smaller than the data to move or bigger
  61881. // Copy what can fit in the free zone
  61882. var curMoveOffset = curOffset - s;
  61883. var copyCount = Math.min(freeZoneSize, usedRange);
  61884. for (var j = 0; j < copyCount; j++) {
  61885. var freeI = firstFreeSlotOffset / s;
  61886. var curI = curMoveOffset / s;
  61887. var moveEl = sortedAll[curI];
  61888. this._moveElement(moveEl, firstFreeSlotOffset);
  61889. var replacedEl = sortedAll[freeI];
  61890. // set the offset of the element we replaced with a value that will make it discard at the end of the method
  61891. replacedEl.offset = curMoveOffset;
  61892. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  61893. sortedAll[freeI] = moveEl;
  61894. sortedAll[curI] = replacedEl;
  61895. curMoveOffset -= s;
  61896. firstFreeSlotOffset += s;
  61897. }
  61898. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  61899. if (freeZoneSize <= usedRange) {
  61900. firstFreeSlotOffset = curMoveOffset + s;
  61901. freeZoneSize = 1 + copyCount;
  61902. }
  61903. else {
  61904. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  61905. }
  61906. // as we're about to iterate to the next, the cur becomes the previous...
  61907. prevOffset = curOffset;
  61908. }
  61909. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  61910. this._lastUsed = firstFreeSlotOffset - s;
  61911. this._firstFree = firstFreeSlotOffset;
  61912. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  61913. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  61914. this._allEntries = sortedAll;
  61915. return elementsBuffer;
  61916. };
  61917. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  61918. for (var i = 0; i < this._stride; i++) {
  61919. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  61920. }
  61921. element.offset = destOffset;
  61922. };
  61923. DynamicFloatArray.prototype._growBuffer = function () {
  61924. // Allocate the new buffer with 50% more entries, copy the content of the current one
  61925. var newElCount = Math.floor(this.totalElementCount * 1.5);
  61926. var newBuffer = new Float32Array(newElCount * this._stride);
  61927. newBuffer.set(this.buffer);
  61928. var curCount = this.totalElementCount;
  61929. var addedCount = newElCount - this.totalElementCount;
  61930. for (var i = 0; i < addedCount; i++) {
  61931. var element = new DynamicFloatArrayElementInfo();
  61932. element.offset = (curCount + i) * this.stride;
  61933. this._allEntries.push(element);
  61934. this._freeEntries[addedCount - i - 1] = element;
  61935. }
  61936. this._firstFree = curCount * this.stride;
  61937. this.buffer = newBuffer;
  61938. };
  61939. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  61940. /**
  61941. * Get the total count of entries that can fit in the current buffer
  61942. * @returns the elements count
  61943. */
  61944. get: function () {
  61945. return this._allEntries.length;
  61946. },
  61947. enumerable: true,
  61948. configurable: true
  61949. });
  61950. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  61951. /**
  61952. * Get the count of free entries that can still be allocated without resizing the buffer
  61953. * @returns the free elements count
  61954. */
  61955. get: function () {
  61956. return this._freeEntries.length;
  61957. },
  61958. enumerable: true,
  61959. configurable: true
  61960. });
  61961. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  61962. /**
  61963. * Get the count of allocated elements
  61964. * @returns the allocated elements count
  61965. */
  61966. get: function () {
  61967. return this._allEntries.length - this._freeEntries.length;
  61968. },
  61969. enumerable: true,
  61970. configurable: true
  61971. });
  61972. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  61973. /**
  61974. * Return the size of one element in float
  61975. * @returns the size in float
  61976. */
  61977. get: function () {
  61978. return this._stride;
  61979. },
  61980. enumerable: true,
  61981. configurable: true
  61982. });
  61983. DynamicFloatArray.prototype.sort = function () {
  61984. var _this = this;
  61985. if (!this.compareValueOffset) {
  61986. throw new Error("The DynamicFloatArray.sort() method needs a valid 'compareValueOffset' property");
  61987. }
  61988. var count = this.usedElementCount;
  61989. // Do we have to (re)create the sort table?
  61990. if (!this._sortTable || this._sortTable.length < count) {
  61991. // 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...
  61992. var newCount = Math.min(this.totalElementCount, count * 2);
  61993. this._sortTable = new Array(newCount);
  61994. }
  61995. if (!this._sortedTable || this._sortedTable.length !== count) {
  61996. this._sortedTable = new Array(count);
  61997. }
  61998. // Because, you know...
  61999. this.pack();
  62000. //let stride = this.stride;
  62001. //for (let i = 0; i < count; i++) {
  62002. // let si = this._sortTable[i];
  62003. // if (!si) {
  62004. // si = new SortInfo();
  62005. // this._sortTable[i] = si;
  62006. // }
  62007. // si.entry = this._allEntries[i];
  62008. // si.compareData = this.buffer[si.entry.offset + this.compareValueOffset];
  62009. // si.swapedOffset = null;
  62010. // this._sortedTable[i] = si;
  62011. //}
  62012. var curOffset = 0;
  62013. var stride = this.stride;
  62014. for (var i = 0; i < count; i++, curOffset += stride) {
  62015. var si = this._sortTable[i];
  62016. if (!si) {
  62017. si = new SortInfo();
  62018. this._sortTable[i] = si;
  62019. }
  62020. si.compareData = this.buffer[curOffset + this.compareValueOffset];
  62021. si.offset = curOffset;
  62022. si.swapedOffset = null;
  62023. this._sortedTable[i] = si;
  62024. }
  62025. // Let's sort the sorted table, we want to keep a track of the original one (that's why we have two buffers)
  62026. if (this.sortingAscending) {
  62027. this._sortedTable.sort(function (a, b) { return a.compareData - b.compareData; });
  62028. }
  62029. else {
  62030. this._sortedTable.sort(function (a, b) { return b.compareData - a.compareData; });
  62031. }
  62032. var swapElements = function (src, dst) {
  62033. for (var i = 0; i < stride; i++) {
  62034. var tps = _this.buffer[dst + i];
  62035. _this.buffer[dst + i] = _this.buffer[src + i];
  62036. _this.buffer[src + i] = tps;
  62037. }
  62038. };
  62039. // 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:
  62040. // 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),
  62041. // and I still want something with a good algorithm complexity.
  62042. // 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,
  62043. // we need sortTable for that, it contains the original layout of SortInfo object, not the sorted one.
  62044. // The best way is to use an extra field in SortInfo, because potentially every element can be replaced.
  62045. // 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
  62046. // until we find a SortInfo object without a swapedOffset which means we got the right location
  62047. // 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
  62048. // than a double allocation of the whole float32Array or a O(n²/2) typical algorithm.
  62049. for (var i = 0; i < count; i++) {
  62050. // Get the element to move
  62051. var sourceSI = this._sortedTable[i];
  62052. var destSI = this._sortTable[i];
  62053. var sourceOff = sourceSI.offset;
  62054. // If the source changed location, find the new one
  62055. if (sourceSI.swapedOffset) {
  62056. // Follow the swapedOffset until there's none, it will mean that curSI contains the new location in its offset member
  62057. var curSI = sourceSI;
  62058. while (curSI.swapedOffset) {
  62059. curSI = this._sortTable[curSI.swapedOffset / stride];
  62060. }
  62061. // Finally get the right location
  62062. sourceOff = curSI.offset;
  62063. }
  62064. // Tag the element being replaced with its new location
  62065. destSI.swapedOffset = sourceOff;
  62066. // Swap elements (only if needed)
  62067. if (sourceOff !== destSI.offset) {
  62068. swapElements(sourceOff, destSI.offset);
  62069. }
  62070. // Update the offset in the corresponding DFAE
  62071. //sourceSI.entry.offset = destSI.entry.offset;
  62072. this._allEntries[sourceSI.offset / stride].offset = destSI.offset;
  62073. }
  62074. this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  62075. return true;
  62076. };
  62077. return DynamicFloatArray;
  62078. }());
  62079. BABYLON.DynamicFloatArray = DynamicFloatArray;
  62080. var SortInfo = (function () {
  62081. function SortInfo() {
  62082. this.compareData = this.offset = this.swapedOffset = null;
  62083. }
  62084. return SortInfo;
  62085. }());
  62086. })(BABYLON || (BABYLON = {}));
  62087. //# sourceMappingURL=babylon.dynamicFloatArray.js.map
  62088. var BABYLON;
  62089. (function (BABYLON) {
  62090. var serializedGeometries = [];
  62091. var serializeGeometry = function (geometry, serializationGeometries) {
  62092. if (serializedGeometries[geometry.id]) {
  62093. return;
  62094. }
  62095. if (geometry.doNotSerialize) {
  62096. return;
  62097. }
  62098. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  62099. serializationGeometries.boxes.push(geometry.serialize());
  62100. }
  62101. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  62102. serializationGeometries.spheres.push(geometry.serialize());
  62103. }
  62104. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  62105. serializationGeometries.cylinders.push(geometry.serialize());
  62106. }
  62107. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  62108. serializationGeometries.toruses.push(geometry.serialize());
  62109. }
  62110. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  62111. serializationGeometries.grounds.push(geometry.serialize());
  62112. }
  62113. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  62114. serializationGeometries.planes.push(geometry.serialize());
  62115. }
  62116. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  62117. serializationGeometries.torusKnots.push(geometry.serialize());
  62118. }
  62119. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  62120. throw new Error("Unknown primitive type");
  62121. }
  62122. else {
  62123. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  62124. }
  62125. serializedGeometries[geometry.id] = true;
  62126. };
  62127. var serializeMesh = function (mesh, serializationScene) {
  62128. var serializationObject = {};
  62129. // Geometry
  62130. var geometry = mesh._geometry;
  62131. if (geometry) {
  62132. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  62133. // 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
  62134. serializeGeometry(geometry, serializationScene.geometries);
  62135. }
  62136. }
  62137. // Custom
  62138. if (mesh.serialize) {
  62139. mesh.serialize(serializationObject);
  62140. }
  62141. return serializationObject;
  62142. };
  62143. var finalizeSingleMesh = function (mesh, serializationObject) {
  62144. //only works if the mesh is already loaded
  62145. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  62146. //serialize material
  62147. if (mesh.material) {
  62148. if (mesh.material instanceof BABYLON.StandardMaterial) {
  62149. serializationObject.materials = serializationObject.materials || [];
  62150. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  62151. serializationObject.materials.push(mesh.material.serialize());
  62152. }
  62153. }
  62154. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  62155. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  62156. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  62157. serializationObject.multiMaterials.push(mesh.material.serialize());
  62158. }
  62159. }
  62160. }
  62161. //serialize geometry
  62162. var geometry = mesh._geometry;
  62163. if (geometry) {
  62164. if (!serializationObject.geometries) {
  62165. serializationObject.geometries = {};
  62166. serializationObject.geometries.boxes = [];
  62167. serializationObject.geometries.spheres = [];
  62168. serializationObject.geometries.cylinders = [];
  62169. serializationObject.geometries.toruses = [];
  62170. serializationObject.geometries.grounds = [];
  62171. serializationObject.geometries.planes = [];
  62172. serializationObject.geometries.torusKnots = [];
  62173. serializationObject.geometries.vertexData = [];
  62174. }
  62175. serializeGeometry(geometry, serializationObject.geometries);
  62176. }
  62177. // Skeletons
  62178. if (mesh.skeleton) {
  62179. serializationObject.skeletons = serializationObject.skeletons || [];
  62180. serializationObject.skeletons.push(mesh.skeleton.serialize());
  62181. }
  62182. //serialize the actual mesh
  62183. serializationObject.meshes = serializationObject.meshes || [];
  62184. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  62185. }
  62186. };
  62187. var SceneSerializer = (function () {
  62188. function SceneSerializer() {
  62189. }
  62190. SceneSerializer.ClearCache = function () {
  62191. serializedGeometries = [];
  62192. };
  62193. SceneSerializer.Serialize = function (scene) {
  62194. var serializationObject = {};
  62195. SceneSerializer.ClearCache();
  62196. // Scene
  62197. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  62198. serializationObject.autoClear = scene.autoClear;
  62199. serializationObject.clearColor = scene.clearColor.asArray();
  62200. serializationObject.ambientColor = scene.ambientColor.asArray();
  62201. serializationObject.gravity = scene.gravity.asArray();
  62202. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  62203. serializationObject.workerCollisions = scene.workerCollisions;
  62204. // Fog
  62205. if (scene.fogMode && scene.fogMode !== 0) {
  62206. serializationObject.fogMode = scene.fogMode;
  62207. serializationObject.fogColor = scene.fogColor.asArray();
  62208. serializationObject.fogStart = scene.fogStart;
  62209. serializationObject.fogEnd = scene.fogEnd;
  62210. serializationObject.fogDensity = scene.fogDensity;
  62211. }
  62212. //Physics
  62213. if (scene.isPhysicsEnabled()) {
  62214. serializationObject.physicsEnabled = true;
  62215. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  62216. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  62217. }
  62218. // Metadata
  62219. if (scene.metadata) {
  62220. serializationObject.metadata = scene.metadata;
  62221. }
  62222. // Morph targets
  62223. serializationObject.morphTargetManagers = [];
  62224. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  62225. var abstractMesh = _a[_i];
  62226. var manager = abstractMesh.morphTargetManager;
  62227. if (manager) {
  62228. serializationObject.morphTargetManagers.push(manager.serialize());
  62229. }
  62230. }
  62231. // Lights
  62232. serializationObject.lights = [];
  62233. var index;
  62234. var light;
  62235. for (index = 0; index < scene.lights.length; index++) {
  62236. light = scene.lights[index];
  62237. if (!light.doNotSerialize) {
  62238. serializationObject.lights.push(light.serialize());
  62239. }
  62240. }
  62241. // Cameras
  62242. serializationObject.cameras = [];
  62243. for (index = 0; index < scene.cameras.length; index++) {
  62244. var camera = scene.cameras[index];
  62245. if (!camera.doNotSerialize) {
  62246. serializationObject.cameras.push(camera.serialize());
  62247. }
  62248. }
  62249. if (scene.activeCamera) {
  62250. serializationObject.activeCameraID = scene.activeCamera.id;
  62251. }
  62252. // Animations
  62253. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  62254. // Materials
  62255. serializationObject.materials = [];
  62256. serializationObject.multiMaterials = [];
  62257. var material;
  62258. for (index = 0; index < scene.materials.length; index++) {
  62259. material = scene.materials[index];
  62260. if (!material.doNotSerialize) {
  62261. serializationObject.materials.push(material.serialize());
  62262. }
  62263. }
  62264. // MultiMaterials
  62265. serializationObject.multiMaterials = [];
  62266. for (index = 0; index < scene.multiMaterials.length; index++) {
  62267. var multiMaterial = scene.multiMaterials[index];
  62268. serializationObject.multiMaterials.push(multiMaterial.serialize());
  62269. }
  62270. // Skeletons
  62271. serializationObject.skeletons = [];
  62272. for (index = 0; index < scene.skeletons.length; index++) {
  62273. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  62274. }
  62275. // Geometries
  62276. serializationObject.geometries = {};
  62277. serializationObject.geometries.boxes = [];
  62278. serializationObject.geometries.spheres = [];
  62279. serializationObject.geometries.cylinders = [];
  62280. serializationObject.geometries.toruses = [];
  62281. serializationObject.geometries.grounds = [];
  62282. serializationObject.geometries.planes = [];
  62283. serializationObject.geometries.torusKnots = [];
  62284. serializationObject.geometries.vertexData = [];
  62285. serializedGeometries = [];
  62286. var geometries = scene.getGeometries();
  62287. for (index = 0; index < geometries.length; index++) {
  62288. var geometry = geometries[index];
  62289. if (geometry.isReady()) {
  62290. serializeGeometry(geometry, serializationObject.geometries);
  62291. }
  62292. }
  62293. // Meshes
  62294. serializationObject.meshes = [];
  62295. for (index = 0; index < scene.meshes.length; index++) {
  62296. var abstractMesh = scene.meshes[index];
  62297. if (abstractMesh instanceof BABYLON.Mesh) {
  62298. var mesh = abstractMesh;
  62299. if (!mesh.doNotSerialize) {
  62300. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  62301. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  62302. }
  62303. }
  62304. }
  62305. }
  62306. // Particles Systems
  62307. serializationObject.particleSystems = [];
  62308. for (index = 0; index < scene.particleSystems.length; index++) {
  62309. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  62310. }
  62311. // Lens flares
  62312. serializationObject.lensFlareSystems = [];
  62313. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  62314. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  62315. }
  62316. // Shadows
  62317. serializationObject.shadowGenerators = [];
  62318. for (index = 0; index < scene.lights.length; index++) {
  62319. light = scene.lights[index];
  62320. var shadowGenerator = light.getShadowGenerator();
  62321. // Only support serialization for official generator so far.
  62322. if (shadowGenerator && shadowGenerator instanceof BABYLON.ShadowGenerator) {
  62323. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  62324. }
  62325. }
  62326. // Action Manager
  62327. if (scene.actionManager) {
  62328. serializationObject.actions = scene.actionManager.serialize("scene");
  62329. }
  62330. // Audio
  62331. serializationObject.sounds = [];
  62332. for (index = 0; index < scene.soundTracks.length; index++) {
  62333. var soundtrack = scene.soundTracks[index];
  62334. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  62335. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  62336. }
  62337. }
  62338. return serializationObject;
  62339. };
  62340. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  62341. if (withParents === void 0) { withParents = false; }
  62342. if (withChildren === void 0) { withChildren = false; }
  62343. var serializationObject = {};
  62344. SceneSerializer.ClearCache();
  62345. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  62346. if (withParents || withChildren) {
  62347. //deliberate for loop! not for each, appended should be processed as well.
  62348. for (var i = 0; i < toSerialize.length; ++i) {
  62349. if (withChildren) {
  62350. toSerialize[i].getDescendants().forEach(function (node) {
  62351. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  62352. toSerialize.push(node);
  62353. }
  62354. });
  62355. }
  62356. //make sure the array doesn't contain the object already
  62357. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  62358. toSerialize.push(toSerialize[i].parent);
  62359. }
  62360. }
  62361. }
  62362. toSerialize.forEach(function (mesh) {
  62363. finalizeSingleMesh(mesh, serializationObject);
  62364. });
  62365. return serializationObject;
  62366. };
  62367. return SceneSerializer;
  62368. }());
  62369. BABYLON.SceneSerializer = SceneSerializer;
  62370. })(BABYLON || (BABYLON = {}));
  62371. //# sourceMappingURL=babylon.sceneSerializer.js.map
  62372. var BABYLON;
  62373. (function (BABYLON) {
  62374. var ReflectionProbe = (function () {
  62375. function ReflectionProbe(name, size, scene, generateMipMaps) {
  62376. if (generateMipMaps === void 0) { generateMipMaps = true; }
  62377. var _this = this;
  62378. this.name = name;
  62379. this._viewMatrix = BABYLON.Matrix.Identity();
  62380. this._target = BABYLON.Vector3.Zero();
  62381. this._add = BABYLON.Vector3.Zero();
  62382. this.invertYAxis = false;
  62383. this.position = BABYLON.Vector3.Zero();
  62384. this._scene = scene;
  62385. this._scene.reflectionProbes.push(this);
  62386. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  62387. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  62388. switch (faceIndex) {
  62389. case 0:
  62390. _this._add.copyFromFloats(1, 0, 0);
  62391. break;
  62392. case 1:
  62393. _this._add.copyFromFloats(-1, 0, 0);
  62394. break;
  62395. case 2:
  62396. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  62397. break;
  62398. case 3:
  62399. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  62400. break;
  62401. case 4:
  62402. _this._add.copyFromFloats(0, 0, 1);
  62403. break;
  62404. case 5:
  62405. _this._add.copyFromFloats(0, 0, -1);
  62406. break;
  62407. }
  62408. if (_this._attachedMesh) {
  62409. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  62410. }
  62411. _this.position.addToRef(_this._add, _this._target);
  62412. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  62413. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  62414. });
  62415. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  62416. scene.updateTransformMatrix(true);
  62417. });
  62418. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  62419. }
  62420. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  62421. get: function () {
  62422. return this._renderTargetTexture.samples;
  62423. },
  62424. set: function (value) {
  62425. this._renderTargetTexture.samples = value;
  62426. },
  62427. enumerable: true,
  62428. configurable: true
  62429. });
  62430. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  62431. get: function () {
  62432. return this._renderTargetTexture.refreshRate;
  62433. },
  62434. set: function (value) {
  62435. this._renderTargetTexture.refreshRate = value;
  62436. },
  62437. enumerable: true,
  62438. configurable: true
  62439. });
  62440. ReflectionProbe.prototype.getScene = function () {
  62441. return this._scene;
  62442. };
  62443. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  62444. get: function () {
  62445. return this._renderTargetTexture;
  62446. },
  62447. enumerable: true,
  62448. configurable: true
  62449. });
  62450. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  62451. get: function () {
  62452. return this._renderTargetTexture.renderList;
  62453. },
  62454. enumerable: true,
  62455. configurable: true
  62456. });
  62457. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  62458. this._attachedMesh = mesh;
  62459. };
  62460. ReflectionProbe.prototype.dispose = function () {
  62461. var index = this._scene.reflectionProbes.indexOf(this);
  62462. if (index !== -1) {
  62463. // Remove from the scene if found
  62464. this._scene.reflectionProbes.splice(index, 1);
  62465. }
  62466. if (this._renderTargetTexture) {
  62467. this._renderTargetTexture.dispose();
  62468. this._renderTargetTexture = null;
  62469. }
  62470. };
  62471. return ReflectionProbe;
  62472. }());
  62473. BABYLON.ReflectionProbe = ReflectionProbe;
  62474. })(BABYLON || (BABYLON = {}));
  62475. //# sourceMappingURL=babylon.reflectionProbe.js.map
  62476. var BABYLON;
  62477. (function (BABYLON) {
  62478. var Layer = (function () {
  62479. function Layer(name, imgUrl, scene, isBackground, color) {
  62480. this.name = name;
  62481. this.scale = new BABYLON.Vector2(1, 1);
  62482. this.offset = new BABYLON.Vector2(0, 0);
  62483. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  62484. this._vertexBuffers = {};
  62485. // Events
  62486. /**
  62487. * An event triggered when the layer is disposed.
  62488. * @type {BABYLON.Observable}
  62489. */
  62490. this.onDisposeObservable = new BABYLON.Observable();
  62491. /**
  62492. * An event triggered before rendering the scene
  62493. * @type {BABYLON.Observable}
  62494. */
  62495. this.onBeforeRenderObservable = new BABYLON.Observable();
  62496. /**
  62497. * An event triggered after rendering the scene
  62498. * @type {BABYLON.Observable}
  62499. */
  62500. this.onAfterRenderObservable = new BABYLON.Observable();
  62501. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  62502. this.isBackground = isBackground === undefined ? true : isBackground;
  62503. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  62504. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  62505. this._scene.layers.push(this);
  62506. var engine = scene.getEngine();
  62507. // VBO
  62508. var vertices = [];
  62509. vertices.push(1, 1);
  62510. vertices.push(-1, 1);
  62511. vertices.push(-1, -1);
  62512. vertices.push(1, -1);
  62513. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  62514. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  62515. // Indices
  62516. var indices = [];
  62517. indices.push(0);
  62518. indices.push(1);
  62519. indices.push(2);
  62520. indices.push(0);
  62521. indices.push(2);
  62522. indices.push(3);
  62523. this._indexBuffer = engine.createIndexBuffer(indices);
  62524. // Effects
  62525. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  62526. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  62527. }
  62528. Object.defineProperty(Layer.prototype, "onDispose", {
  62529. set: function (callback) {
  62530. if (this._onDisposeObserver) {
  62531. this.onDisposeObservable.remove(this._onDisposeObserver);
  62532. }
  62533. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  62534. },
  62535. enumerable: true,
  62536. configurable: true
  62537. });
  62538. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  62539. set: function (callback) {
  62540. if (this._onBeforeRenderObserver) {
  62541. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  62542. }
  62543. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  62544. },
  62545. enumerable: true,
  62546. configurable: true
  62547. });
  62548. Object.defineProperty(Layer.prototype, "onAfterRender", {
  62549. set: function (callback) {
  62550. if (this._onAfterRenderObserver) {
  62551. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  62552. }
  62553. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  62554. },
  62555. enumerable: true,
  62556. configurable: true
  62557. });
  62558. Layer.prototype.render = function () {
  62559. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  62560. // Check
  62561. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  62562. return;
  62563. var engine = this._scene.getEngine();
  62564. this.onBeforeRenderObservable.notifyObservers(this);
  62565. // Render
  62566. engine.enableEffect(currentEffect);
  62567. engine.setState(false);
  62568. // Texture
  62569. currentEffect.setTexture("textureSampler", this.texture);
  62570. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  62571. // Color
  62572. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  62573. // Scale / offset
  62574. currentEffect.setVector2("offset", this.offset);
  62575. currentEffect.setVector2("scale", this.scale);
  62576. // VBOs
  62577. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  62578. // Draw order
  62579. if (!this.alphaTest) {
  62580. engine.setAlphaMode(this.alphaBlendingMode);
  62581. engine.draw(true, 0, 6);
  62582. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  62583. }
  62584. else {
  62585. engine.draw(true, 0, 6);
  62586. }
  62587. this.onAfterRenderObservable.notifyObservers(this);
  62588. };
  62589. Layer.prototype.dispose = function () {
  62590. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  62591. if (vertexBuffer) {
  62592. vertexBuffer.dispose();
  62593. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  62594. }
  62595. if (this._indexBuffer) {
  62596. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  62597. this._indexBuffer = null;
  62598. }
  62599. if (this.texture) {
  62600. this.texture.dispose();
  62601. this.texture = null;
  62602. }
  62603. // Remove from scene
  62604. var index = this._scene.layers.indexOf(this);
  62605. this._scene.layers.splice(index, 1);
  62606. // Callback
  62607. this.onDisposeObservable.notifyObservers(this);
  62608. this.onDisposeObservable.clear();
  62609. this.onAfterRenderObservable.clear();
  62610. this.onBeforeRenderObservable.clear();
  62611. };
  62612. return Layer;
  62613. }());
  62614. BABYLON.Layer = Layer;
  62615. })(BABYLON || (BABYLON = {}));
  62616. //# sourceMappingURL=babylon.layer.js.map
  62617. 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}"};
  62618. 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"};
  62619. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  62620. module.exports = BABYLON;
  62621. };