babylon.max.js 3.1 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595605966059760598605996060060601606026060360604606056060660607606086060960610606116061260613606146061560616606176061860619606206062160622606236062460625606266062760628606296063060631606326063360634606356063660637606386063960640606416064260643606446064560646606476064860649606506065160652606536065460655606566065760658606596066060661606626066360664606656066660667606686066960670606716067260673606746067560676606776067860679606806068160682606836068460685606866068760688606896069060691606926069360694606956069660697606986069960700607016070260703607046070560706607076070860709607106071160712607136071460715607166071760718607196072060721607226072360724607256072660727607286072960730607316073260733607346073560736607376073860739607406074160742607436074460745607466074760748607496075060751607526075360754607556075660757607586075960760607616076260763607646076560766607676076860769607706077160772607736077460775607766077760778607796078060781607826078360784607856078660787607886078960790607916079260793607946079560796607976079860799608006080160802608036080460805608066080760808608096081060811608126081360814608156081660817608186081960820608216082260823608246082560826608276082860829608306083160832608336083460835608366083760838608396084060841608426084360844608456084660847608486084960850608516085260853608546085560856608576085860859608606086160862608636086460865608666086760868608696087060871608726087360874608756087660877608786087960880608816088260883608846088560886608876088860889608906089160892608936089460895608966089760898608996090060901609026090360904609056090660907609086090960910609116091260913609146091560916609176091860919609206092160922609236092460925609266092760928609296093060931609326093360934609356093660937609386093960940609416094260943609446094560946609476094860949609506095160952609536095460955609566095760958609596096060961609626096360964609656096660967609686096960970609716097260973609746097560976609776097860979609806098160982609836098460985609866098760988609896099060991609926099360994609956099660997609986099961000610016100261003610046100561006610076100861009610106101161012610136101461015610166101761018610196102061021610226102361024610256102661027610286102961030610316103261033610346103561036610376103861039610406104161042610436104461045610466104761048610496105061051610526105361054610556105661057610586105961060610616106261063610646106561066610676106861069610706107161072610736107461075610766107761078610796108061081610826108361084610856108661087610886108961090610916109261093610946109561096610976109861099611006110161102611036110461105611066110761108611096111061111611126111361114611156111661117611186111961120611216112261123611246112561126611276112861129611306113161132611336113461135611366113761138611396114061141611426114361144611456114661147611486114961150611516115261153611546115561156611576115861159611606116161162611636116461165611666116761168611696117061171611726117361174611756117661177611786117961180611816118261183611846118561186611876118861189611906119161192611936119461195611966119761198611996120061201612026120361204612056120661207612086120961210612116121261213612146121561216612176121861219612206122161222612236122461225612266122761228612296123061231612326123361234612356123661237612386123961240612416124261243612446124561246612476124861249612506125161252612536125461255612566125761258612596126061261612626126361264612656126661267612686126961270612716127261273612746127561276612776127861279612806128161282612836128461285612866128761288612896129061291612926129361294612956129661297612986129961300613016130261303613046130561306613076130861309613106131161312613136131461315613166131761318613196132061321613226132361324613256132661327613286132961330613316133261333613346133561336613376133861339613406134161342613436134461345613466134761348613496135061351613526135361354613556135661357613586135961360613616136261363613646136561366613676136861369613706137161372613736137461375613766137761378613796138061381613826138361384613856138661387613886138961390613916139261393613946139561396613976139861399614006140161402614036140461405614066140761408614096141061411614126141361414614156141661417614186141961420614216142261423614246142561426614276142861429614306143161432614336143461435614366143761438614396144061441614426144361444614456144661447614486144961450614516145261453614546145561456614576145861459614606146161462614636146461465614666146761468614696147061471614726147361474614756147661477614786147961480614816148261483614846148561486614876148861489614906149161492614936149461495614966149761498614996150061501615026150361504615056150661507615086150961510615116151261513615146151561516615176151861519615206152161522615236152461525615266152761528615296153061531615326153361534615356153661537615386153961540615416154261543615446154561546615476154861549615506155161552615536155461555615566155761558615596156061561615626156361564615656156661567615686156961570615716157261573615746157561576615776157861579615806158161582615836158461585615866158761588615896159061591615926159361594615956159661597615986159961600616016160261603616046160561606616076160861609616106161161612616136161461615616166161761618616196162061621616226162361624616256162661627616286162961630616316163261633616346163561636616376163861639616406164161642616436164461645616466164761648616496165061651616526165361654616556165661657616586165961660616616166261663616646166561666616676166861669616706167161672616736167461675616766167761678616796168061681616826168361684616856168661687616886168961690616916169261693616946169561696616976169861699617006170161702617036170461705617066170761708617096171061711617126171361714617156171661717617186171961720617216172261723617246172561726617276172861729617306173161732617336173461735617366173761738617396174061741617426174361744617456174661747617486174961750617516175261753617546175561756617576175861759617606176161762617636176461765617666176761768617696177061771617726177361774617756177661777617786177961780617816178261783617846178561786617876178861789617906179161792617936179461795617966179761798617996180061801618026180361804618056180661807618086180961810618116181261813618146181561816618176181861819618206182161822618236182461825618266182761828618296183061831618326183361834618356183661837618386183961840618416184261843618446184561846618476184861849618506185161852618536185461855618566185761858618596186061861618626186361864618656186661867618686186961870618716187261873618746187561876618776187861879618806188161882618836188461885618866188761888618896189061891618926189361894618956189661897618986189961900619016190261903619046190561906619076190861909619106191161912619136191461915619166191761918619196192061921619226192361924619256192661927619286192961930619316193261933619346193561936619376193861939619406194161942619436194461945619466194761948619496195061951619526195361954619556195661957619586195961960619616196261963619646196561966619676196861969619706197161972619736197461975619766197761978619796198061981619826198361984619856198661987619886198961990619916199261993619946199561996619976199861999620006200162002620036200462005620066200762008620096201062011620126201362014620156201662017620186201962020620216202262023620246202562026620276202862029620306203162032620336203462035620366203762038620396204062041620426204362044620456204662047620486204962050620516205262053620546205562056620576205862059620606206162062620636206462065620666206762068620696207062071620726207362074620756207662077620786207962080620816208262083620846208562086620876208862089620906209162092620936209462095620966209762098620996210062101621026210362104621056210662107621086210962110621116211262113621146211562116621176211862119621206212162122621236212462125621266212762128621296213062131621326213362134621356213662137621386213962140621416214262143621446214562146621476214862149621506215162152621536215462155621566215762158621596216062161621626216362164621656216662167621686216962170621716217262173621746217562176621776217862179621806218162182621836218462185621866218762188621896219062191621926219362194621956219662197621986219962200622016220262203622046220562206622076220862209622106221162212622136221462215622166221762218622196222062221622226222362224622256222662227622286222962230622316223262233622346223562236622376223862239622406224162242622436224462245622466224762248622496225062251622526225362254622556225662257622586225962260622616226262263622646226562266622676226862269622706227162272622736227462275622766227762278622796228062281622826228362284622856228662287622886228962290622916229262293622946229562296622976229862299623006230162302623036230462305623066230762308623096231062311623126231362314623156231662317623186231962320623216232262323623246232562326623276232862329623306233162332623336233462335623366233762338623396234062341623426234362344623456234662347623486234962350623516235262353623546235562356623576235862359623606236162362623636236462365623666236762368623696237062371623726237362374623756237662377623786237962380623816238262383623846238562386623876238862389623906239162392623936239462395623966239762398623996240062401624026240362404624056240662407624086240962410624116241262413624146241562416624176241862419624206242162422624236242462425624266242762428624296243062431624326243362434624356243662437624386243962440624416244262443624446244562446624476244862449624506245162452624536245462455624566245762458624596246062461624626246362464624656246662467624686246962470624716247262473624746247562476624776247862479624806248162482624836248462485624866248762488624896249062491624926249362494624956249662497624986249962500625016250262503625046250562506625076250862509625106251162512625136251462515625166251762518625196252062521625226252362524625256252662527625286252962530625316253262533625346253562536625376253862539625406254162542625436254462545625466254762548625496255062551625526255362554625556255662557625586255962560625616256262563625646256562566625676256862569625706257162572625736257462575625766257762578625796258062581625826258362584625856258662587625886258962590625916259262593625946259562596625976259862599626006260162602626036260462605626066260762608626096261062611626126261362614626156261662617626186261962620626216262262623626246262562626626276262862629626306263162632626336263462635626366263762638626396264062641626426264362644626456264662647626486264962650626516265262653626546265562656626576265862659626606266162662626636266462665626666266762668626696267062671626726267362674626756267662677626786267962680626816268262683626846268562686626876268862689626906269162692626936269462695626966269762698626996270062701627026270362704627056270662707627086270962710627116271262713627146271562716627176271862719627206272162722627236272462725627266272762728627296273062731627326273362734627356273662737627386273962740627416274262743627446274562746627476274862749627506275162752627536275462755627566275762758627596276062761627626276362764627656276662767627686276962770627716277262773627746277562776627776277862779627806278162782627836278462785627866278762788627896279062791627926279362794627956279662797627986279962800628016280262803628046280562806628076280862809628106281162812628136281462815628166281762818628196282062821628226282362824628256282662827628286282962830628316283262833628346283562836628376283862839628406284162842628436284462845628466284762848628496285062851628526285362854628556285662857628586285962860628616286262863628646286562866628676286862869628706287162872628736287462875628766287762878628796288062881628826288362884628856288662887628886288962890628916289262893628946289562896628976289862899629006290162902629036290462905629066290762908629096291062911629126291362914629156291662917629186291962920629216292262923629246292562926629276292862929629306293162932629336293462935629366293762938629396294062941629426294362944629456294662947629486294962950629516295262953629546295562956629576295862959629606296162962629636296462965629666296762968629696297062971629726297362974629756297662977629786297962980629816298262983629846298562986629876298862989629906299162992629936299462995629966299762998629996300063001630026300363004630056300663007630086300963010630116301263013630146301563016630176301863019630206302163022630236302463025630266302763028630296303063031630326303363034630356303663037630386303963040630416304263043630446304563046630476304863049630506305163052630536305463055630566305763058630596306063061630626306363064630656306663067630686306963070630716307263073630746307563076630776307863079630806308163082630836308463085630866308763088630896309063091630926309363094630956309663097630986309963100631016310263103631046310563106631076310863109631106311163112631136311463115631166311763118631196312063121631226312363124631256312663127631286312963130631316313263133631346313563136631376313863139631406314163142631436314463145631466314763148631496315063151631526315363154631556315663157631586315963160631616316263163631646316563166631676316863169631706317163172631736317463175631766317763178631796318063181631826318363184631856318663187631886318963190631916319263193631946319563196631976319863199632006320163202632036320463205632066320763208632096321063211632126321363214632156321663217632186321963220632216322263223632246322563226632276322863229632306323163232632336323463235632366323763238632396324063241632426324363244632456324663247632486324963250632516325263253632546325563256632576325863259632606326163262632636326463265632666326763268632696327063271632726327363274632756327663277632786327963280632816328263283632846328563286632876328863289632906329163292632936329463295632966329763298632996330063301633026330363304633056330663307633086330963310633116331263313633146331563316633176331863319633206332163322633236332463325633266332763328633296333063331633326333363334633356333663337633386333963340633416334263343633446334563346633476334863349633506335163352633536335463355633566335763358633596336063361633626336363364633656336663367633686336963370633716337263373633746337563376633776337863379633806338163382633836338463385633866338763388633896339063391633926339363394633956339663397633986339963400634016340263403634046340563406634076340863409634106341163412634136341463415634166341763418634196342063421634226342363424634256342663427634286342963430634316343263433634346343563436634376343863439634406344163442634436344463445634466344763448634496345063451634526345363454634556345663457634586345963460634616346263463634646346563466634676346863469634706347163472634736347463475634766347763478634796348063481634826348363484634856348663487634886348963490634916349263493634946349563496634976349863499635006350163502635036350463505635066350763508635096351063511635126351363514635156351663517635186351963520635216352263523635246352563526635276352863529635306353163532635336353463535635366353763538635396354063541635426354363544635456354663547635486354963550635516355263553635546355563556635576355863559635606356163562635636356463565635666356763568635696357063571635726357363574635756357663577635786357963580635816358263583635846358563586635876358863589635906359163592635936359463595635966359763598635996360063601636026360363604636056360663607636086360963610636116361263613636146361563616636176361863619636206362163622636236362463625636266362763628636296363063631636326363363634636356363663637636386363963640636416364263643636446364563646636476364863649636506365163652636536365463655636566365763658636596366063661636626366363664636656366663667636686366963670636716367263673636746367563676636776367863679636806368163682
  1. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  2. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  3. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  4. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  5. return c > 3 && r && Object.defineProperty(target, key, r), r;
  6. };
  7. var __extends = (this && this.__extends) || (function () {
  8. var extendStatics = Object.setPrototypeOf ||
  9. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  10. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  11. return function (d, b) {
  12. extendStatics(d, b);
  13. function __() { this.constructor = d; }
  14. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  15. };
  16. })();
  17. var BABYLON;
  18. (function (BABYLON) {
  19. BABYLON.ToGammaSpace = 1 / 2.2;
  20. BABYLON.ToLinearSpace = 2.2;
  21. BABYLON.Epsilon = 0.001;
  22. var MathTools = (function () {
  23. function MathTools() {
  24. }
  25. /**
  26. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  27. */
  28. MathTools.WithinEpsilon = function (a, b, epsilon) {
  29. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  30. var num = a - b;
  31. return -epsilon <= num && num <= epsilon;
  32. };
  33. /**
  34. * Returns a string : the upper case translation of the number i to hexadecimal.
  35. */
  36. MathTools.ToHex = function (i) {
  37. var str = i.toString(16);
  38. if (i <= 15) {
  39. return ("0" + str).toUpperCase();
  40. }
  41. return str.toUpperCase();
  42. };
  43. /**
  44. * Returns -1 if value is negative and +1 is value is positive.
  45. * Returns the value itself if it's equal to zero.
  46. */
  47. MathTools.Sign = function (value) {
  48. value = +value; // convert to a number
  49. if (value === 0 || isNaN(value))
  50. return value;
  51. return value > 0 ? 1 : -1;
  52. };
  53. /**
  54. * Returns the value itself if it's between min and max.
  55. * Returns min if the value is lower than min.
  56. * Returns max if the value is greater than max.
  57. */
  58. MathTools.Clamp = function (value, min, max) {
  59. if (min === void 0) { min = 0; }
  60. if (max === void 0) { max = 1; }
  61. return Math.min(max, Math.max(min, value));
  62. };
  63. return MathTools;
  64. }());
  65. BABYLON.MathTools = MathTools;
  66. var Scalar = (function () {
  67. function Scalar() {
  68. }
  69. /**
  70. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  71. */
  72. Scalar.Lerp = function (start, end, amount) {
  73. return start + ((end - start) * amount);
  74. };
  75. /**
  76. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  77. */
  78. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  79. var squared = amount * amount;
  80. var cubed = amount * squared;
  81. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  82. var part2 = (-2.0 * cubed) + (3.0 * squared);
  83. var part3 = (cubed - (2.0 * squared)) + amount;
  84. var part4 = cubed - squared;
  85. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  86. };
  87. return Scalar;
  88. }());
  89. BABYLON.Scalar = Scalar;
  90. var Color3 = (function () {
  91. /**
  92. * Creates a new Color3 object from red, green, blue values, all between 0 and 1.
  93. */
  94. function Color3(r, g, b) {
  95. if (r === void 0) { r = 0; }
  96. if (g === void 0) { g = 0; }
  97. if (b === void 0) { b = 0; }
  98. this.r = r;
  99. this.g = g;
  100. this.b = b;
  101. }
  102. /**
  103. * Returns a string with the Color3 current values.
  104. */
  105. Color3.prototype.toString = function () {
  106. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  107. };
  108. /**
  109. * Returns the string "Color3".
  110. */
  111. Color3.prototype.getClassName = function () {
  112. return "Color3";
  113. };
  114. /**
  115. * Returns the Color3 hash code.
  116. */
  117. Color3.prototype.getHashCode = function () {
  118. var hash = this.r || 0;
  119. hash = (hash * 397) ^ (this.g || 0);
  120. hash = (hash * 397) ^ (this.b || 0);
  121. return hash;
  122. };
  123. // Operators
  124. /**
  125. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements.
  126. * Returns the Color3.
  127. */
  128. Color3.prototype.toArray = function (array, index) {
  129. if (index === undefined) {
  130. index = 0;
  131. }
  132. array[index] = this.r;
  133. array[index + 1] = this.g;
  134. array[index + 2] = this.b;
  135. return this;
  136. };
  137. /**
  138. * Returns a new Color4 object from the current Color3 and the passed alpha.
  139. */
  140. Color3.prototype.toColor4 = function (alpha) {
  141. if (alpha === void 0) { alpha = 1; }
  142. return new Color4(this.r, this.g, this.b, alpha);
  143. };
  144. /**
  145. * Returns a new array populated with 3 numeric elements : red, green and blue values.
  146. */
  147. Color3.prototype.asArray = function () {
  148. var result = [];
  149. this.toArray(result, 0);
  150. return result;
  151. };
  152. /**
  153. * Returns the luminance value (float).
  154. */
  155. Color3.prototype.toLuminance = function () {
  156. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  157. };
  158. /**
  159. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object.
  160. * Returns this new object.
  161. */
  162. Color3.prototype.multiply = function (otherColor) {
  163. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  164. };
  165. /**
  166. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result".
  167. * Returns the current Color3.
  168. */
  169. Color3.prototype.multiplyToRef = function (otherColor, result) {
  170. result.r = this.r * otherColor.r;
  171. result.g = this.g * otherColor.g;
  172. result.b = this.b * otherColor.b;
  173. return this;
  174. };
  175. /**
  176. * Boolean : True if the rgb values are equal to the passed ones.
  177. */
  178. Color3.prototype.equals = function (otherColor) {
  179. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  180. };
  181. /**
  182. * Boolean : True if the rgb values are equal to the passed ones.
  183. */
  184. Color3.prototype.equalsFloats = function (r, g, b) {
  185. return this.r === r && this.g === g && this.b === b;
  186. };
  187. /**
  188. * Multiplies in place each rgb value by scale.
  189. * Returns the updated Color3.
  190. */
  191. Color3.prototype.scale = function (scale) {
  192. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  193. };
  194. /**
  195. * Multiplies the rgb values by scale and stores the result into "result".
  196. * Returns the unmodified current Color3.
  197. */
  198. Color3.prototype.scaleToRef = function (scale, result) {
  199. result.r = this.r * scale;
  200. result.g = this.g * scale;
  201. result.b = this.b * scale;
  202. return this;
  203. };
  204. /**
  205. * Returns a new Color3 set with the added values of the current Color3 and of the passed one.
  206. */
  207. Color3.prototype.add = function (otherColor) {
  208. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  209. };
  210. /**
  211. * Stores the result of the addition of the current Color3 and passed one rgb values into "result".
  212. * Returns the unmodified current Color3.
  213. */
  214. Color3.prototype.addToRef = function (otherColor, result) {
  215. result.r = this.r + otherColor.r;
  216. result.g = this.g + otherColor.g;
  217. result.b = this.b + otherColor.b;
  218. return this;
  219. };
  220. /**
  221. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3 .
  222. */
  223. Color3.prototype.subtract = function (otherColor) {
  224. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  225. };
  226. /**
  227. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result".
  228. * Returns the unmodified current Color3.
  229. */
  230. Color3.prototype.subtractToRef = function (otherColor, result) {
  231. result.r = this.r - otherColor.r;
  232. result.g = this.g - otherColor.g;
  233. result.b = this.b - otherColor.b;
  234. return this;
  235. };
  236. /**
  237. * Returns a new Color3 copied the current one.
  238. */
  239. Color3.prototype.clone = function () {
  240. return new Color3(this.r, this.g, this.b);
  241. };
  242. /**
  243. * Copies the rgb values from the source in the current Color3.
  244. * Returns the updated Color3.
  245. */
  246. Color3.prototype.copyFrom = function (source) {
  247. this.r = source.r;
  248. this.g = source.g;
  249. this.b = source.b;
  250. return this;
  251. };
  252. /**
  253. * Updates the Color3 rgb values from the passed floats.
  254. * Returns the Color3.
  255. */
  256. Color3.prototype.copyFromFloats = function (r, g, b) {
  257. this.r = r;
  258. this.g = g;
  259. this.b = b;
  260. return this;
  261. };
  262. /**
  263. * Updates the Color3 rgb values from the passed floats.
  264. * Returns the Color3.
  265. */
  266. Color3.prototype.set = function (r, g, b) {
  267. return this.copyFromFloats(r, g, b);
  268. };
  269. /**
  270. * Returns the Color3 hexadecimal code as a string.
  271. */
  272. Color3.prototype.toHexString = function () {
  273. var intR = (this.r * 255) | 0;
  274. var intG = (this.g * 255) | 0;
  275. var intB = (this.b * 255) | 0;
  276. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB);
  277. };
  278. /**
  279. * Returns a new Color3 converted to linear space.
  280. */
  281. Color3.prototype.toLinearSpace = function () {
  282. var convertedColor = new Color3();
  283. this.toLinearSpaceToRef(convertedColor);
  284. return convertedColor;
  285. };
  286. /**
  287. * Converts the Color3 values to linear space and stores the result in "convertedColor".
  288. * Returns the unmodified Color3.
  289. */
  290. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  291. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  292. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  293. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  294. return this;
  295. };
  296. /**
  297. * Returns a new Color3 converted to gamma space.
  298. */
  299. Color3.prototype.toGammaSpace = function () {
  300. var convertedColor = new Color3();
  301. this.toGammaSpaceToRef(convertedColor);
  302. return convertedColor;
  303. };
  304. /**
  305. * Converts the Color3 values to gamma space and stores the result in "convertedColor".
  306. * Returns the unmodified Color3.
  307. */
  308. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  309. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  310. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  311. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  312. return this;
  313. };
  314. // Statics
  315. /**
  316. * Creates a new Color3 from the string containing valid hexadecimal values.
  317. */
  318. Color3.FromHexString = function (hex) {
  319. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  320. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  321. return new Color3(0, 0, 0);
  322. }
  323. var r = parseInt(hex.substring(1, 3), 16);
  324. var g = parseInt(hex.substring(3, 5), 16);
  325. var b = parseInt(hex.substring(5, 7), 16);
  326. return Color3.FromInts(r, g, b);
  327. };
  328. /**
  329. * Creates a new Vector3 from the startind index of the passed array.
  330. */
  331. Color3.FromArray = function (array, offset) {
  332. if (offset === void 0) { offset = 0; }
  333. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  334. };
  335. /**
  336. * Creates a new Color3 from integer values ( < 256).
  337. */
  338. Color3.FromInts = function (r, g, b) {
  339. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  340. };
  341. /**
  342. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3.
  343. */
  344. Color3.Lerp = function (start, end, amount) {
  345. var r = start.r + ((end.r - start.r) * amount);
  346. var g = start.g + ((end.g - start.g) * amount);
  347. var b = start.b + ((end.b - start.b) * amount);
  348. return new Color3(r, g, b);
  349. };
  350. Color3.Red = function () { return new Color3(1, 0, 0); };
  351. Color3.Green = function () { return new Color3(0, 1, 0); };
  352. Color3.Blue = function () { return new Color3(0, 0, 1); };
  353. Color3.Black = function () { return new Color3(0, 0, 0); };
  354. Color3.White = function () { return new Color3(1, 1, 1); };
  355. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  356. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  357. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  358. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  359. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  360. return Color3;
  361. }());
  362. BABYLON.Color3 = Color3;
  363. var Color4 = (function () {
  364. /**
  365. * Creates a new Color4 object from the passed float values ( < 1) : red, green, blue, alpha.
  366. */
  367. function Color4(r, g, b, a) {
  368. this.r = r;
  369. this.g = g;
  370. this.b = b;
  371. this.a = a;
  372. }
  373. // Operators
  374. /**
  375. * Adds in place the passed Color4 values to the current Color4.
  376. * Returns the updated Color4.
  377. */
  378. Color4.prototype.addInPlace = function (right) {
  379. this.r += right.r;
  380. this.g += right.g;
  381. this.b += right.b;
  382. this.a += right.a;
  383. return this;
  384. };
  385. /**
  386. * Returns a new array populated with 4 numeric elements : red, green, blue, alpha values.
  387. */
  388. Color4.prototype.asArray = function () {
  389. var result = [];
  390. this.toArray(result, 0);
  391. return result;
  392. };
  393. /**
  394. * Stores from the starting index in the passed array the Color4 successive values.
  395. * Returns the Color4.
  396. */
  397. Color4.prototype.toArray = function (array, index) {
  398. if (index === undefined) {
  399. index = 0;
  400. }
  401. array[index] = this.r;
  402. array[index + 1] = this.g;
  403. array[index + 2] = this.b;
  404. array[index + 3] = this.a;
  405. return this;
  406. };
  407. /**
  408. * Returns a new Color4 set with the added values of the current Color4 and of the passed one.
  409. */
  410. Color4.prototype.add = function (right) {
  411. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  412. };
  413. /**
  414. * Returns a new Color4 set with the subtracted values of the passed one from the current Color4.
  415. */
  416. Color4.prototype.subtract = function (right) {
  417. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  418. };
  419. /**
  420. * Subtracts the passed ones from the current Color4 values and stores the results in "result".
  421. * Returns the Color4.
  422. */
  423. Color4.prototype.subtractToRef = function (right, result) {
  424. result.r = this.r - right.r;
  425. result.g = this.g - right.g;
  426. result.b = this.b - right.b;
  427. result.a = this.a - right.a;
  428. return this;
  429. };
  430. /**
  431. * Creates a new Color4 with the current Color4 values multiplied by scale.
  432. */
  433. Color4.prototype.scale = function (scale) {
  434. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  435. };
  436. /**
  437. * Multiplies the current Color4 values by scale and stores the result in "result".
  438. * Returns the Color4.
  439. */
  440. Color4.prototype.scaleToRef = function (scale, result) {
  441. result.r = this.r * scale;
  442. result.g = this.g * scale;
  443. result.b = this.b * scale;
  444. result.a = this.a * scale;
  445. return this;
  446. };
  447. /**
  448. * Multipy an RGBA Color4 value by another and return a new Color4 object
  449. * @param color The Color4 (RGBA) value to multiply by
  450. * @returns A new Color4.
  451. */
  452. Color4.prototype.multiply = function (color) {
  453. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  454. };
  455. /**
  456. * Multipy an RGBA Color4 value by another and push the result in a reference value
  457. * @param color The Color4 (RGBA) value to multiply by
  458. * @param result The Color4 (RGBA) to fill the result in
  459. * @returns the result Color4.
  460. */
  461. Color4.prototype.multiplyToRef = function (color, result) {
  462. result.r = this.r * color.r;
  463. result.g = this.g * color.g;
  464. result.b = this.b * color.b;
  465. result.a = this.a * color.a;
  466. return result;
  467. };
  468. /**
  469. * Returns a string with the Color4 values.
  470. */
  471. Color4.prototype.toString = function () {
  472. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  473. };
  474. /**
  475. * Returns the string "Color4"
  476. */
  477. Color4.prototype.getClassName = function () {
  478. return "Color4";
  479. };
  480. /**
  481. * Return the Color4 hash code as a number.
  482. */
  483. Color4.prototype.getHashCode = function () {
  484. var hash = this.r || 0;
  485. hash = (hash * 397) ^ (this.g || 0);
  486. hash = (hash * 397) ^ (this.b || 0);
  487. hash = (hash * 397) ^ (this.a || 0);
  488. return hash;
  489. };
  490. /**
  491. * Creates a new Color4 copied from the current one.
  492. */
  493. Color4.prototype.clone = function () {
  494. return new Color4(this.r, this.g, this.b, this.a);
  495. };
  496. /**
  497. * Copies the passed Color4 values into the current one.
  498. * Returns the updated Color4.
  499. */
  500. Color4.prototype.copyFrom = function (source) {
  501. this.r = source.r;
  502. this.g = source.g;
  503. this.b = source.b;
  504. this.a = source.a;
  505. return this;
  506. };
  507. /**
  508. * Copies the passed float values into the current one.
  509. * Returns the updated Color4.
  510. */
  511. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  512. this.r = r;
  513. this.g = g;
  514. this.b = b;
  515. this.a = a;
  516. return this;
  517. };
  518. /**
  519. * Copies the passed float values into the current one.
  520. * Returns the updated Color4.
  521. */
  522. Color4.prototype.set = function (r, g, b, a) {
  523. return this.copyFromFloats(r, g, b, a);
  524. };
  525. /**
  526. * Returns a string containing the hexadecimal Color4 code.
  527. */
  528. Color4.prototype.toHexString = function () {
  529. var intR = (this.r * 255) | 0;
  530. var intG = (this.g * 255) | 0;
  531. var intB = (this.b * 255) | 0;
  532. var intA = (this.a * 255) | 0;
  533. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB) + MathTools.ToHex(intA);
  534. };
  535. // Statics
  536. /**
  537. * Creates a new Color4 from the valid hexadecimal value contained in the passed string.
  538. */
  539. Color4.FromHexString = function (hex) {
  540. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  541. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  542. return new Color4(0.0, 0.0, 0.0, 0.0);
  543. }
  544. var r = parseInt(hex.substring(1, 3), 16);
  545. var g = parseInt(hex.substring(3, 5), 16);
  546. var b = parseInt(hex.substring(5, 7), 16);
  547. var a = parseInt(hex.substring(7, 9), 16);
  548. return Color4.FromInts(r, g, b, a);
  549. };
  550. /**
  551. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  552. */
  553. Color4.Lerp = function (left, right, amount) {
  554. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  555. Color4.LerpToRef(left, right, amount, result);
  556. return result;
  557. };
  558. /**
  559. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  560. */
  561. Color4.LerpToRef = function (left, right, amount, result) {
  562. result.r = left.r + (right.r - left.r) * amount;
  563. result.g = left.g + (right.g - left.g) * amount;
  564. result.b = left.b + (right.b - left.b) * amount;
  565. result.a = left.a + (right.a - left.a) * amount;
  566. };
  567. /**
  568. * Creates a new Color4 from the starting index element of the passed array.
  569. */
  570. Color4.FromArray = function (array, offset) {
  571. if (offset === void 0) { offset = 0; }
  572. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  573. };
  574. /**
  575. * Creates a new Color4 from the passed integers ( < 256 ).
  576. */
  577. Color4.FromInts = function (r, g, b, a) {
  578. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  579. };
  580. Color4.CheckColors4 = function (colors, count) {
  581. // Check if color3 was used
  582. if (colors.length === count * 3) {
  583. var colors4 = [];
  584. for (var index = 0; index < colors.length; index += 3) {
  585. var newIndex = (index / 3) * 4;
  586. colors4[newIndex] = colors[index];
  587. colors4[newIndex + 1] = colors[index + 1];
  588. colors4[newIndex + 2] = colors[index + 2];
  589. colors4[newIndex + 3] = 1.0;
  590. }
  591. return colors4;
  592. }
  593. return colors;
  594. };
  595. return Color4;
  596. }());
  597. BABYLON.Color4 = Color4;
  598. var Vector2 = (function () {
  599. /**
  600. * Creates a new Vector2 from the passed x and y coordinates.
  601. */
  602. function Vector2(x, y) {
  603. this.x = x;
  604. this.y = y;
  605. }
  606. /**
  607. * Returns a string with the Vector2 coordinates.
  608. */
  609. Vector2.prototype.toString = function () {
  610. return "{X: " + this.x + " Y:" + this.y + "}";
  611. };
  612. /**
  613. * Returns the string "Vector2"
  614. */
  615. Vector2.prototype.getClassName = function () {
  616. return "Vector2";
  617. };
  618. /**
  619. * Returns the Vector2 hash code as a number.
  620. */
  621. Vector2.prototype.getHashCode = function () {
  622. var hash = this.x || 0;
  623. hash = (hash * 397) ^ (this.y || 0);
  624. return hash;
  625. };
  626. // Operators
  627. /**
  628. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  629. * Returns the Vector2.
  630. */
  631. Vector2.prototype.toArray = function (array, index) {
  632. if (index === void 0) { index = 0; }
  633. array[index] = this.x;
  634. array[index + 1] = this.y;
  635. return this;
  636. };
  637. /**
  638. * Returns a new array with 2 elements : the Vector2 coordinates.
  639. */
  640. Vector2.prototype.asArray = function () {
  641. var result = [];
  642. this.toArray(result, 0);
  643. return result;
  644. };
  645. /**
  646. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  647. * Returns the updated Vector2.
  648. */
  649. Vector2.prototype.copyFrom = function (source) {
  650. this.x = source.x;
  651. this.y = source.y;
  652. return this;
  653. };
  654. /**
  655. * Sets the Vector2 coordinates with the passed floats.
  656. * Returns the updated Vector2.
  657. */
  658. Vector2.prototype.copyFromFloats = function (x, y) {
  659. this.x = x;
  660. this.y = y;
  661. return this;
  662. };
  663. /**
  664. * Sets the Vector2 coordinates with the passed floats.
  665. * Returns the updated Vector2.
  666. */
  667. Vector2.prototype.set = function (x, y) {
  668. return this.copyFromFloats(x, y);
  669. };
  670. /**
  671. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  672. */
  673. Vector2.prototype.add = function (otherVector) {
  674. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  675. };
  676. /**
  677. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  678. * Returns the Vector2.
  679. */
  680. Vector2.prototype.addToRef = function (otherVector, result) {
  681. result.x = this.x + otherVector.x;
  682. result.y = this.y + otherVector.y;
  683. return this;
  684. };
  685. /**
  686. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  687. * Returns the updated Vector2.
  688. */
  689. Vector2.prototype.addInPlace = function (otherVector) {
  690. this.x += otherVector.x;
  691. this.y += otherVector.y;
  692. return this;
  693. };
  694. /**
  695. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  696. */
  697. Vector2.prototype.addVector3 = function (otherVector) {
  698. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  699. };
  700. /**
  701. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  702. */
  703. Vector2.prototype.subtract = function (otherVector) {
  704. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  705. };
  706. /**
  707. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  708. * Returns the Vector2.
  709. */
  710. Vector2.prototype.subtractToRef = function (otherVector, result) {
  711. result.x = this.x - otherVector.x;
  712. result.y = this.y - otherVector.y;
  713. return this;
  714. };
  715. /**
  716. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  717. * Returns the updated Vector2.
  718. */
  719. Vector2.prototype.subtractInPlace = function (otherVector) {
  720. this.x -= otherVector.x;
  721. this.y -= otherVector.y;
  722. return this;
  723. };
  724. /**
  725. * Multiplies in place the current Vector2 coordinates by the passed ones.
  726. * Returns the updated Vector2.
  727. */
  728. Vector2.prototype.multiplyInPlace = function (otherVector) {
  729. this.x *= otherVector.x;
  730. this.y *= otherVector.y;
  731. return this;
  732. };
  733. /**
  734. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  735. */
  736. Vector2.prototype.multiply = function (otherVector) {
  737. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  738. };
  739. /**
  740. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  741. * Returns the Vector2.
  742. */
  743. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  744. result.x = this.x * otherVector.x;
  745. result.y = this.y * otherVector.y;
  746. return this;
  747. };
  748. /**
  749. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  750. */
  751. Vector2.prototype.multiplyByFloats = function (x, y) {
  752. return new Vector2(this.x * x, this.y * y);
  753. };
  754. /**
  755. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  756. */
  757. Vector2.prototype.divide = function (otherVector) {
  758. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  759. };
  760. /**
  761. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  762. * Returns the Vector2.
  763. */
  764. Vector2.prototype.divideToRef = function (otherVector, result) {
  765. result.x = this.x / otherVector.x;
  766. result.y = this.y / otherVector.y;
  767. return this;
  768. };
  769. /**
  770. * Returns a new Vector2 with current Vector2 negated coordinates.
  771. */
  772. Vector2.prototype.negate = function () {
  773. return new Vector2(-this.x, -this.y);
  774. };
  775. /**
  776. * Multiply the Vector2 coordinates by scale.
  777. * Returns the updated Vector2.
  778. */
  779. Vector2.prototype.scaleInPlace = function (scale) {
  780. this.x *= scale;
  781. this.y *= scale;
  782. return this;
  783. };
  784. /**
  785. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  786. */
  787. Vector2.prototype.scale = function (scale) {
  788. return new Vector2(this.x * scale, this.y * scale);
  789. };
  790. /**
  791. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  792. */
  793. Vector2.prototype.equals = function (otherVector) {
  794. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  795. };
  796. /**
  797. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  798. */
  799. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  800. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  801. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon);
  802. };
  803. // Properties
  804. /**
  805. * Returns the vector length (float).
  806. */
  807. Vector2.prototype.length = function () {
  808. return Math.sqrt(this.x * this.x + this.y * this.y);
  809. };
  810. /**
  811. * Returns the vector squared length (float);
  812. */
  813. Vector2.prototype.lengthSquared = function () {
  814. return (this.x * this.x + this.y * this.y);
  815. };
  816. // Methods
  817. /**
  818. * Normalize the vector.
  819. * Returns the updated Vector2.
  820. */
  821. Vector2.prototype.normalize = function () {
  822. var len = this.length();
  823. if (len === 0)
  824. return this;
  825. var num = 1.0 / len;
  826. this.x *= num;
  827. this.y *= num;
  828. return this;
  829. };
  830. /**
  831. * Returns a new Vector2 copied from the Vector2.
  832. */
  833. Vector2.prototype.clone = function () {
  834. return new Vector2(this.x, this.y);
  835. };
  836. // Statics
  837. /**
  838. * Returns a new Vector2(0, 0)
  839. */
  840. Vector2.Zero = function () {
  841. return new Vector2(0, 0);
  842. };
  843. /**
  844. * Returns a new Vector2 set from the passed index element of the passed array.
  845. */
  846. Vector2.FromArray = function (array, offset) {
  847. if (offset === void 0) { offset = 0; }
  848. return new Vector2(array[offset], array[offset + 1]);
  849. };
  850. /**
  851. * Sets "result" from the passed index element of the passed array.
  852. */
  853. Vector2.FromArrayToRef = function (array, offset, result) {
  854. result.x = array[offset];
  855. result.y = array[offset + 1];
  856. };
  857. /**
  858. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  859. */
  860. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  861. var squared = amount * amount;
  862. var cubed = amount * squared;
  863. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  864. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  865. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  866. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  867. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  868. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  869. return new Vector2(x, y);
  870. };
  871. /**
  872. * 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".
  873. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  874. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  875. */
  876. Vector2.Clamp = function (value, min, max) {
  877. var x = value.x;
  878. x = (x > max.x) ? max.x : x;
  879. x = (x < min.x) ? min.x : x;
  880. var y = value.y;
  881. y = (y > max.y) ? max.y : y;
  882. y = (y < min.y) ? min.y : y;
  883. return new Vector2(x, y);
  884. };
  885. /**
  886. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  887. */
  888. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  889. var squared = amount * amount;
  890. var cubed = amount * squared;
  891. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  892. var part2 = (-2.0 * cubed) + (3.0 * squared);
  893. var part3 = (cubed - (2.0 * squared)) + amount;
  894. var part4 = cubed - squared;
  895. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  896. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  897. return new Vector2(x, y);
  898. };
  899. /**
  900. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  901. */
  902. Vector2.Lerp = function (start, end, amount) {
  903. var x = start.x + ((end.x - start.x) * amount);
  904. var y = start.y + ((end.y - start.y) * amount);
  905. return new Vector2(x, y);
  906. };
  907. /**
  908. * Returns the dot product (float) of the vector "left" and the vector "right".
  909. */
  910. Vector2.Dot = function (left, right) {
  911. return left.x * right.x + left.y * right.y;
  912. };
  913. /**
  914. * Returns a new Vector2 equal to the normalized passed vector.
  915. */
  916. Vector2.Normalize = function (vector) {
  917. var newVector = vector.clone();
  918. newVector.normalize();
  919. return newVector;
  920. };
  921. /**
  922. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  923. */
  924. Vector2.Minimize = function (left, right) {
  925. var x = (left.x < right.x) ? left.x : right.x;
  926. var y = (left.y < right.y) ? left.y : right.y;
  927. return new Vector2(x, y);
  928. };
  929. /**
  930. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  931. */
  932. Vector2.Maximize = function (left, right) {
  933. var x = (left.x > right.x) ? left.x : right.x;
  934. var y = (left.y > right.y) ? left.y : right.y;
  935. return new Vector2(x, y);
  936. };
  937. /**
  938. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  939. */
  940. Vector2.Transform = function (vector, transformation) {
  941. var r = Vector2.Zero();
  942. Vector2.TransformToRef(vector, transformation, r);
  943. return r;
  944. };
  945. /**
  946. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  947. */
  948. Vector2.TransformToRef = function (vector, transformation, result) {
  949. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  950. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  951. result.x = x;
  952. result.y = y;
  953. };
  954. /**
  955. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  956. */
  957. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  958. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  959. var sign = a < 0 ? -1 : 1;
  960. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  961. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  962. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  963. };
  964. /**
  965. * Returns the distance (float) between the vectors "value1" and "value2".
  966. */
  967. Vector2.Distance = function (value1, value2) {
  968. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  969. };
  970. /**
  971. * Returns the squared distance (float) between the vectors "value1" and "value2".
  972. */
  973. Vector2.DistanceSquared = function (value1, value2) {
  974. var x = value1.x - value2.x;
  975. var y = value1.y - value2.y;
  976. return (x * x) + (y * y);
  977. };
  978. /**
  979. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  980. */
  981. Vector2.Center = function (value1, value2) {
  982. var center = value1.add(value2);
  983. center.scaleInPlace(0.5);
  984. return center;
  985. };
  986. /**
  987. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  988. */
  989. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  990. var l2 = Vector2.DistanceSquared(segA, segB);
  991. if (l2 === 0.0) {
  992. return Vector2.Distance(p, segA);
  993. }
  994. var v = segB.subtract(segA);
  995. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  996. var proj = segA.add(v.multiplyByFloats(t, t));
  997. return Vector2.Distance(p, proj);
  998. };
  999. return Vector2;
  1000. }());
  1001. BABYLON.Vector2 = Vector2;
  1002. var Vector3 = (function () {
  1003. /**
  1004. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  1005. * A Vector3 is the main object used in 3D geometry.
  1006. * It can represent etiher the coordinates of a point the space, either a direction.
  1007. */
  1008. function Vector3(x, y, z) {
  1009. this.x = x;
  1010. this.y = y;
  1011. this.z = z;
  1012. }
  1013. /**
  1014. * Returns a string with the Vector3 coordinates.
  1015. */
  1016. Vector3.prototype.toString = function () {
  1017. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  1018. };
  1019. /**
  1020. * Returns the string "Vector3"
  1021. */
  1022. Vector3.prototype.getClassName = function () {
  1023. return "Vector3";
  1024. };
  1025. /**
  1026. * Returns the Vector hash code.
  1027. */
  1028. Vector3.prototype.getHashCode = function () {
  1029. var hash = this.x || 0;
  1030. hash = (hash * 397) ^ (this.y || 0);
  1031. hash = (hash * 397) ^ (this.z || 0);
  1032. return hash;
  1033. };
  1034. // Operators
  1035. /**
  1036. * Returns a new array with three elements : the coordinates the Vector3.
  1037. */
  1038. Vector3.prototype.asArray = function () {
  1039. var result = [];
  1040. this.toArray(result, 0);
  1041. return result;
  1042. };
  1043. /**
  1044. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3.
  1045. * Returns the Vector3.
  1046. */
  1047. Vector3.prototype.toArray = function (array, index) {
  1048. if (index === void 0) { index = 0; }
  1049. array[index] = this.x;
  1050. array[index + 1] = this.y;
  1051. array[index + 2] = this.z;
  1052. return this;
  1053. };
  1054. /**
  1055. * Returns a new Quaternion object, computed from the Vector3 coordinates.
  1056. */
  1057. Vector3.prototype.toQuaternion = function () {
  1058. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  1059. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  1060. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  1061. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  1062. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  1063. var cosy = Math.cos(this.y * 0.5);
  1064. var siny = Math.sin(this.y * 0.5);
  1065. result.x = coszMinusx * siny;
  1066. result.y = -sinzMinusx * siny;
  1067. result.z = sinxPlusz * cosy;
  1068. result.w = cosxPlusz * cosy;
  1069. return result;
  1070. };
  1071. /**
  1072. * Adds the passed vector to the current Vector3.
  1073. * Returns the updated Vector3.
  1074. */
  1075. Vector3.prototype.addInPlace = function (otherVector) {
  1076. this.x += otherVector.x;
  1077. this.y += otherVector.y;
  1078. this.z += otherVector.z;
  1079. return this;
  1080. };
  1081. /**
  1082. * Returns a new Vector3, result of the addition the current Vector3 and the passed vector.
  1083. */
  1084. Vector3.prototype.add = function (otherVector) {
  1085. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  1086. };
  1087. /**
  1088. * Adds the current Vector3 to the passed one and stores the result in the vector "result".
  1089. * Returns the current Vector3.
  1090. */
  1091. Vector3.prototype.addToRef = function (otherVector, result) {
  1092. result.x = this.x + otherVector.x;
  1093. result.y = this.y + otherVector.y;
  1094. result.z = this.z + otherVector.z;
  1095. return this;
  1096. };
  1097. /**
  1098. * Subtract the passed vector from the current Vector3.
  1099. * Returns the updated Vector3.
  1100. */
  1101. Vector3.prototype.subtractInPlace = function (otherVector) {
  1102. this.x -= otherVector.x;
  1103. this.y -= otherVector.y;
  1104. this.z -= otherVector.z;
  1105. return this;
  1106. };
  1107. /**
  1108. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3.
  1109. */
  1110. Vector3.prototype.subtract = function (otherVector) {
  1111. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  1112. };
  1113. /**
  1114. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  1115. * Returns the current Vector3.
  1116. */
  1117. Vector3.prototype.subtractToRef = function (otherVector, result) {
  1118. result.x = this.x - otherVector.x;
  1119. result.y = this.y - otherVector.y;
  1120. result.z = this.z - otherVector.z;
  1121. return this;
  1122. };
  1123. /**
  1124. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates.
  1125. */
  1126. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  1127. return new Vector3(this.x - x, this.y - y, this.z - z);
  1128. };
  1129. /**
  1130. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result.
  1131. * Returns the current Vector3.
  1132. */
  1133. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  1134. result.x = this.x - x;
  1135. result.y = this.y - y;
  1136. result.z = this.z - z;
  1137. return this;
  1138. };
  1139. /**
  1140. * Returns a new Vector3 set with the current Vector3 negated coordinates.
  1141. */
  1142. Vector3.prototype.negate = function () {
  1143. return new Vector3(-this.x, -this.y, -this.z);
  1144. };
  1145. /**
  1146. * Multiplies the Vector3 coordinates by the float "scale".
  1147. * Returns the updated Vector3.
  1148. */
  1149. Vector3.prototype.scaleInPlace = function (scale) {
  1150. this.x *= scale;
  1151. this.y *= scale;
  1152. this.z *= scale;
  1153. return this;
  1154. };
  1155. /**
  1156. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale".
  1157. */
  1158. Vector3.prototype.scale = function (scale) {
  1159. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  1160. };
  1161. /**
  1162. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates.
  1163. * Returns the current Vector3.
  1164. */
  1165. Vector3.prototype.scaleToRef = function (scale, result) {
  1166. result.x = this.x * scale;
  1167. result.y = this.y * scale;
  1168. result.z = this.z * scale;
  1169. return this;
  1170. };
  1171. /**
  1172. * Boolean : True if the current Vector3 and the passed vector coordinates are strictly equal.
  1173. */
  1174. Vector3.prototype.equals = function (otherVector) {
  1175. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  1176. };
  1177. /**
  1178. * Boolean : True if the current Vector3 and the passed vector coordinates are distant less than epsilon.
  1179. */
  1180. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1181. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1182. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon) && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon);
  1183. };
  1184. /**
  1185. * Boolean : True if the current Vector3 coordinate equal the passed floats.
  1186. */
  1187. Vector3.prototype.equalsToFloats = function (x, y, z) {
  1188. return this.x === x && this.y === y && this.z === z;
  1189. };
  1190. /**
  1191. * Muliplies the current Vector3 coordinates by the passed ones.
  1192. * Returns the updated Vector3.
  1193. */
  1194. Vector3.prototype.multiplyInPlace = function (otherVector) {
  1195. this.x *= otherVector.x;
  1196. this.y *= otherVector.y;
  1197. this.z *= otherVector.z;
  1198. return this;
  1199. };
  1200. /**
  1201. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector.
  1202. */
  1203. Vector3.prototype.multiply = function (otherVector) {
  1204. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  1205. };
  1206. /**
  1207. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result".
  1208. * Returns the current Vector3.
  1209. */
  1210. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  1211. result.x = this.x * otherVector.x;
  1212. result.y = this.y * otherVector.y;
  1213. result.z = this.z * otherVector.z;
  1214. return this;
  1215. };
  1216. /**
  1217. * Returns a new Vector3 set witth the result of the mulliplication of the current Vector3 coordinates by the passed floats.
  1218. */
  1219. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  1220. return new Vector3(this.x * x, this.y * y, this.z * z);
  1221. };
  1222. /**
  1223. * Returns a new Vector3 set witth the result of the division of the current Vector3 coordinates by the passed ones.
  1224. */
  1225. Vector3.prototype.divide = function (otherVector) {
  1226. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  1227. };
  1228. /**
  1229. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result".
  1230. * Returns the current Vector3.
  1231. */
  1232. Vector3.prototype.divideToRef = function (otherVector, result) {
  1233. result.x = this.x / otherVector.x;
  1234. result.y = this.y / otherVector.y;
  1235. result.z = this.z / otherVector.z;
  1236. return this;
  1237. };
  1238. /**
  1239. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones.
  1240. * Returns the updated Vector3.
  1241. */
  1242. Vector3.prototype.MinimizeInPlace = function (other) {
  1243. if (other.x < this.x)
  1244. this.x = other.x;
  1245. if (other.y < this.y)
  1246. this.y = other.y;
  1247. if (other.z < this.z)
  1248. this.z = other.z;
  1249. return this;
  1250. };
  1251. /**
  1252. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  1253. * Returns the updated Vector3.
  1254. */
  1255. Vector3.prototype.MaximizeInPlace = function (other) {
  1256. if (other.x > this.x)
  1257. this.x = other.x;
  1258. if (other.y > this.y)
  1259. this.y = other.y;
  1260. if (other.z > this.z)
  1261. this.z = other.z;
  1262. return this;
  1263. };
  1264. // Properties
  1265. /**
  1266. * Returns the length of the Vector3 (float).
  1267. */
  1268. Vector3.prototype.length = function () {
  1269. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  1270. };
  1271. /**
  1272. * Returns the squared length of the Vector3 (float).
  1273. */
  1274. Vector3.prototype.lengthSquared = function () {
  1275. return (this.x * this.x + this.y * this.y + this.z * this.z);
  1276. };
  1277. // Methods
  1278. /**
  1279. * Normalize the current Vector3.
  1280. * Returns the updated Vector3.
  1281. */
  1282. Vector3.prototype.normalize = function () {
  1283. var len = this.length();
  1284. if (len === 0 || len === 1.0)
  1285. return this;
  1286. var num = 1.0 / len;
  1287. this.x *= num;
  1288. this.y *= num;
  1289. this.z *= num;
  1290. return this;
  1291. };
  1292. /**
  1293. * Returns a new Vector3 copied from the current Vector3.
  1294. */
  1295. Vector3.prototype.clone = function () {
  1296. return new Vector3(this.x, this.y, this.z);
  1297. };
  1298. /**
  1299. * Copies the passed vector coordinates to the current Vector3 ones.
  1300. * Returns the updated Vector3.
  1301. */
  1302. Vector3.prototype.copyFrom = function (source) {
  1303. this.x = source.x;
  1304. this.y = source.y;
  1305. this.z = source.z;
  1306. return this;
  1307. };
  1308. /**
  1309. * Copies the passed floats to the current Vector3 coordinates.
  1310. * Returns the updated Vector3.
  1311. */
  1312. Vector3.prototype.copyFromFloats = function (x, y, z) {
  1313. this.x = x;
  1314. this.y = y;
  1315. this.z = z;
  1316. return this;
  1317. };
  1318. /**
  1319. * Copies the passed floats to the current Vector3 coordinates.
  1320. * Returns the updated Vector3.
  1321. */
  1322. Vector3.prototype.set = function (x, y, z) {
  1323. return this.copyFromFloats(x, y, z);
  1324. };
  1325. // Statics
  1326. /**
  1327. *
  1328. */
  1329. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  1330. var d0 = Vector3.Dot(vector0, axis) - size;
  1331. var d1 = Vector3.Dot(vector1, axis) - size;
  1332. var s = d0 / (d0 - d1);
  1333. return s;
  1334. };
  1335. /**
  1336. * Returns a new Vector3 set from the index "offset" of the passed array.
  1337. */
  1338. Vector3.FromArray = function (array, offset) {
  1339. if (!offset) {
  1340. offset = 0;
  1341. }
  1342. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  1343. };
  1344. /**
  1345. * Returns a new Vector3 set from the index "offset" of the passed Float32Array.
  1346. * This function is deprecated. Use FromArray instead.
  1347. */
  1348. Vector3.FromFloatArray = function (array, offset) {
  1349. return Vector3.FromArray(array, offset);
  1350. };
  1351. /**
  1352. * Sets the passed vector "result" with the element values from the index "offset" of the passed array.
  1353. */
  1354. Vector3.FromArrayToRef = function (array, offset, result) {
  1355. result.x = array[offset];
  1356. result.y = array[offset + 1];
  1357. result.z = array[offset + 2];
  1358. };
  1359. /**
  1360. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array.
  1361. * This function is deprecated. Use FromArrayToRef instead.
  1362. */
  1363. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  1364. return Vector3.FromArrayToRef(array, offset, result);
  1365. };
  1366. /**
  1367. * Sets the passed vector "result" with the passed floats.
  1368. */
  1369. Vector3.FromFloatsToRef = function (x, y, z, result) {
  1370. result.x = x;
  1371. result.y = y;
  1372. result.z = z;
  1373. };
  1374. /**
  1375. * Returns a new Vector3 set to (0.0, 0.0, 0.0).
  1376. */
  1377. Vector3.Zero = function () {
  1378. return new Vector3(0.0, 0.0, 0.0);
  1379. };
  1380. /**
  1381. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  1382. */
  1383. Vector3.Up = function () {
  1384. return new Vector3(0.0, 1.0, 0.0);
  1385. };
  1386. /**
  1387. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  1388. */
  1389. Vector3.Forward = function () {
  1390. return new Vector3(0.0, 0.0, 1.0);
  1391. };
  1392. /**
  1393. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  1394. */
  1395. Vector3.Right = function () {
  1396. return new Vector3(1.0, 0.0, 0.0);
  1397. };
  1398. /**
  1399. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  1400. */
  1401. Vector3.Left = function () {
  1402. return new Vector3(-1.0, 0.0, 0.0);
  1403. };
  1404. /**
  1405. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  1406. * This method computes tranformed coordinates only, not transformed direction vectors.
  1407. */
  1408. Vector3.TransformCoordinates = function (vector, transformation) {
  1409. var result = Vector3.Zero();
  1410. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  1411. return result;
  1412. };
  1413. /**
  1414. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector.
  1415. * This method computes tranformed coordinates only, not transformed direction vectors.
  1416. */
  1417. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  1418. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  1419. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  1420. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  1421. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  1422. result.x = x / w;
  1423. result.y = y / w;
  1424. result.z = z / w;
  1425. };
  1426. /**
  1427. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z).
  1428. * This method computes tranformed coordinates only, not transformed direction vectors.
  1429. */
  1430. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  1431. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  1432. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  1433. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  1434. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  1435. result.x = rx / rw;
  1436. result.y = ry / rw;
  1437. result.z = rz / rw;
  1438. };
  1439. /**
  1440. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector.
  1441. * This methods computes transformed normalized direction vectors only.
  1442. */
  1443. Vector3.TransformNormal = function (vector, transformation) {
  1444. var result = Vector3.Zero();
  1445. Vector3.TransformNormalToRef(vector, transformation, result);
  1446. return result;
  1447. };
  1448. /**
  1449. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  1450. * This methods computes transformed normalized direction vectors only.
  1451. */
  1452. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  1453. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  1454. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  1455. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  1456. result.x = x;
  1457. result.y = y;
  1458. result.z = z;
  1459. };
  1460. /**
  1461. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z).
  1462. * This methods computes transformed normalized direction vectors only.
  1463. */
  1464. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  1465. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  1466. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  1467. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  1468. };
  1469. /**
  1470. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4".
  1471. */
  1472. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  1473. var squared = amount * amount;
  1474. var cubed = amount * squared;
  1475. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  1476. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  1477. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  1478. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  1479. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1480. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1481. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  1482. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  1483. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  1484. return new Vector3(x, y, z);
  1485. };
  1486. /**
  1487. * 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".
  1488. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one.
  1489. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one.
  1490. */
  1491. Vector3.Clamp = function (value, min, max) {
  1492. var x = value.x;
  1493. x = (x > max.x) ? max.x : x;
  1494. x = (x < min.x) ? min.x : x;
  1495. var y = value.y;
  1496. y = (y > max.y) ? max.y : y;
  1497. y = (y < min.y) ? min.y : y;
  1498. var z = value.z;
  1499. z = (z > max.z) ? max.z : z;
  1500. z = (z < min.z) ? min.z : z;
  1501. return new Vector3(x, y, z);
  1502. };
  1503. /**
  1504. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  1505. */
  1506. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  1507. var squared = amount * amount;
  1508. var cubed = amount * squared;
  1509. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1510. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1511. var part3 = (cubed - (2.0 * squared)) + amount;
  1512. var part4 = cubed - squared;
  1513. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1514. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1515. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  1516. return new Vector3(x, y, z);
  1517. };
  1518. /**
  1519. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end".
  1520. */
  1521. Vector3.Lerp = function (start, end, amount) {
  1522. var result = new Vector3(0, 0, 0);
  1523. Vector3.LerpToRef(start, end, amount, result);
  1524. return result;
  1525. };
  1526. /**
  1527. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end".
  1528. */
  1529. Vector3.LerpToRef = function (start, end, amount, result) {
  1530. result.x = start.x + ((end.x - start.x) * amount);
  1531. result.y = start.y + ((end.y - start.y) * amount);
  1532. result.z = start.z + ((end.z - start.z) * amount);
  1533. };
  1534. /**
  1535. * Returns the dot product (float) between the vectors "left" and "right".
  1536. */
  1537. Vector3.Dot = function (left, right) {
  1538. return (left.x * right.x + left.y * right.y + left.z * right.z);
  1539. };
  1540. /**
  1541. * Returns a new Vector3 as the cross product of the vectors "left" and "right".
  1542. * The cross product is then orthogonal to both "left" and "right".
  1543. */
  1544. Vector3.Cross = function (left, right) {
  1545. var result = Vector3.Zero();
  1546. Vector3.CrossToRef(left, right, result);
  1547. return result;
  1548. };
  1549. /**
  1550. * Sets the passed vector "result" with the cross product of "left" and "right".
  1551. * The cross product is then orthogonal to both "left" and "right".
  1552. */
  1553. Vector3.CrossToRef = function (left, right, result) {
  1554. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  1555. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  1556. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  1557. result.copyFrom(MathTmp.Vector3[0]);
  1558. };
  1559. /**
  1560. * Returns a new Vector3 as the normalization of the passed vector.
  1561. */
  1562. Vector3.Normalize = function (vector) {
  1563. var result = Vector3.Zero();
  1564. Vector3.NormalizeToRef(vector, result);
  1565. return result;
  1566. };
  1567. /**
  1568. * Sets the passed vector "result" with the normalization of the passed first vector.
  1569. */
  1570. Vector3.NormalizeToRef = function (vector, result) {
  1571. result.copyFrom(vector);
  1572. result.normalize();
  1573. };
  1574. Vector3.Project = function (vector, world, transform, viewport) {
  1575. var cw = viewport.width;
  1576. var ch = viewport.height;
  1577. var cx = viewport.x;
  1578. var cy = viewport.y;
  1579. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  1580. 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);
  1581. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  1582. world.multiplyToRef(transform, matrix);
  1583. matrix.multiplyToRef(viewportMatrix, matrix);
  1584. return Vector3.TransformCoordinates(vector, matrix);
  1585. };
  1586. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  1587. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  1588. world.multiplyToRef(transform, matrix);
  1589. matrix.invert();
  1590. source.x = source.x / viewportWidth * 2 - 1;
  1591. source.y = -(source.y / viewportHeight * 2 - 1);
  1592. var vector = Vector3.TransformCoordinates(source, matrix);
  1593. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  1594. if (MathTools.WithinEpsilon(num, 1.0)) {
  1595. vector = vector.scale(1.0 / num);
  1596. }
  1597. return vector;
  1598. };
  1599. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  1600. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  1601. world.multiplyToRef(view, matrix);
  1602. matrix.multiplyToRef(projection, matrix);
  1603. matrix.invert();
  1604. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), 2 * source.z - 1.0);
  1605. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  1606. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  1607. if (MathTools.WithinEpsilon(num, 1.0)) {
  1608. vector = vector.scale(1.0 / num);
  1609. }
  1610. return vector;
  1611. };
  1612. Vector3.Minimize = function (left, right) {
  1613. var min = left.clone();
  1614. min.MinimizeInPlace(right);
  1615. return min;
  1616. };
  1617. Vector3.Maximize = function (left, right) {
  1618. var max = left.clone();
  1619. max.MaximizeInPlace(right);
  1620. return max;
  1621. };
  1622. /**
  1623. * Returns the distance (float) between the vectors "value1" and "value2".
  1624. */
  1625. Vector3.Distance = function (value1, value2) {
  1626. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  1627. };
  1628. /**
  1629. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1630. */
  1631. Vector3.DistanceSquared = function (value1, value2) {
  1632. var x = value1.x - value2.x;
  1633. var y = value1.y - value2.y;
  1634. var z = value1.z - value2.z;
  1635. return (x * x) + (y * y) + (z * z);
  1636. };
  1637. /**
  1638. * Returns a new Vector3 located at the center between "value1" and "value2".
  1639. */
  1640. Vector3.Center = function (value1, value2) {
  1641. var center = value1.add(value2);
  1642. center.scaleInPlace(0.5);
  1643. return center;
  1644. };
  1645. /**
  1646. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  1647. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  1648. * to something in order to rotate it from its local system to the given target system.
  1649. * Note : axis1, axis2 and axis3 are normalized during this operation.
  1650. * Returns a new Vector3.
  1651. */
  1652. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  1653. var rotation = Vector3.Zero();
  1654. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  1655. return rotation;
  1656. };
  1657. /**
  1658. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3.
  1659. */
  1660. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  1661. var quat = MathTmp.Quaternion[0];
  1662. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  1663. quat.toEulerAnglesToRef(ref);
  1664. };
  1665. return Vector3;
  1666. }());
  1667. BABYLON.Vector3 = Vector3;
  1668. //Vector4 class created for EulerAngle class conversion to Quaternion
  1669. var Vector4 = (function () {
  1670. /**
  1671. * Creates a Vector4 object from the passed floats.
  1672. */
  1673. function Vector4(x, y, z, w) {
  1674. this.x = x;
  1675. this.y = y;
  1676. this.z = z;
  1677. this.w = w;
  1678. }
  1679. /**
  1680. * Returns the string with the Vector4 coordinates.
  1681. */
  1682. Vector4.prototype.toString = function () {
  1683. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1684. };
  1685. /**
  1686. * Returns the string "Vector4".
  1687. */
  1688. Vector4.prototype.getClassName = function () {
  1689. return "Vector4";
  1690. };
  1691. /**
  1692. * Returns the Vector4 hash code.
  1693. */
  1694. Vector4.prototype.getHashCode = function () {
  1695. var hash = this.x || 0;
  1696. hash = (hash * 397) ^ (this.y || 0);
  1697. hash = (hash * 397) ^ (this.z || 0);
  1698. hash = (hash * 397) ^ (this.w || 0);
  1699. return hash;
  1700. };
  1701. // Operators
  1702. /**
  1703. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  1704. */
  1705. Vector4.prototype.asArray = function () {
  1706. var result = [];
  1707. this.toArray(result, 0);
  1708. return result;
  1709. };
  1710. /**
  1711. * Populates the passed array from the passed index with the Vector4 coordinates.
  1712. * Returns the Vector4.
  1713. */
  1714. Vector4.prototype.toArray = function (array, index) {
  1715. if (index === undefined) {
  1716. index = 0;
  1717. }
  1718. array[index] = this.x;
  1719. array[index + 1] = this.y;
  1720. array[index + 2] = this.z;
  1721. array[index + 3] = this.w;
  1722. return this;
  1723. };
  1724. /**
  1725. * Adds the passed vector to the current Vector4.
  1726. * Returns the updated Vector4.
  1727. */
  1728. Vector4.prototype.addInPlace = function (otherVector) {
  1729. this.x += otherVector.x;
  1730. this.y += otherVector.y;
  1731. this.z += otherVector.z;
  1732. this.w += otherVector.w;
  1733. return this;
  1734. };
  1735. /**
  1736. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  1737. */
  1738. Vector4.prototype.add = function (otherVector) {
  1739. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1740. };
  1741. /**
  1742. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  1743. * Returns the current Vector4.
  1744. */
  1745. Vector4.prototype.addToRef = function (otherVector, result) {
  1746. result.x = this.x + otherVector.x;
  1747. result.y = this.y + otherVector.y;
  1748. result.z = this.z + otherVector.z;
  1749. result.w = this.w + otherVector.w;
  1750. return this;
  1751. };
  1752. /**
  1753. * Subtract in place the passed vector from the current Vector4.
  1754. * Returns the updated Vector4.
  1755. */
  1756. Vector4.prototype.subtractInPlace = function (otherVector) {
  1757. this.x -= otherVector.x;
  1758. this.y -= otherVector.y;
  1759. this.z -= otherVector.z;
  1760. this.w -= otherVector.w;
  1761. return this;
  1762. };
  1763. /**
  1764. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  1765. */
  1766. Vector4.prototype.subtract = function (otherVector) {
  1767. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1768. };
  1769. /**
  1770. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  1771. * Returns the current Vector4.
  1772. */
  1773. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1774. result.x = this.x - otherVector.x;
  1775. result.y = this.y - otherVector.y;
  1776. result.z = this.z - otherVector.z;
  1777. result.w = this.w - otherVector.w;
  1778. return this;
  1779. };
  1780. /**
  1781. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1782. */
  1783. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1784. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1785. };
  1786. /**
  1787. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1788. * Returns the current Vector4.
  1789. */
  1790. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1791. result.x = this.x - x;
  1792. result.y = this.y - y;
  1793. result.z = this.z - z;
  1794. result.w = this.w - w;
  1795. return this;
  1796. };
  1797. /**
  1798. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  1799. */
  1800. Vector4.prototype.negate = function () {
  1801. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1802. };
  1803. /**
  1804. * Multiplies the current Vector4 coordinates by scale (float).
  1805. * Returns the updated Vector4.
  1806. */
  1807. Vector4.prototype.scaleInPlace = function (scale) {
  1808. this.x *= scale;
  1809. this.y *= scale;
  1810. this.z *= scale;
  1811. this.w *= scale;
  1812. return this;
  1813. };
  1814. /**
  1815. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  1816. */
  1817. Vector4.prototype.scale = function (scale) {
  1818. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1819. };
  1820. /**
  1821. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  1822. * Returns the current Vector4.
  1823. */
  1824. Vector4.prototype.scaleToRef = function (scale, result) {
  1825. result.x = this.x * scale;
  1826. result.y = this.y * scale;
  1827. result.z = this.z * scale;
  1828. result.w = this.w * scale;
  1829. return this;
  1830. };
  1831. /**
  1832. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  1833. */
  1834. Vector4.prototype.equals = function (otherVector) {
  1835. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1836. };
  1837. /**
  1838. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  1839. */
  1840. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1841. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1842. return otherVector
  1843. && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1844. && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1845. && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1846. && MathTools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1847. };
  1848. /**
  1849. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  1850. */
  1851. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1852. return this.x === x && this.y === y && this.z === z && this.w === w;
  1853. };
  1854. /**
  1855. * Multiplies in place the current Vector4 by the passed one.
  1856. * Returns the updated Vector4.
  1857. */
  1858. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1859. this.x *= otherVector.x;
  1860. this.y *= otherVector.y;
  1861. this.z *= otherVector.z;
  1862. this.w *= otherVector.w;
  1863. return this;
  1864. };
  1865. /**
  1866. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  1867. */
  1868. Vector4.prototype.multiply = function (otherVector) {
  1869. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1870. };
  1871. /**
  1872. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  1873. * Returns the current Vector4.
  1874. */
  1875. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1876. result.x = this.x * otherVector.x;
  1877. result.y = this.y * otherVector.y;
  1878. result.z = this.z * otherVector.z;
  1879. result.w = this.w * otherVector.w;
  1880. return this;
  1881. };
  1882. /**
  1883. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  1884. */
  1885. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1886. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1887. };
  1888. /**
  1889. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  1890. */
  1891. Vector4.prototype.divide = function (otherVector) {
  1892. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1893. };
  1894. /**
  1895. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  1896. * Returns the current Vector4.
  1897. */
  1898. Vector4.prototype.divideToRef = function (otherVector, result) {
  1899. result.x = this.x / otherVector.x;
  1900. result.y = this.y / otherVector.y;
  1901. result.z = this.z / otherVector.z;
  1902. result.w = this.w / otherVector.w;
  1903. return this;
  1904. };
  1905. /**
  1906. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones.
  1907. */
  1908. Vector4.prototype.MinimizeInPlace = function (other) {
  1909. if (other.x < this.x)
  1910. this.x = other.x;
  1911. if (other.y < this.y)
  1912. this.y = other.y;
  1913. if (other.z < this.z)
  1914. this.z = other.z;
  1915. if (other.w < this.w)
  1916. this.w = other.w;
  1917. return this;
  1918. };
  1919. /**
  1920. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones.
  1921. */
  1922. Vector4.prototype.MaximizeInPlace = function (other) {
  1923. if (other.x > this.x)
  1924. this.x = other.x;
  1925. if (other.y > this.y)
  1926. this.y = other.y;
  1927. if (other.z > this.z)
  1928. this.z = other.z;
  1929. if (other.w > this.w)
  1930. this.w = other.w;
  1931. return this;
  1932. };
  1933. // Properties
  1934. /**
  1935. * Returns the Vector4 length (float).
  1936. */
  1937. Vector4.prototype.length = function () {
  1938. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1939. };
  1940. /**
  1941. * Returns the Vector4 squared length (float).
  1942. */
  1943. Vector4.prototype.lengthSquared = function () {
  1944. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1945. };
  1946. // Methods
  1947. /**
  1948. * Normalizes in place the Vector4.
  1949. * Returns the updated Vector4.
  1950. */
  1951. Vector4.prototype.normalize = function () {
  1952. var len = this.length();
  1953. if (len === 0)
  1954. return this;
  1955. var num = 1.0 / len;
  1956. this.x *= num;
  1957. this.y *= num;
  1958. this.z *= num;
  1959. this.w *= num;
  1960. return this;
  1961. };
  1962. /**
  1963. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  1964. */
  1965. Vector4.prototype.toVector3 = function () {
  1966. return new Vector3(this.x, this.y, this.z);
  1967. };
  1968. /**
  1969. * Returns a new Vector4 copied from the current one.
  1970. */
  1971. Vector4.prototype.clone = function () {
  1972. return new Vector4(this.x, this.y, this.z, this.w);
  1973. };
  1974. /**
  1975. * Updates the current Vector4 with the passed one coordinates.
  1976. * Returns the updated Vector4.
  1977. */
  1978. Vector4.prototype.copyFrom = function (source) {
  1979. this.x = source.x;
  1980. this.y = source.y;
  1981. this.z = source.z;
  1982. this.w = source.w;
  1983. return this;
  1984. };
  1985. /**
  1986. * Updates the current Vector4 coordinates with the passed floats.
  1987. * Returns the updated Vector4.
  1988. */
  1989. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1990. this.x = x;
  1991. this.y = y;
  1992. this.z = z;
  1993. this.w = w;
  1994. return this;
  1995. };
  1996. /**
  1997. * Updates the current Vector4 coordinates with the passed floats.
  1998. * Returns the updated Vector4.
  1999. */
  2000. Vector4.prototype.set = function (x, y, z, w) {
  2001. return this.copyFromFloats(x, y, z, w);
  2002. };
  2003. // Statics
  2004. /**
  2005. * Returns a new Vector4 set from the starting index of the passed array.
  2006. */
  2007. Vector4.FromArray = function (array, offset) {
  2008. if (!offset) {
  2009. offset = 0;
  2010. }
  2011. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2012. };
  2013. /**
  2014. * Updates the passed vector "result" from the starting index of the passed array.
  2015. */
  2016. Vector4.FromArrayToRef = function (array, offset, result) {
  2017. result.x = array[offset];
  2018. result.y = array[offset + 1];
  2019. result.z = array[offset + 2];
  2020. result.w = array[offset + 3];
  2021. };
  2022. /**
  2023. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  2024. */
  2025. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  2026. Vector4.FromArrayToRef(array, offset, result);
  2027. };
  2028. /**
  2029. * Updates the passed vector "result" coordinates from the passed floats.
  2030. */
  2031. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  2032. result.x = x;
  2033. result.y = y;
  2034. result.z = z;
  2035. result.w = w;
  2036. };
  2037. /**
  2038. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  2039. */
  2040. Vector4.Zero = function () {
  2041. return new Vector4(0.0, 0.0, 0.0, 0.0);
  2042. };
  2043. /**
  2044. * Returns a new normalized Vector4 from the passed one.
  2045. */
  2046. Vector4.Normalize = function (vector) {
  2047. var result = Vector4.Zero();
  2048. Vector4.NormalizeToRef(vector, result);
  2049. return result;
  2050. };
  2051. /**
  2052. * Updates the passed vector "result" from the normalization of the passed one.
  2053. */
  2054. Vector4.NormalizeToRef = function (vector, result) {
  2055. result.copyFrom(vector);
  2056. result.normalize();
  2057. };
  2058. Vector4.Minimize = function (left, right) {
  2059. var min = left.clone();
  2060. min.MinimizeInPlace(right);
  2061. return min;
  2062. };
  2063. Vector4.Maximize = function (left, right) {
  2064. var max = left.clone();
  2065. max.MaximizeInPlace(right);
  2066. return max;
  2067. };
  2068. /**
  2069. * Returns the distance (float) between the vectors "value1" and "value2".
  2070. */
  2071. Vector4.Distance = function (value1, value2) {
  2072. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  2073. };
  2074. /**
  2075. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2076. */
  2077. Vector4.DistanceSquared = function (value1, value2) {
  2078. var x = value1.x - value2.x;
  2079. var y = value1.y - value2.y;
  2080. var z = value1.z - value2.z;
  2081. var w = value1.w - value2.w;
  2082. return (x * x) + (y * y) + (z * z) + (w * w);
  2083. };
  2084. /**
  2085. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  2086. */
  2087. Vector4.Center = function (value1, value2) {
  2088. var center = value1.add(value2);
  2089. center.scaleInPlace(0.5);
  2090. return center;
  2091. };
  2092. /**
  2093. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  2094. * This methods computes transformed normalized direction vectors only.
  2095. */
  2096. Vector4.TransformNormal = function (vector, transformation) {
  2097. var result = Vector4.Zero();
  2098. Vector4.TransformNormalToRef(vector, transformation, result);
  2099. return result;
  2100. };
  2101. /**
  2102. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  2103. * This methods computes transformed normalized direction vectors only.
  2104. */
  2105. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  2106. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  2107. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  2108. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  2109. result.x = x;
  2110. result.y = y;
  2111. result.z = z;
  2112. result.w = vector.w;
  2113. };
  2114. /**
  2115. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  2116. * This methods computes transformed normalized direction vectors only.
  2117. */
  2118. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  2119. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  2120. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  2121. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  2122. result.w = w;
  2123. };
  2124. return Vector4;
  2125. }());
  2126. BABYLON.Vector4 = Vector4;
  2127. var Size = (function () {
  2128. /**
  2129. * Creates a Size object from the passed width and height (floats).
  2130. */
  2131. function Size(width, height) {
  2132. this.width = width;
  2133. this.height = height;
  2134. }
  2135. // Returns a string with the Size width and height.
  2136. Size.prototype.toString = function () {
  2137. return "{W: " + this.width + ", H: " + this.height + "}";
  2138. };
  2139. /**
  2140. * Returns the string "Size"
  2141. */
  2142. Size.prototype.getClassName = function () {
  2143. return "Size";
  2144. };
  2145. /**
  2146. * Returns the Size hash code.
  2147. */
  2148. Size.prototype.getHashCode = function () {
  2149. var hash = this.width || 0;
  2150. hash = (hash * 397) ^ (this.height || 0);
  2151. return hash;
  2152. };
  2153. /**
  2154. * Updates the current size from the passed one.
  2155. * Returns the updated Size.
  2156. */
  2157. Size.prototype.copyFrom = function (src) {
  2158. this.width = src.width;
  2159. this.height = src.height;
  2160. };
  2161. /**
  2162. * Updates in place the current Size from the passed floats.
  2163. * Returns the updated Size.
  2164. */
  2165. Size.prototype.copyFromFloats = function (width, height) {
  2166. this.width = width;
  2167. this.height = height;
  2168. return this;
  2169. };
  2170. /**
  2171. * Updates in place the current Size from the passed floats.
  2172. * Returns the updated Size.
  2173. */
  2174. Size.prototype.set = function (width, height) {
  2175. return this.copyFromFloats(width, height);
  2176. };
  2177. /**
  2178. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  2179. */
  2180. Size.prototype.multiplyByFloats = function (w, h) {
  2181. return new Size(this.width * w, this.height * h);
  2182. };
  2183. /**
  2184. * Returns a new Size copied from the passed one.
  2185. */
  2186. Size.prototype.clone = function () {
  2187. return new Size(this.width, this.height);
  2188. };
  2189. /**
  2190. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  2191. */
  2192. Size.prototype.equals = function (other) {
  2193. if (!other) {
  2194. return false;
  2195. }
  2196. return (this.width === other.width) && (this.height === other.height);
  2197. };
  2198. Object.defineProperty(Size.prototype, "surface", {
  2199. /**
  2200. * Returns the surface of the Size : width * height (float).
  2201. */
  2202. get: function () {
  2203. return this.width * this.height;
  2204. },
  2205. enumerable: true,
  2206. configurable: true
  2207. });
  2208. /**
  2209. * Returns a new Size set to (0.0, 0.0)
  2210. */
  2211. Size.Zero = function () {
  2212. return new Size(0.0, 0.0);
  2213. };
  2214. /**
  2215. * Returns a new Size set as the addition result of the current Size and the passed one.
  2216. */
  2217. Size.prototype.add = function (otherSize) {
  2218. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  2219. return r;
  2220. };
  2221. /**
  2222. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  2223. */
  2224. Size.prototype.subtract = function (otherSize) {
  2225. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  2226. return r;
  2227. };
  2228. /**
  2229. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  2230. */
  2231. Size.Lerp = function (start, end, amount) {
  2232. var w = start.width + ((end.width - start.width) * amount);
  2233. var h = start.height + ((end.height - start.height) * amount);
  2234. return new Size(w, h);
  2235. };
  2236. return Size;
  2237. }());
  2238. BABYLON.Size = Size;
  2239. var Quaternion = (function () {
  2240. /**
  2241. * Creates a new Quaternion from the passed floats.
  2242. */
  2243. function Quaternion(x, y, z, w) {
  2244. if (x === void 0) { x = 0.0; }
  2245. if (y === void 0) { y = 0.0; }
  2246. if (z === void 0) { z = 0.0; }
  2247. if (w === void 0) { w = 1.0; }
  2248. this.x = x;
  2249. this.y = y;
  2250. this.z = z;
  2251. this.w = w;
  2252. }
  2253. /**
  2254. * Returns a string with the Quaternion coordinates.
  2255. */
  2256. Quaternion.prototype.toString = function () {
  2257. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  2258. };
  2259. /**
  2260. * Returns the string "Quaternion".
  2261. */
  2262. Quaternion.prototype.getClassName = function () {
  2263. return "Quaternion";
  2264. };
  2265. /**
  2266. * Returns the Quaternion hash code.
  2267. */
  2268. Quaternion.prototype.getHashCode = function () {
  2269. var hash = this.x || 0;
  2270. hash = (hash * 397) ^ (this.y || 0);
  2271. hash = (hash * 397) ^ (this.z || 0);
  2272. hash = (hash * 397) ^ (this.w || 0);
  2273. return hash;
  2274. };
  2275. /**
  2276. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  2277. */
  2278. Quaternion.prototype.asArray = function () {
  2279. return [this.x, this.y, this.z, this.w];
  2280. };
  2281. /**
  2282. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  2283. */
  2284. Quaternion.prototype.equals = function (otherQuaternion) {
  2285. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  2286. };
  2287. /**
  2288. * Returns a new Quaternion copied from the current one.
  2289. */
  2290. Quaternion.prototype.clone = function () {
  2291. return new Quaternion(this.x, this.y, this.z, this.w);
  2292. };
  2293. /**
  2294. * Updates the current Quaternion from the passed one coordinates.
  2295. * Returns the updated Quaterion.
  2296. */
  2297. Quaternion.prototype.copyFrom = function (other) {
  2298. this.x = other.x;
  2299. this.y = other.y;
  2300. this.z = other.z;
  2301. this.w = other.w;
  2302. return this;
  2303. };
  2304. /**
  2305. * Updates the current Quaternion from the passed float coordinates.
  2306. * Returns the updated Quaterion.
  2307. */
  2308. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  2309. this.x = x;
  2310. this.y = y;
  2311. this.z = z;
  2312. this.w = w;
  2313. return this;
  2314. };
  2315. /**
  2316. * Updates the current Quaternion from the passed float coordinates.
  2317. * Returns the updated Quaterion.
  2318. */
  2319. Quaternion.prototype.set = function (x, y, z, w) {
  2320. return this.copyFromFloats(x, y, z, w);
  2321. };
  2322. /**
  2323. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  2324. */
  2325. Quaternion.prototype.add = function (other) {
  2326. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  2327. };
  2328. /**
  2329. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  2330. */
  2331. Quaternion.prototype.subtract = function (other) {
  2332. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  2333. };
  2334. /**
  2335. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  2336. */
  2337. Quaternion.prototype.scale = function (value) {
  2338. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  2339. };
  2340. /**
  2341. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  2342. */
  2343. Quaternion.prototype.multiply = function (q1) {
  2344. var result = new Quaternion(0, 0, 0, 1.0);
  2345. this.multiplyToRef(q1, result);
  2346. return result;
  2347. };
  2348. /**
  2349. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  2350. * Returns the current Quaternion.
  2351. */
  2352. Quaternion.prototype.multiplyToRef = function (q1, result) {
  2353. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  2354. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  2355. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  2356. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  2357. result.copyFromFloats(x, y, z, w);
  2358. return this;
  2359. };
  2360. /**
  2361. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  2362. * Returns the updated Quaternion.
  2363. */
  2364. Quaternion.prototype.multiplyInPlace = function (q1) {
  2365. this.multiplyToRef(q1, this);
  2366. return this;
  2367. };
  2368. /**
  2369. * Sets the passed "ref" with the conjugation of the current Quaternion.
  2370. * Returns the current Quaternion.
  2371. */
  2372. Quaternion.prototype.conjugateToRef = function (ref) {
  2373. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  2374. return this;
  2375. };
  2376. /**
  2377. * Conjugates in place the current Quaternion.
  2378. * Returns the updated Quaternion.
  2379. */
  2380. Quaternion.prototype.conjugateInPlace = function () {
  2381. this.x *= -1;
  2382. this.y *= -1;
  2383. this.z *= -1;
  2384. return this;
  2385. };
  2386. /**
  2387. * Returns a new Quaternion as the conjugate of the current Quaternion.
  2388. */
  2389. Quaternion.prototype.conjugate = function () {
  2390. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  2391. return result;
  2392. };
  2393. /**
  2394. * Returns the Quaternion length (float).
  2395. */
  2396. Quaternion.prototype.length = function () {
  2397. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  2398. };
  2399. /**
  2400. * Normalize in place the current Quaternion.
  2401. * Returns the updated Quaternion.
  2402. */
  2403. Quaternion.prototype.normalize = function () {
  2404. var length = 1.0 / this.length();
  2405. this.x *= length;
  2406. this.y *= length;
  2407. this.z *= length;
  2408. this.w *= length;
  2409. return this;
  2410. };
  2411. /**
  2412. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  2413. */
  2414. Quaternion.prototype.toEulerAngles = function (order) {
  2415. if (order === void 0) { order = "YZX"; }
  2416. var result = Vector3.Zero();
  2417. this.toEulerAnglesToRef(result, order);
  2418. return result;
  2419. };
  2420. /**
  2421. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  2422. * Returns the current Quaternion.
  2423. */
  2424. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  2425. if (order === void 0) { order = "YZX"; }
  2426. var qz = this.z;
  2427. var qx = this.x;
  2428. var qy = this.y;
  2429. var qw = this.w;
  2430. var sqw = qw * qw;
  2431. var sqz = qz * qz;
  2432. var sqx = qx * qx;
  2433. var sqy = qy * qy;
  2434. var zAxisY = qy * qz - qx * qw;
  2435. var limit = .4999999;
  2436. if (zAxisY < -limit) {
  2437. result.y = 2 * Math.atan2(qy, qw);
  2438. result.x = Math.PI / 2;
  2439. result.z = 0;
  2440. }
  2441. else if (zAxisY > limit) {
  2442. result.y = 2 * Math.atan2(qy, qw);
  2443. result.x = -Math.PI / 2;
  2444. result.z = 0;
  2445. }
  2446. else {
  2447. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  2448. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  2449. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  2450. }
  2451. return this;
  2452. };
  2453. /**
  2454. * Updates the passed rotation matrix with the current Quaternion values.
  2455. * Returns the current Quaternion.
  2456. */
  2457. Quaternion.prototype.toRotationMatrix = function (result) {
  2458. var xx = this.x * this.x;
  2459. var yy = this.y * this.y;
  2460. var zz = this.z * this.z;
  2461. var xy = this.x * this.y;
  2462. var zw = this.z * this.w;
  2463. var zx = this.z * this.x;
  2464. var yw = this.y * this.w;
  2465. var yz = this.y * this.z;
  2466. var xw = this.x * this.w;
  2467. result.m[0] = 1.0 - (2.0 * (yy + zz));
  2468. result.m[1] = 2.0 * (xy + zw);
  2469. result.m[2] = 2.0 * (zx - yw);
  2470. result.m[3] = 0;
  2471. result.m[4] = 2.0 * (xy - zw);
  2472. result.m[5] = 1.0 - (2.0 * (zz + xx));
  2473. result.m[6] = 2.0 * (yz + xw);
  2474. result.m[7] = 0;
  2475. result.m[8] = 2.0 * (zx + yw);
  2476. result.m[9] = 2.0 * (yz - xw);
  2477. result.m[10] = 1.0 - (2.0 * (yy + xx));
  2478. result.m[11] = 0;
  2479. result.m[12] = 0;
  2480. result.m[13] = 0;
  2481. result.m[14] = 0;
  2482. result.m[15] = 1.0;
  2483. result._markAsUpdated();
  2484. return this;
  2485. };
  2486. /**
  2487. * Updates the current Quaternion from the passed rotation matrix values.
  2488. * Returns the updated Quaternion.
  2489. */
  2490. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  2491. Quaternion.FromRotationMatrixToRef(matrix, this);
  2492. return this;
  2493. };
  2494. // Statics
  2495. /**
  2496. * Returns a new Quaternion set from the passed rotation matrix values.
  2497. */
  2498. Quaternion.FromRotationMatrix = function (matrix) {
  2499. var result = new Quaternion();
  2500. Quaternion.FromRotationMatrixToRef(matrix, result);
  2501. return result;
  2502. };
  2503. /**
  2504. * Updates the passed quaternion "result" with the passed rotation matrix values.
  2505. */
  2506. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  2507. var data = matrix.m;
  2508. var m11 = data[0], m12 = data[4], m13 = data[8];
  2509. var m21 = data[1], m22 = data[5], m23 = data[9];
  2510. var m31 = data[2], m32 = data[6], m33 = data[10];
  2511. var trace = m11 + m22 + m33;
  2512. var s;
  2513. if (trace > 0) {
  2514. s = 0.5 / Math.sqrt(trace + 1.0);
  2515. result.w = 0.25 / s;
  2516. result.x = (m32 - m23) * s;
  2517. result.y = (m13 - m31) * s;
  2518. result.z = (m21 - m12) * s;
  2519. }
  2520. else if (m11 > m22 && m11 > m33) {
  2521. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  2522. result.w = (m32 - m23) / s;
  2523. result.x = 0.25 * s;
  2524. result.y = (m12 + m21) / s;
  2525. result.z = (m13 + m31) / s;
  2526. }
  2527. else if (m22 > m33) {
  2528. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  2529. result.w = (m13 - m31) / s;
  2530. result.x = (m12 + m21) / s;
  2531. result.y = 0.25 * s;
  2532. result.z = (m23 + m32) / s;
  2533. }
  2534. else {
  2535. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  2536. result.w = (m21 - m12) / s;
  2537. result.x = (m13 + m31) / s;
  2538. result.y = (m23 + m32) / s;
  2539. result.z = 0.25 * s;
  2540. }
  2541. };
  2542. /**
  2543. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  2544. */
  2545. Quaternion.Zero = function () {
  2546. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  2547. };
  2548. /**
  2549. * Returns a new Quaternion as the inverted current Quaternion.
  2550. */
  2551. Quaternion.Inverse = function (q) {
  2552. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  2553. };
  2554. /**
  2555. * Returns the identity Quaternion.
  2556. */
  2557. Quaternion.Identity = function () {
  2558. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  2559. };
  2560. Quaternion.IsIdentity = function (quaternion) {
  2561. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  2562. };
  2563. /**
  2564. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  2565. */
  2566. Quaternion.RotationAxis = function (axis, angle) {
  2567. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  2568. };
  2569. /**
  2570. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  2571. */
  2572. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  2573. var sin = Math.sin(angle / 2);
  2574. axis.normalize();
  2575. result.w = Math.cos(angle / 2);
  2576. result.x = axis.x * sin;
  2577. result.y = axis.y * sin;
  2578. result.z = axis.z * sin;
  2579. return result;
  2580. };
  2581. /**
  2582. * Retuns a new Quaternion set from the starting index of the passed array.
  2583. */
  2584. Quaternion.FromArray = function (array, offset) {
  2585. if (!offset) {
  2586. offset = 0;
  2587. }
  2588. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2589. };
  2590. /**
  2591. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  2592. */
  2593. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2594. var q = new Quaternion();
  2595. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  2596. return q;
  2597. };
  2598. /**
  2599. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  2600. */
  2601. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2602. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  2603. var halfRoll = roll * 0.5;
  2604. var halfPitch = pitch * 0.5;
  2605. var halfYaw = yaw * 0.5;
  2606. var sinRoll = Math.sin(halfRoll);
  2607. var cosRoll = Math.cos(halfRoll);
  2608. var sinPitch = Math.sin(halfPitch);
  2609. var cosPitch = Math.cos(halfPitch);
  2610. var sinYaw = Math.sin(halfYaw);
  2611. var cosYaw = Math.cos(halfYaw);
  2612. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  2613. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  2614. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  2615. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  2616. };
  2617. /**
  2618. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  2619. */
  2620. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  2621. var result = new Quaternion();
  2622. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  2623. return result;
  2624. };
  2625. /**
  2626. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  2627. */
  2628. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  2629. // Produces a quaternion from Euler angles in the z-x-z orientation
  2630. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  2631. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  2632. var halfBeta = beta * 0.5;
  2633. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2634. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2635. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2636. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2637. };
  2638. /**
  2639. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2640. * cf to Vector3.RotationFromAxis() documentation.
  2641. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2642. */
  2643. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  2644. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  2645. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  2646. return quat;
  2647. };
  2648. /**
  2649. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2650. * cf to Vector3.RotationFromAxis() documentation.
  2651. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2652. */
  2653. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  2654. var rotMat = MathTmp.Matrix[0];
  2655. BABYLON.Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  2656. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, ref);
  2657. };
  2658. Quaternion.Slerp = function (left, right, amount) {
  2659. var result = Quaternion.Identity();
  2660. Quaternion.SlerpToRef(left, right, amount, result);
  2661. return result;
  2662. };
  2663. Quaternion.SlerpToRef = function (left, right, amount, result) {
  2664. var num2;
  2665. var num3;
  2666. var num = amount;
  2667. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  2668. var flag = false;
  2669. if (num4 < 0) {
  2670. flag = true;
  2671. num4 = -num4;
  2672. }
  2673. if (num4 > 0.999999) {
  2674. num3 = 1 - num;
  2675. num2 = flag ? -num : num;
  2676. }
  2677. else {
  2678. var num5 = Math.acos(num4);
  2679. var num6 = (1.0 / Math.sin(num5));
  2680. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  2681. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  2682. }
  2683. result.x = (num3 * left.x) + (num2 * right.x);
  2684. result.y = (num3 * left.y) + (num2 * right.y);
  2685. result.z = (num3 * left.z) + (num2 * right.z);
  2686. result.w = (num3 * left.w) + (num2 * right.w);
  2687. };
  2688. /**
  2689. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  2690. */
  2691. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2692. var squared = amount * amount;
  2693. var cubed = amount * squared;
  2694. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2695. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2696. var part3 = (cubed - (2.0 * squared)) + amount;
  2697. var part4 = cubed - squared;
  2698. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2699. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2700. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  2701. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  2702. return new Quaternion(x, y, z, w);
  2703. };
  2704. return Quaternion;
  2705. }());
  2706. BABYLON.Quaternion = Quaternion;
  2707. var Matrix = (function () {
  2708. function Matrix() {
  2709. this.m = new Float32Array(16);
  2710. this._markAsUpdated();
  2711. }
  2712. Matrix.prototype._markAsUpdated = function () {
  2713. this.updateFlag = Matrix._updateFlagSeed++;
  2714. };
  2715. // Properties
  2716. /**
  2717. * Boolean : True is the matrix is the identity matrix
  2718. */
  2719. Matrix.prototype.isIdentity = function () {
  2720. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  2721. return false;
  2722. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  2723. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  2724. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  2725. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  2726. return false;
  2727. return true;
  2728. };
  2729. /**
  2730. * Returns the matrix determinant (float).
  2731. */
  2732. Matrix.prototype.determinant = function () {
  2733. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  2734. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  2735. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  2736. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  2737. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  2738. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  2739. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  2740. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  2741. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  2742. };
  2743. // Methods
  2744. /**
  2745. * Returns the matrix underlying array.
  2746. */
  2747. Matrix.prototype.toArray = function () {
  2748. return this.m;
  2749. };
  2750. /**
  2751. * Returns the matrix underlying array.
  2752. */
  2753. Matrix.prototype.asArray = function () {
  2754. return this.toArray();
  2755. };
  2756. /**
  2757. * Inverts in place the Matrix.
  2758. * Returns the Matrix inverted.
  2759. */
  2760. Matrix.prototype.invert = function () {
  2761. this.invertToRef(this);
  2762. return this;
  2763. };
  2764. /**
  2765. * Sets all the matrix elements to zero.
  2766. * Returns the Matrix.
  2767. */
  2768. Matrix.prototype.reset = function () {
  2769. for (var index = 0; index < 16; index++) {
  2770. this.m[index] = 0.0;
  2771. }
  2772. this._markAsUpdated();
  2773. return this;
  2774. };
  2775. /**
  2776. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  2777. */
  2778. Matrix.prototype.add = function (other) {
  2779. var result = new Matrix();
  2780. this.addToRef(other, result);
  2781. return result;
  2782. };
  2783. /**
  2784. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  2785. * Returns the Matrix.
  2786. */
  2787. Matrix.prototype.addToRef = function (other, result) {
  2788. for (var index = 0; index < 16; index++) {
  2789. result.m[index] = this.m[index] + other.m[index];
  2790. }
  2791. result._markAsUpdated();
  2792. return this;
  2793. };
  2794. /**
  2795. * Adds in place the passed matrix to the current Matrix.
  2796. * Returns the updated Matrix.
  2797. */
  2798. Matrix.prototype.addToSelf = function (other) {
  2799. for (var index = 0; index < 16; index++) {
  2800. this.m[index] += other.m[index];
  2801. }
  2802. this._markAsUpdated();
  2803. return this;
  2804. };
  2805. /**
  2806. * Sets the passed matrix with the current inverted Matrix.
  2807. * Returns the unmodified current Matrix.
  2808. */
  2809. Matrix.prototype.invertToRef = function (other) {
  2810. var l1 = this.m[0];
  2811. var l2 = this.m[1];
  2812. var l3 = this.m[2];
  2813. var l4 = this.m[3];
  2814. var l5 = this.m[4];
  2815. var l6 = this.m[5];
  2816. var l7 = this.m[6];
  2817. var l8 = this.m[7];
  2818. var l9 = this.m[8];
  2819. var l10 = this.m[9];
  2820. var l11 = this.m[10];
  2821. var l12 = this.m[11];
  2822. var l13 = this.m[12];
  2823. var l14 = this.m[13];
  2824. var l15 = this.m[14];
  2825. var l16 = this.m[15];
  2826. var l17 = (l11 * l16) - (l12 * l15);
  2827. var l18 = (l10 * l16) - (l12 * l14);
  2828. var l19 = (l10 * l15) - (l11 * l14);
  2829. var l20 = (l9 * l16) - (l12 * l13);
  2830. var l21 = (l9 * l15) - (l11 * l13);
  2831. var l22 = (l9 * l14) - (l10 * l13);
  2832. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  2833. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  2834. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  2835. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  2836. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  2837. var l28 = (l7 * l16) - (l8 * l15);
  2838. var l29 = (l6 * l16) - (l8 * l14);
  2839. var l30 = (l6 * l15) - (l7 * l14);
  2840. var l31 = (l5 * l16) - (l8 * l13);
  2841. var l32 = (l5 * l15) - (l7 * l13);
  2842. var l33 = (l5 * l14) - (l6 * l13);
  2843. var l34 = (l7 * l12) - (l8 * l11);
  2844. var l35 = (l6 * l12) - (l8 * l10);
  2845. var l36 = (l6 * l11) - (l7 * l10);
  2846. var l37 = (l5 * l12) - (l8 * l9);
  2847. var l38 = (l5 * l11) - (l7 * l9);
  2848. var l39 = (l5 * l10) - (l6 * l9);
  2849. other.m[0] = l23 * l27;
  2850. other.m[4] = l24 * l27;
  2851. other.m[8] = l25 * l27;
  2852. other.m[12] = l26 * l27;
  2853. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  2854. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  2855. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  2856. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  2857. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  2858. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  2859. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  2860. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  2861. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  2862. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  2863. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  2864. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  2865. other._markAsUpdated();
  2866. return this;
  2867. };
  2868. /**
  2869. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  2870. * Returns the updated Matrix.
  2871. */
  2872. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  2873. this.m[12] = x;
  2874. this.m[13] = y;
  2875. this.m[14] = z;
  2876. this._markAsUpdated();
  2877. return this;
  2878. };
  2879. /**
  2880. * Inserts the translation vector in the current Matrix.
  2881. * Returns the updated Matrix.
  2882. */
  2883. Matrix.prototype.setTranslation = function (vector3) {
  2884. this.m[12] = vector3.x;
  2885. this.m[13] = vector3.y;
  2886. this.m[14] = vector3.z;
  2887. this._markAsUpdated();
  2888. return this;
  2889. };
  2890. /**
  2891. * Returns a new Vector3 as the extracted translation from the Matrix.
  2892. */
  2893. Matrix.prototype.getTranslation = function () {
  2894. return new Vector3(this.m[12], this.m[13], this.m[14]);
  2895. };
  2896. /**
  2897. * Fill a Vector3 with the extracted translation from the Matrix.
  2898. */
  2899. Matrix.prototype.getTranslationToRef = function (result) {
  2900. result.x = this.m[12];
  2901. result.y = this.m[13];
  2902. result.z = this.m[14];
  2903. return this;
  2904. };
  2905. /**
  2906. * Remove rotation and scaling part from the Matrix.
  2907. * Returns the updated Matrix.
  2908. */
  2909. Matrix.prototype.removeRotationAndScaling = function () {
  2910. this.setRowFromFloats(0, 1, 0, 0, 0);
  2911. this.setRowFromFloats(1, 0, 1, 0, 0);
  2912. this.setRowFromFloats(2, 0, 0, 1, 0);
  2913. return this;
  2914. };
  2915. /**
  2916. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  2917. */
  2918. Matrix.prototype.multiply = function (other) {
  2919. var result = new Matrix();
  2920. this.multiplyToRef(other, result);
  2921. return result;
  2922. };
  2923. /**
  2924. * Updates the current Matrix from the passed one values.
  2925. * Returns the updated Matrix.
  2926. */
  2927. Matrix.prototype.copyFrom = function (other) {
  2928. for (var index = 0; index < 16; index++) {
  2929. this.m[index] = other.m[index];
  2930. }
  2931. this._markAsUpdated();
  2932. return this;
  2933. };
  2934. /**
  2935. * Populates the passed array from the starting index with the Matrix values.
  2936. * Returns the Matrix.
  2937. */
  2938. Matrix.prototype.copyToArray = function (array, offset) {
  2939. if (offset === void 0) { offset = 0; }
  2940. for (var index = 0; index < 16; index++) {
  2941. array[offset + index] = this.m[index];
  2942. }
  2943. return this;
  2944. };
  2945. /**
  2946. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  2947. */
  2948. Matrix.prototype.multiplyToRef = function (other, result) {
  2949. this.multiplyToArray(other, result.m, 0);
  2950. result._markAsUpdated();
  2951. return this;
  2952. };
  2953. /**
  2954. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  2955. */
  2956. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  2957. var tm0 = this.m[0];
  2958. var tm1 = this.m[1];
  2959. var tm2 = this.m[2];
  2960. var tm3 = this.m[3];
  2961. var tm4 = this.m[4];
  2962. var tm5 = this.m[5];
  2963. var tm6 = this.m[6];
  2964. var tm7 = this.m[7];
  2965. var tm8 = this.m[8];
  2966. var tm9 = this.m[9];
  2967. var tm10 = this.m[10];
  2968. var tm11 = this.m[11];
  2969. var tm12 = this.m[12];
  2970. var tm13 = this.m[13];
  2971. var tm14 = this.m[14];
  2972. var tm15 = this.m[15];
  2973. var om0 = other.m[0];
  2974. var om1 = other.m[1];
  2975. var om2 = other.m[2];
  2976. var om3 = other.m[3];
  2977. var om4 = other.m[4];
  2978. var om5 = other.m[5];
  2979. var om6 = other.m[6];
  2980. var om7 = other.m[7];
  2981. var om8 = other.m[8];
  2982. var om9 = other.m[9];
  2983. var om10 = other.m[10];
  2984. var om11 = other.m[11];
  2985. var om12 = other.m[12];
  2986. var om13 = other.m[13];
  2987. var om14 = other.m[14];
  2988. var om15 = other.m[15];
  2989. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  2990. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  2991. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  2992. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  2993. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  2994. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  2995. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  2996. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  2997. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  2998. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  2999. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  3000. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  3001. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  3002. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  3003. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  3004. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  3005. return this;
  3006. };
  3007. /**
  3008. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  3009. */
  3010. Matrix.prototype.equals = function (value) {
  3011. return value &&
  3012. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  3013. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  3014. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  3015. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  3016. };
  3017. /**
  3018. * Returns a new Matrix from the current Matrix.
  3019. */
  3020. Matrix.prototype.clone = function () {
  3021. 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]);
  3022. };
  3023. /**
  3024. * Returns the string "Matrix"
  3025. */
  3026. Matrix.prototype.getClassName = function () {
  3027. return "Matrix";
  3028. };
  3029. /**
  3030. * Returns the Matrix hash code.
  3031. */
  3032. Matrix.prototype.getHashCode = function () {
  3033. var hash = this.m[0] || 0;
  3034. for (var i = 1; i < 16; i++) {
  3035. hash = (hash * 397) ^ (this.m[i] || 0);
  3036. }
  3037. return hash;
  3038. };
  3039. /**
  3040. * Decomposes the current Matrix into :
  3041. * - a scale vector3 passed as a reference to update,
  3042. * - a rotation quaternion passed as a reference to update,
  3043. * - a translation vector3 passed as a reference to update.
  3044. * Returns the boolean `true`.
  3045. */
  3046. Matrix.prototype.decompose = function (scale, rotation, translation) {
  3047. translation.x = this.m[12];
  3048. translation.y = this.m[13];
  3049. translation.z = this.m[14];
  3050. var xs = MathTools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  3051. var ys = MathTools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  3052. var zs = MathTools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  3053. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  3054. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  3055. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  3056. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  3057. rotation.x = 0;
  3058. rotation.y = 0;
  3059. rotation.z = 0;
  3060. rotation.w = 1;
  3061. return false;
  3062. }
  3063. 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]);
  3064. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  3065. return true;
  3066. };
  3067. /**
  3068. * Returns a new Matrix as the extracted rotation matrix from the current one.
  3069. */
  3070. Matrix.prototype.getRotationMatrix = function () {
  3071. var result = Matrix.Identity();
  3072. this.getRotationMatrixToRef(result);
  3073. return result;
  3074. };
  3075. /**
  3076. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  3077. * Returns the current Matrix.
  3078. */
  3079. Matrix.prototype.getRotationMatrixToRef = function (result) {
  3080. var m = this.m;
  3081. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  3082. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  3083. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  3084. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  3085. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  3086. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  3087. 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);
  3088. return this;
  3089. };
  3090. // Statics
  3091. /**
  3092. * Returns a new Matrix set from the starting index of the passed array.
  3093. */
  3094. Matrix.FromArray = function (array, offset) {
  3095. var result = new Matrix();
  3096. if (!offset) {
  3097. offset = 0;
  3098. }
  3099. Matrix.FromArrayToRef(array, offset, result);
  3100. return result;
  3101. };
  3102. /**
  3103. * Sets the passed "result" matrix from the starting index of the passed array.
  3104. */
  3105. Matrix.FromArrayToRef = function (array, offset, result) {
  3106. for (var index = 0; index < 16; index++) {
  3107. result.m[index] = array[index + offset];
  3108. }
  3109. result._markAsUpdated();
  3110. };
  3111. /**
  3112. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  3113. */
  3114. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  3115. for (var index = 0; index < 16; index++) {
  3116. result.m[index] = array[index + offset] * scale;
  3117. }
  3118. result._markAsUpdated();
  3119. };
  3120. /**
  3121. * Sets the passed matrix "result" with the 16 passed floats.
  3122. */
  3123. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  3124. result.m[0] = initialM11;
  3125. result.m[1] = initialM12;
  3126. result.m[2] = initialM13;
  3127. result.m[3] = initialM14;
  3128. result.m[4] = initialM21;
  3129. result.m[5] = initialM22;
  3130. result.m[6] = initialM23;
  3131. result.m[7] = initialM24;
  3132. result.m[8] = initialM31;
  3133. result.m[9] = initialM32;
  3134. result.m[10] = initialM33;
  3135. result.m[11] = initialM34;
  3136. result.m[12] = initialM41;
  3137. result.m[13] = initialM42;
  3138. result.m[14] = initialM43;
  3139. result.m[15] = initialM44;
  3140. result._markAsUpdated();
  3141. };
  3142. /**
  3143. * Returns the index-th row of the current matrix as a new Vector4.
  3144. */
  3145. Matrix.prototype.getRow = function (index) {
  3146. if (index < 0 || index > 3) {
  3147. return null;
  3148. }
  3149. var i = index * 4;
  3150. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  3151. };
  3152. /**
  3153. * Sets the index-th row of the current matrix with the passed Vector4 values.
  3154. * Returns the updated Matrix.
  3155. */
  3156. Matrix.prototype.setRow = function (index, row) {
  3157. if (index < 0 || index > 3) {
  3158. return this;
  3159. }
  3160. var i = index * 4;
  3161. this.m[i + 0] = row.x;
  3162. this.m[i + 1] = row.y;
  3163. this.m[i + 2] = row.z;
  3164. this.m[i + 3] = row.w;
  3165. this._markAsUpdated();
  3166. return this;
  3167. };
  3168. /**
  3169. * Sets the index-th row of the current matrix with the passed 4 x float values.
  3170. * Returns the updated Matrix.
  3171. */
  3172. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  3173. if (index < 0 || index > 3) {
  3174. return this;
  3175. }
  3176. var i = index * 4;
  3177. this.m[i + 0] = x;
  3178. this.m[i + 1] = y;
  3179. this.m[i + 2] = z;
  3180. this.m[i + 3] = w;
  3181. this._markAsUpdated();
  3182. return this;
  3183. };
  3184. /**
  3185. * Returns a new Matrix set from the 16 passed floats.
  3186. */
  3187. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  3188. var result = new Matrix();
  3189. result.m[0] = initialM11;
  3190. result.m[1] = initialM12;
  3191. result.m[2] = initialM13;
  3192. result.m[3] = initialM14;
  3193. result.m[4] = initialM21;
  3194. result.m[5] = initialM22;
  3195. result.m[6] = initialM23;
  3196. result.m[7] = initialM24;
  3197. result.m[8] = initialM31;
  3198. result.m[9] = initialM32;
  3199. result.m[10] = initialM33;
  3200. result.m[11] = initialM34;
  3201. result.m[12] = initialM41;
  3202. result.m[13] = initialM42;
  3203. result.m[14] = initialM43;
  3204. result.m[15] = initialM44;
  3205. return result;
  3206. };
  3207. /**
  3208. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3209. */
  3210. Matrix.Compose = function (scale, rotation, translation) {
  3211. var result = Matrix.Identity();
  3212. Matrix.ComposeToRef(scale, rotation, translation, result);
  3213. return result;
  3214. };
  3215. /**
  3216. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3217. */
  3218. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  3219. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  3220. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  3221. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  3222. result.setTranslation(translation);
  3223. };
  3224. /**
  3225. * Returns a new indentity Matrix.
  3226. */
  3227. Matrix.Identity = function () {
  3228. 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);
  3229. };
  3230. /**
  3231. * Sets the passed "result" as an identity matrix.
  3232. */
  3233. Matrix.IdentityToRef = function (result) {
  3234. 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);
  3235. };
  3236. /**
  3237. * Returns a new zero Matrix.
  3238. */
  3239. Matrix.Zero = function () {
  3240. 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);
  3241. };
  3242. /**
  3243. * Returns a new rotation matrix for "angle" radians around the X axis.
  3244. */
  3245. Matrix.RotationX = function (angle) {
  3246. var result = new Matrix();
  3247. Matrix.RotationXToRef(angle, result);
  3248. return result;
  3249. };
  3250. /**
  3251. * Returns a new Matrix as the passed inverted one.
  3252. */
  3253. Matrix.Invert = function (source) {
  3254. var result = new Matrix();
  3255. source.invertToRef(result);
  3256. return result;
  3257. };
  3258. /**
  3259. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  3260. */
  3261. Matrix.RotationXToRef = function (angle, result) {
  3262. var s = Math.sin(angle);
  3263. var c = Math.cos(angle);
  3264. result.m[0] = 1.0;
  3265. result.m[15] = 1.0;
  3266. result.m[5] = c;
  3267. result.m[10] = c;
  3268. result.m[9] = -s;
  3269. result.m[6] = s;
  3270. result.m[1] = 0.0;
  3271. result.m[2] = 0.0;
  3272. result.m[3] = 0.0;
  3273. result.m[4] = 0.0;
  3274. result.m[7] = 0.0;
  3275. result.m[8] = 0.0;
  3276. result.m[11] = 0.0;
  3277. result.m[12] = 0.0;
  3278. result.m[13] = 0.0;
  3279. result.m[14] = 0.0;
  3280. result._markAsUpdated();
  3281. };
  3282. /**
  3283. * Returns a new rotation matrix for "angle" radians around the Y axis.
  3284. */
  3285. Matrix.RotationY = function (angle) {
  3286. var result = new Matrix();
  3287. Matrix.RotationYToRef(angle, result);
  3288. return result;
  3289. };
  3290. /**
  3291. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  3292. */
  3293. Matrix.RotationYToRef = function (angle, result) {
  3294. var s = Math.sin(angle);
  3295. var c = Math.cos(angle);
  3296. result.m[5] = 1.0;
  3297. result.m[15] = 1.0;
  3298. result.m[0] = c;
  3299. result.m[2] = -s;
  3300. result.m[8] = s;
  3301. result.m[10] = c;
  3302. result.m[1] = 0.0;
  3303. result.m[3] = 0.0;
  3304. result.m[4] = 0.0;
  3305. result.m[6] = 0.0;
  3306. result.m[7] = 0.0;
  3307. result.m[9] = 0.0;
  3308. result.m[11] = 0.0;
  3309. result.m[12] = 0.0;
  3310. result.m[13] = 0.0;
  3311. result.m[14] = 0.0;
  3312. result._markAsUpdated();
  3313. };
  3314. /**
  3315. * Returns a new rotation matrix for "angle" radians around the Z axis.
  3316. */
  3317. Matrix.RotationZ = function (angle) {
  3318. var result = new Matrix();
  3319. Matrix.RotationZToRef(angle, result);
  3320. return result;
  3321. };
  3322. /**
  3323. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  3324. */
  3325. Matrix.RotationZToRef = function (angle, result) {
  3326. var s = Math.sin(angle);
  3327. var c = Math.cos(angle);
  3328. result.m[10] = 1.0;
  3329. result.m[15] = 1.0;
  3330. result.m[0] = c;
  3331. result.m[1] = s;
  3332. result.m[4] = -s;
  3333. result.m[5] = c;
  3334. result.m[2] = 0.0;
  3335. result.m[3] = 0.0;
  3336. result.m[6] = 0.0;
  3337. result.m[7] = 0.0;
  3338. result.m[8] = 0.0;
  3339. result.m[9] = 0.0;
  3340. result.m[11] = 0.0;
  3341. result.m[12] = 0.0;
  3342. result.m[13] = 0.0;
  3343. result.m[14] = 0.0;
  3344. result._markAsUpdated();
  3345. };
  3346. /**
  3347. * Returns a new rotation matrix for "angle" radians around the passed axis.
  3348. */
  3349. Matrix.RotationAxis = function (axis, angle) {
  3350. var result = Matrix.Zero();
  3351. Matrix.RotationAxisToRef(axis, angle, result);
  3352. return result;
  3353. };
  3354. /**
  3355. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  3356. */
  3357. Matrix.RotationAxisToRef = function (axis, angle, result) {
  3358. var s = Math.sin(-angle);
  3359. var c = Math.cos(-angle);
  3360. var c1 = 1 - c;
  3361. axis.normalize();
  3362. result.m[0] = (axis.x * axis.x) * c1 + c;
  3363. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  3364. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  3365. result.m[3] = 0.0;
  3366. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  3367. result.m[5] = (axis.y * axis.y) * c1 + c;
  3368. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  3369. result.m[7] = 0.0;
  3370. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  3371. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  3372. result.m[10] = (axis.z * axis.z) * c1 + c;
  3373. result.m[11] = 0.0;
  3374. result.m[15] = 1.0;
  3375. result._markAsUpdated();
  3376. };
  3377. /**
  3378. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  3379. */
  3380. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  3381. var result = new Matrix();
  3382. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  3383. return result;
  3384. };
  3385. /**
  3386. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  3387. */
  3388. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  3389. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  3390. this._tempQuaternion.toRotationMatrix(result);
  3391. };
  3392. /**
  3393. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  3394. */
  3395. Matrix.Scaling = function (x, y, z) {
  3396. var result = Matrix.Zero();
  3397. Matrix.ScalingToRef(x, y, z, result);
  3398. return result;
  3399. };
  3400. /**
  3401. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  3402. */
  3403. Matrix.ScalingToRef = function (x, y, z, result) {
  3404. result.m[0] = x;
  3405. result.m[1] = 0.0;
  3406. result.m[2] = 0.0;
  3407. result.m[3] = 0.0;
  3408. result.m[4] = 0.0;
  3409. result.m[5] = y;
  3410. result.m[6] = 0.0;
  3411. result.m[7] = 0.0;
  3412. result.m[8] = 0.0;
  3413. result.m[9] = 0.0;
  3414. result.m[10] = z;
  3415. result.m[11] = 0.0;
  3416. result.m[12] = 0.0;
  3417. result.m[13] = 0.0;
  3418. result.m[14] = 0.0;
  3419. result.m[15] = 1.0;
  3420. result._markAsUpdated();
  3421. };
  3422. /**
  3423. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  3424. */
  3425. Matrix.Translation = function (x, y, z) {
  3426. var result = Matrix.Identity();
  3427. Matrix.TranslationToRef(x, y, z, result);
  3428. return result;
  3429. };
  3430. /**
  3431. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  3432. */
  3433. Matrix.TranslationToRef = function (x, y, z, result) {
  3434. 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);
  3435. };
  3436. /**
  3437. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  3438. */
  3439. Matrix.Lerp = function (startValue, endValue, gradient) {
  3440. var result = Matrix.Zero();
  3441. for (var index = 0; index < 16; index++) {
  3442. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  3443. }
  3444. result._markAsUpdated();
  3445. return result;
  3446. };
  3447. /**
  3448. * Returns a new Matrix whose values are computed by :
  3449. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  3450. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  3451. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  3452. */
  3453. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  3454. var startScale = new Vector3(0, 0, 0);
  3455. var startRotation = new Quaternion();
  3456. var startTranslation = new Vector3(0, 0, 0);
  3457. startValue.decompose(startScale, startRotation, startTranslation);
  3458. var endScale = new Vector3(0, 0, 0);
  3459. var endRotation = new Quaternion();
  3460. var endTranslation = new Vector3(0, 0, 0);
  3461. endValue.decompose(endScale, endRotation, endTranslation);
  3462. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  3463. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  3464. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  3465. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  3466. };
  3467. /**
  3468. * 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".
  3469. * This methods works for a Left-Handed system.
  3470. */
  3471. Matrix.LookAtLH = function (eye, target, up) {
  3472. var result = Matrix.Zero();
  3473. Matrix.LookAtLHToRef(eye, target, up, result);
  3474. return result;
  3475. };
  3476. /**
  3477. * 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".
  3478. * This methods works for a Left-Handed system.
  3479. */
  3480. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  3481. // Z axis
  3482. target.subtractToRef(eye, this._zAxis);
  3483. this._zAxis.normalize();
  3484. // X axis
  3485. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3486. if (this._xAxis.lengthSquared() === 0) {
  3487. this._xAxis.x = 1.0;
  3488. }
  3489. else {
  3490. this._xAxis.normalize();
  3491. }
  3492. // Y axis
  3493. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3494. this._yAxis.normalize();
  3495. // Eye angles
  3496. var ex = -Vector3.Dot(this._xAxis, eye);
  3497. var ey = -Vector3.Dot(this._yAxis, eye);
  3498. var ez = -Vector3.Dot(this._zAxis, eye);
  3499. 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);
  3500. };
  3501. /**
  3502. * 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".
  3503. * This methods works for a Right-Handed system.
  3504. */
  3505. Matrix.LookAtRH = function (eye, target, up) {
  3506. var result = Matrix.Zero();
  3507. Matrix.LookAtRHToRef(eye, target, up, result);
  3508. return result;
  3509. };
  3510. /**
  3511. * 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".
  3512. * This methods works for a Left-Handed system.
  3513. */
  3514. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  3515. // Z axis
  3516. eye.subtractToRef(target, this._zAxis);
  3517. this._zAxis.normalize();
  3518. // X axis
  3519. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3520. if (this._xAxis.lengthSquared() === 0) {
  3521. this._xAxis.x = 1.0;
  3522. }
  3523. else {
  3524. this._xAxis.normalize();
  3525. }
  3526. // Y axis
  3527. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3528. this._yAxis.normalize();
  3529. // Eye angles
  3530. var ex = -Vector3.Dot(this._xAxis, eye);
  3531. var ey = -Vector3.Dot(this._yAxis, eye);
  3532. var ez = -Vector3.Dot(this._zAxis, eye);
  3533. 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);
  3534. };
  3535. /**
  3536. * 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.
  3537. */
  3538. Matrix.OrthoLH = function (width, height, znear, zfar) {
  3539. var matrix = Matrix.Zero();
  3540. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  3541. return matrix;
  3542. };
  3543. /**
  3544. * 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.
  3545. */
  3546. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  3547. var n = znear;
  3548. var f = zfar;
  3549. var a = 2.0 / width;
  3550. var b = 2.0 / height;
  3551. var c = 2.0 / (f - n);
  3552. var d = -(f + n) / (f - n);
  3553. 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);
  3554. };
  3555. /**
  3556. * 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.
  3557. */
  3558. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  3559. var matrix = Matrix.Zero();
  3560. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  3561. return matrix;
  3562. };
  3563. /**
  3564. * 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.
  3565. */
  3566. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3567. var n = znear;
  3568. var f = zfar;
  3569. var a = 2.0 / (right - left);
  3570. var b = 2.0 / (top - bottom);
  3571. var c = 2.0 / (f - n);
  3572. var d = -(f + n) / (f - n);
  3573. var i0 = (left + right) / (left - right);
  3574. var i1 = (top + bottom) / (bottom - top);
  3575. 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);
  3576. };
  3577. /**
  3578. * 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.
  3579. */
  3580. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  3581. var matrix = Matrix.Zero();
  3582. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  3583. return matrix;
  3584. };
  3585. /**
  3586. * 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.
  3587. */
  3588. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3589. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  3590. result.m[10] *= -1.0;
  3591. };
  3592. /**
  3593. * 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.
  3594. */
  3595. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  3596. var matrix = Matrix.Zero();
  3597. var n = znear;
  3598. var f = zfar;
  3599. var a = 2.0 * n / width;
  3600. var b = 2.0 * n / height;
  3601. var c = (f + n) / (f - n);
  3602. var d = -2.0 * f * n / (f - n);
  3603. 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);
  3604. return matrix;
  3605. };
  3606. /**
  3607. * 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.
  3608. */
  3609. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  3610. var matrix = Matrix.Zero();
  3611. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  3612. return matrix;
  3613. };
  3614. /**
  3615. * 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.
  3616. */
  3617. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3618. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3619. var n = znear;
  3620. var f = zfar;
  3621. var t = 1.0 / (Math.tan(fov * 0.5));
  3622. var a = isVerticalFovFixed ? (t / aspect) : t;
  3623. var b = isVerticalFovFixed ? t : (t * aspect);
  3624. var c = (f + n) / (f - n);
  3625. var d = -2.0 * f * n / (f - n);
  3626. 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);
  3627. };
  3628. /**
  3629. * 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.
  3630. */
  3631. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  3632. var matrix = Matrix.Zero();
  3633. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  3634. return matrix;
  3635. };
  3636. /**
  3637. * 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.
  3638. */
  3639. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3640. //alternatively this could be expressed as:
  3641. // m = PerspectiveFovLHToRef
  3642. // m[10] *= -1.0;
  3643. // m[11] *= -1.0;
  3644. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3645. var n = znear;
  3646. var f = zfar;
  3647. var t = 1.0 / (Math.tan(fov * 0.5));
  3648. var a = isVerticalFovFixed ? (t / aspect) : t;
  3649. var b = isVerticalFovFixed ? t : (t * aspect);
  3650. var c = -(f + n) / (f - n);
  3651. var d = -2 * f * n / (f - n);
  3652. 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);
  3653. };
  3654. /**
  3655. * 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.
  3656. */
  3657. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  3658. if (rightHanded === void 0) { rightHanded = false; }
  3659. var rightHandedFactor = rightHanded ? -1 : 1;
  3660. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  3661. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  3662. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  3663. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  3664. var xScale = 2.0 / (leftTan + rightTan);
  3665. var yScale = 2.0 / (upTan + downTan);
  3666. result.m[0] = xScale;
  3667. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  3668. result.m[5] = yScale;
  3669. result.m[6] = result.m[7] = 0.0;
  3670. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  3671. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  3672. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  3673. result.m[10] = -zfar / (znear - zfar);
  3674. result.m[11] = 1.0 * rightHandedFactor;
  3675. result.m[12] = result.m[13] = result.m[15] = 0.0;
  3676. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  3677. // result.m[14] = (znear * zfar) / (znear - zfar);
  3678. result._markAsUpdated();
  3679. };
  3680. /**
  3681. * Returns the final transformation matrix : world * view * projection * viewport
  3682. */
  3683. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  3684. var cw = viewport.width;
  3685. var ch = viewport.height;
  3686. var cx = viewport.x;
  3687. var cy = viewport.y;
  3688. 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);
  3689. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  3690. };
  3691. /**
  3692. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  3693. */
  3694. Matrix.GetAsMatrix2x2 = function (matrix) {
  3695. return new Float32Array([
  3696. matrix.m[0], matrix.m[1],
  3697. matrix.m[4], matrix.m[5]
  3698. ]);
  3699. };
  3700. /**
  3701. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  3702. */
  3703. Matrix.GetAsMatrix3x3 = function (matrix) {
  3704. return new Float32Array([
  3705. matrix.m[0], matrix.m[1], matrix.m[2],
  3706. matrix.m[4], matrix.m[5], matrix.m[6],
  3707. matrix.m[8], matrix.m[9], matrix.m[10]
  3708. ]);
  3709. };
  3710. /**
  3711. * Compute the transpose of the passed Matrix.
  3712. * Returns a new Matrix.
  3713. */
  3714. Matrix.Transpose = function (matrix) {
  3715. var result = new Matrix();
  3716. result.m[0] = matrix.m[0];
  3717. result.m[1] = matrix.m[4];
  3718. result.m[2] = matrix.m[8];
  3719. result.m[3] = matrix.m[12];
  3720. result.m[4] = matrix.m[1];
  3721. result.m[5] = matrix.m[5];
  3722. result.m[6] = matrix.m[9];
  3723. result.m[7] = matrix.m[13];
  3724. result.m[8] = matrix.m[2];
  3725. result.m[9] = matrix.m[6];
  3726. result.m[10] = matrix.m[10];
  3727. result.m[11] = matrix.m[14];
  3728. result.m[12] = matrix.m[3];
  3729. result.m[13] = matrix.m[7];
  3730. result.m[14] = matrix.m[11];
  3731. result.m[15] = matrix.m[15];
  3732. return result;
  3733. };
  3734. /**
  3735. * Returns a new Matrix as the reflection matrix across the passed plane.
  3736. */
  3737. Matrix.Reflection = function (plane) {
  3738. var matrix = new Matrix();
  3739. Matrix.ReflectionToRef(plane, matrix);
  3740. return matrix;
  3741. };
  3742. /**
  3743. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  3744. */
  3745. Matrix.ReflectionToRef = function (plane, result) {
  3746. plane.normalize();
  3747. var x = plane.normal.x;
  3748. var y = plane.normal.y;
  3749. var z = plane.normal.z;
  3750. var temp = -2 * x;
  3751. var temp2 = -2 * y;
  3752. var temp3 = -2 * z;
  3753. result.m[0] = (temp * x) + 1;
  3754. result.m[1] = temp2 * x;
  3755. result.m[2] = temp3 * x;
  3756. result.m[3] = 0.0;
  3757. result.m[4] = temp * y;
  3758. result.m[5] = (temp2 * y) + 1;
  3759. result.m[6] = temp3 * y;
  3760. result.m[7] = 0.0;
  3761. result.m[8] = temp * z;
  3762. result.m[9] = temp2 * z;
  3763. result.m[10] = (temp3 * z) + 1;
  3764. result.m[11] = 0.0;
  3765. result.m[12] = temp * plane.d;
  3766. result.m[13] = temp2 * plane.d;
  3767. result.m[14] = temp3 * plane.d;
  3768. result.m[15] = 1.0;
  3769. result._markAsUpdated();
  3770. };
  3771. /**
  3772. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  3773. */
  3774. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  3775. result.m[0] = xaxis.x;
  3776. result.m[1] = xaxis.y;
  3777. result.m[2] = xaxis.z;
  3778. result.m[3] = 0.0;
  3779. result.m[4] = yaxis.x;
  3780. result.m[5] = yaxis.y;
  3781. result.m[6] = yaxis.z;
  3782. result.m[7] = 0.0;
  3783. result.m[8] = zaxis.x;
  3784. result.m[9] = zaxis.y;
  3785. result.m[10] = zaxis.z;
  3786. result.m[11] = 0.0;
  3787. result.m[12] = 0.0;
  3788. result.m[13] = 0.0;
  3789. result.m[14] = 0.0;
  3790. result.m[15] = 1.0;
  3791. result._markAsUpdated();
  3792. };
  3793. /**
  3794. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  3795. */
  3796. Matrix.FromQuaternionToRef = function (quat, result) {
  3797. var xx = quat.x * quat.x;
  3798. var yy = quat.y * quat.y;
  3799. var zz = quat.z * quat.z;
  3800. var xy = quat.x * quat.y;
  3801. var zw = quat.z * quat.w;
  3802. var zx = quat.z * quat.x;
  3803. var yw = quat.y * quat.w;
  3804. var yz = quat.y * quat.z;
  3805. var xw = quat.x * quat.w;
  3806. result.m[0] = 1.0 - (2.0 * (yy + zz));
  3807. result.m[1] = 2.0 * (xy + zw);
  3808. result.m[2] = 2.0 * (zx - yw);
  3809. result.m[3] = 0.0;
  3810. result.m[4] = 2.0 * (xy - zw);
  3811. result.m[5] = 1.0 - (2.0 * (zz + xx));
  3812. result.m[6] = 2.0 * (yz + xw);
  3813. result.m[7] = 0.0;
  3814. result.m[8] = 2.0 * (zx + yw);
  3815. result.m[9] = 2.0 * (yz - xw);
  3816. result.m[10] = 1.0 - (2.0 * (yy + xx));
  3817. result.m[11] = 0.0;
  3818. result.m[12] = 0.0;
  3819. result.m[13] = 0.0;
  3820. result.m[14] = 0.0;
  3821. result.m[15] = 1.0;
  3822. result._markAsUpdated();
  3823. };
  3824. return Matrix;
  3825. }());
  3826. Matrix._tempQuaternion = new Quaternion();
  3827. Matrix._xAxis = Vector3.Zero();
  3828. Matrix._yAxis = Vector3.Zero();
  3829. Matrix._zAxis = Vector3.Zero();
  3830. Matrix._updateFlagSeed = 0;
  3831. BABYLON.Matrix = Matrix;
  3832. var Plane = (function () {
  3833. /**
  3834. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  3835. */
  3836. function Plane(a, b, c, d) {
  3837. this.normal = new Vector3(a, b, c);
  3838. this.d = d;
  3839. }
  3840. /**
  3841. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  3842. */
  3843. Plane.prototype.asArray = function () {
  3844. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  3845. };
  3846. // Methods
  3847. /**
  3848. * Returns a new plane copied from the current Plane.
  3849. */
  3850. Plane.prototype.clone = function () {
  3851. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  3852. };
  3853. /**
  3854. * Returns the string "Plane".
  3855. */
  3856. Plane.prototype.getClassName = function () {
  3857. return "Plane";
  3858. };
  3859. /**
  3860. * Returns the Plane hash code.
  3861. */
  3862. Plane.prototype.getHashCode = function () {
  3863. var hash = this.normal.getHashCode();
  3864. hash = (hash * 397) ^ (this.d || 0);
  3865. return hash;
  3866. };
  3867. /**
  3868. * Normalize the current Plane in place.
  3869. * Returns the updated Plane.
  3870. */
  3871. Plane.prototype.normalize = function () {
  3872. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  3873. var magnitude = 0.0;
  3874. if (norm !== 0) {
  3875. magnitude = 1.0 / norm;
  3876. }
  3877. this.normal.x *= magnitude;
  3878. this.normal.y *= magnitude;
  3879. this.normal.z *= magnitude;
  3880. this.d *= magnitude;
  3881. return this;
  3882. };
  3883. /**
  3884. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  3885. */
  3886. Plane.prototype.transform = function (transformation) {
  3887. var transposedMatrix = Matrix.Transpose(transformation);
  3888. var x = this.normal.x;
  3889. var y = this.normal.y;
  3890. var z = this.normal.z;
  3891. var d = this.d;
  3892. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  3893. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  3894. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  3895. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  3896. return new Plane(normalX, normalY, normalZ, finalD);
  3897. };
  3898. /**
  3899. * Returns the dot product (float) of the point coordinates and the plane normal.
  3900. */
  3901. Plane.prototype.dotCoordinate = function (point) {
  3902. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  3903. };
  3904. /**
  3905. * Updates the current Plane from the plane defined by the three passed points.
  3906. * Returns the updated Plane.
  3907. */
  3908. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  3909. var x1 = point2.x - point1.x;
  3910. var y1 = point2.y - point1.y;
  3911. var z1 = point2.z - point1.z;
  3912. var x2 = point3.x - point1.x;
  3913. var y2 = point3.y - point1.y;
  3914. var z2 = point3.z - point1.z;
  3915. var yz = (y1 * z2) - (z1 * y2);
  3916. var xz = (z1 * x2) - (x1 * z2);
  3917. var xy = (x1 * y2) - (y1 * x2);
  3918. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  3919. var invPyth;
  3920. if (pyth !== 0) {
  3921. invPyth = 1.0 / pyth;
  3922. }
  3923. else {
  3924. invPyth = 0.0;
  3925. }
  3926. this.normal.x = yz * invPyth;
  3927. this.normal.y = xz * invPyth;
  3928. this.normal.z = xy * invPyth;
  3929. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  3930. return this;
  3931. };
  3932. /**
  3933. * Boolean : True is the vector "direction" is the same side than the plane normal.
  3934. */
  3935. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  3936. var dot = Vector3.Dot(this.normal, direction);
  3937. return (dot <= epsilon);
  3938. };
  3939. /**
  3940. * Returns the signed distance (float) from the passed point to the Plane.
  3941. */
  3942. Plane.prototype.signedDistanceTo = function (point) {
  3943. return Vector3.Dot(point, this.normal) + this.d;
  3944. };
  3945. // Statics
  3946. /**
  3947. * Returns a new Plane from the passed array.
  3948. */
  3949. Plane.FromArray = function (array) {
  3950. return new Plane(array[0], array[1], array[2], array[3]);
  3951. };
  3952. /**
  3953. * Returns a new Plane defined by the three passed points.
  3954. */
  3955. Plane.FromPoints = function (point1, point2, point3) {
  3956. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  3957. result.copyFromPoints(point1, point2, point3);
  3958. return result;
  3959. };
  3960. /**
  3961. * Returns a new Plane the normal vector to this plane at the passed origin point.
  3962. * Note : the vector "normal" is updated because normalized.
  3963. */
  3964. Plane.FromPositionAndNormal = function (origin, normal) {
  3965. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  3966. normal.normalize();
  3967. result.normal = normal;
  3968. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  3969. return result;
  3970. };
  3971. /**
  3972. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  3973. */
  3974. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  3975. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  3976. return Vector3.Dot(point, normal) + d;
  3977. };
  3978. return Plane;
  3979. }());
  3980. BABYLON.Plane = Plane;
  3981. var Viewport = (function () {
  3982. /**
  3983. * Creates a Viewport object located at (x, y) and sized (width, height).
  3984. */
  3985. function Viewport(x, y, width, height) {
  3986. this.x = x;
  3987. this.y = y;
  3988. this.width = width;
  3989. this.height = height;
  3990. }
  3991. Viewport.prototype.toGlobal = function (renderWidth, renderHeight) {
  3992. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  3993. };
  3994. /**
  3995. * Returns a new Viewport copied from the current one.
  3996. */
  3997. Viewport.prototype.clone = function () {
  3998. return new Viewport(this.x, this.y, this.width, this.height);
  3999. };
  4000. return Viewport;
  4001. }());
  4002. BABYLON.Viewport = Viewport;
  4003. var Frustum = (function () {
  4004. function Frustum() {
  4005. }
  4006. /**
  4007. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  4008. */
  4009. Frustum.GetPlanes = function (transform) {
  4010. var frustumPlanes = [];
  4011. for (var index = 0; index < 6; index++) {
  4012. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  4013. }
  4014. Frustum.GetPlanesToRef(transform, frustumPlanes);
  4015. return frustumPlanes;
  4016. };
  4017. /**
  4018. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  4019. */
  4020. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  4021. // Near
  4022. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  4023. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  4024. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  4025. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  4026. frustumPlanes[0].normalize();
  4027. // Far
  4028. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  4029. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  4030. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  4031. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  4032. frustumPlanes[1].normalize();
  4033. // Left
  4034. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  4035. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  4036. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  4037. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  4038. frustumPlanes[2].normalize();
  4039. // Right
  4040. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  4041. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  4042. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  4043. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  4044. frustumPlanes[3].normalize();
  4045. // Top
  4046. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  4047. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  4048. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  4049. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  4050. frustumPlanes[4].normalize();
  4051. // Bottom
  4052. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  4053. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  4054. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  4055. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  4056. frustumPlanes[5].normalize();
  4057. };
  4058. return Frustum;
  4059. }());
  4060. BABYLON.Frustum = Frustum;
  4061. var Space;
  4062. (function (Space) {
  4063. Space[Space["LOCAL"] = 0] = "LOCAL";
  4064. Space[Space["WORLD"] = 1] = "WORLD";
  4065. Space[Space["BONE"] = 2] = "BONE";
  4066. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  4067. var Axis = (function () {
  4068. function Axis() {
  4069. }
  4070. return Axis;
  4071. }());
  4072. Axis.X = new Vector3(1.0, 0.0, 0.0);
  4073. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  4074. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  4075. BABYLON.Axis = Axis;
  4076. ;
  4077. var BezierCurve = (function () {
  4078. function BezierCurve() {
  4079. }
  4080. /**
  4081. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  4082. */
  4083. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  4084. // Extract X (which is equal to time here)
  4085. var f0 = 1 - 3 * x2 + 3 * x1;
  4086. var f1 = 3 * x2 - 6 * x1;
  4087. var f2 = 3 * x1;
  4088. var refinedT = t;
  4089. for (var i = 0; i < 5; i++) {
  4090. var refinedT2 = refinedT * refinedT;
  4091. var refinedT3 = refinedT2 * refinedT;
  4092. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  4093. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  4094. refinedT -= (x - t) * slope;
  4095. refinedT = Math.min(1, Math.max(0, refinedT));
  4096. }
  4097. // Resolve cubic bezier for the given x
  4098. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  4099. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  4100. Math.pow(refinedT, 3);
  4101. };
  4102. return BezierCurve;
  4103. }());
  4104. BABYLON.BezierCurve = BezierCurve;
  4105. var Orientation;
  4106. (function (Orientation) {
  4107. Orientation[Orientation["CW"] = 0] = "CW";
  4108. Orientation[Orientation["CCW"] = 1] = "CCW";
  4109. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  4110. var Angle = (function () {
  4111. /**
  4112. * Creates an Angle object of "radians" radians (float).
  4113. */
  4114. function Angle(radians) {
  4115. var _this = this;
  4116. /**
  4117. * Returns the Angle value in degrees (float).
  4118. */
  4119. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  4120. /**
  4121. * Returns the Angle value in radians (float).
  4122. */
  4123. this.radians = function () { return _this._radians; };
  4124. this._radians = radians;
  4125. if (this._radians < 0.0)
  4126. this._radians += (2.0 * Math.PI);
  4127. }
  4128. /**
  4129. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  4130. */
  4131. Angle.BetweenTwoPoints = function (a, b) {
  4132. var delta = b.subtract(a);
  4133. var theta = Math.atan2(delta.y, delta.x);
  4134. return new Angle(theta);
  4135. };
  4136. /**
  4137. * Returns a new Angle object from the passed float in radians.
  4138. */
  4139. Angle.FromRadians = function (radians) {
  4140. return new Angle(radians);
  4141. };
  4142. /**
  4143. * Returns a new Angle object from the passed float in degrees.
  4144. */
  4145. Angle.FromDegrees = function (degrees) {
  4146. return new Angle(degrees * Math.PI / 180.0);
  4147. };
  4148. return Angle;
  4149. }());
  4150. BABYLON.Angle = Angle;
  4151. var Arc2 = (function () {
  4152. /**
  4153. * Creates an Arc object from the three passed points : start, middle and end.
  4154. */
  4155. function Arc2(startPoint, midPoint, endPoint) {
  4156. this.startPoint = startPoint;
  4157. this.midPoint = midPoint;
  4158. this.endPoint = endPoint;
  4159. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  4160. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  4161. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  4162. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  4163. 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);
  4164. this.radius = this.centerPoint.subtract(this.startPoint).length();
  4165. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  4166. var a1 = this.startAngle.degrees();
  4167. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  4168. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  4169. // angles correction
  4170. if (a2 - a1 > +180.0)
  4171. a2 -= 360.0;
  4172. if (a2 - a1 < -180.0)
  4173. a2 += 360.0;
  4174. if (a3 - a2 > +180.0)
  4175. a3 -= 360.0;
  4176. if (a3 - a2 < -180.0)
  4177. a3 += 360.0;
  4178. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  4179. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  4180. }
  4181. return Arc2;
  4182. }());
  4183. BABYLON.Arc2 = Arc2;
  4184. var Path2 = (function () {
  4185. /**
  4186. * Creates a Path2 object from the starting 2D coordinates x and y.
  4187. */
  4188. function Path2(x, y) {
  4189. this._points = new Array();
  4190. this._length = 0.0;
  4191. this.closed = false;
  4192. this._points.push(new Vector2(x, y));
  4193. }
  4194. /**
  4195. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  4196. * Returns the updated Path2.
  4197. */
  4198. Path2.prototype.addLineTo = function (x, y) {
  4199. if (closed) {
  4200. //Tools.Error("cannot add lines to closed paths");
  4201. return this;
  4202. }
  4203. var newPoint = new Vector2(x, y);
  4204. var previousPoint = this._points[this._points.length - 1];
  4205. this._points.push(newPoint);
  4206. this._length += newPoint.subtract(previousPoint).length();
  4207. return this;
  4208. };
  4209. /**
  4210. * 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.
  4211. * Returns the updated Path2.
  4212. */
  4213. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  4214. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  4215. if (closed) {
  4216. //Tools.Error("cannot add arcs to closed paths");
  4217. return this;
  4218. }
  4219. var startPoint = this._points[this._points.length - 1];
  4220. var midPoint = new Vector2(midX, midY);
  4221. var endPoint = new Vector2(endX, endY);
  4222. var arc = new Arc2(startPoint, midPoint, endPoint);
  4223. var increment = arc.angle.radians() / numberOfSegments;
  4224. if (arc.orientation === Orientation.CW)
  4225. increment *= -1;
  4226. var currentAngle = arc.startAngle.radians() + increment;
  4227. for (var i = 0; i < numberOfSegments; i++) {
  4228. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  4229. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  4230. this.addLineTo(x, y);
  4231. currentAngle += increment;
  4232. }
  4233. return this;
  4234. };
  4235. /**
  4236. * Closes the Path2.
  4237. * Returns the Path2.
  4238. */
  4239. Path2.prototype.close = function () {
  4240. this.closed = true;
  4241. return this;
  4242. };
  4243. /**
  4244. * Returns the Path2 total length (float).
  4245. */
  4246. Path2.prototype.length = function () {
  4247. var result = this._length;
  4248. if (!this.closed) {
  4249. var lastPoint = this._points[this._points.length - 1];
  4250. var firstPoint = this._points[0];
  4251. result += (firstPoint.subtract(lastPoint).length());
  4252. }
  4253. return result;
  4254. };
  4255. /**
  4256. * Returns the Path2 internal array of points.
  4257. */
  4258. Path2.prototype.getPoints = function () {
  4259. return this._points;
  4260. };
  4261. /**
  4262. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  4263. */
  4264. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  4265. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  4266. //Tools.Error("normalized length position should be between 0 and 1.");
  4267. return Vector2.Zero();
  4268. }
  4269. var lengthPosition = normalizedLengthPosition * this.length();
  4270. var previousOffset = 0;
  4271. for (var i = 0; i < this._points.length; i++) {
  4272. var j = (i + 1) % this._points.length;
  4273. var a = this._points[i];
  4274. var b = this._points[j];
  4275. var bToA = b.subtract(a);
  4276. var nextOffset = (bToA.length() + previousOffset);
  4277. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  4278. var dir = bToA.normalize();
  4279. var localOffset = lengthPosition - previousOffset;
  4280. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  4281. }
  4282. previousOffset = nextOffset;
  4283. }
  4284. //Tools.Error("internal error");
  4285. return Vector2.Zero();
  4286. };
  4287. /**
  4288. * Returns a new Path2 starting at the coordinates (x, y).
  4289. */
  4290. Path2.StartingAt = function (x, y) {
  4291. return new Path2(x, y);
  4292. };
  4293. return Path2;
  4294. }());
  4295. BABYLON.Path2 = Path2;
  4296. var Path3D = (function () {
  4297. /**
  4298. * new Path3D(path, normal, raw)
  4299. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  4300. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  4301. * path : an array of Vector3, the curve axis of the Path3D
  4302. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  4303. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  4304. */
  4305. function Path3D(path, firstNormal, raw) {
  4306. this.path = path;
  4307. this._curve = new Array();
  4308. this._distances = new Array();
  4309. this._tangents = new Array();
  4310. this._normals = new Array();
  4311. this._binormals = new Array();
  4312. for (var p = 0; p < path.length; p++) {
  4313. this._curve[p] = path[p].clone(); // hard copy
  4314. }
  4315. this._raw = raw || false;
  4316. this._compute(firstNormal);
  4317. }
  4318. /**
  4319. * Returns the Path3D array of successive Vector3 designing its curve.
  4320. */
  4321. Path3D.prototype.getCurve = function () {
  4322. return this._curve;
  4323. };
  4324. /**
  4325. * Returns an array populated with tangent vectors on each Path3D curve point.
  4326. */
  4327. Path3D.prototype.getTangents = function () {
  4328. return this._tangents;
  4329. };
  4330. /**
  4331. * Returns an array populated with normal vectors on each Path3D curve point.
  4332. */
  4333. Path3D.prototype.getNormals = function () {
  4334. return this._normals;
  4335. };
  4336. /**
  4337. * Returns an array populated with binormal vectors on each Path3D curve point.
  4338. */
  4339. Path3D.prototype.getBinormals = function () {
  4340. return this._binormals;
  4341. };
  4342. /**
  4343. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  4344. */
  4345. Path3D.prototype.getDistances = function () {
  4346. return this._distances;
  4347. };
  4348. /**
  4349. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  4350. * Returns the same object updated.
  4351. */
  4352. Path3D.prototype.update = function (path, firstNormal) {
  4353. for (var p = 0; p < path.length; p++) {
  4354. this._curve[p].x = path[p].x;
  4355. this._curve[p].y = path[p].y;
  4356. this._curve[p].z = path[p].z;
  4357. }
  4358. this._compute(firstNormal);
  4359. return this;
  4360. };
  4361. // private function compute() : computes tangents, normals and binormals
  4362. Path3D.prototype._compute = function (firstNormal) {
  4363. var l = this._curve.length;
  4364. // first and last tangents
  4365. this._tangents[0] = this._getFirstNonNullVector(0);
  4366. if (!this._raw) {
  4367. this._tangents[0].normalize();
  4368. }
  4369. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  4370. if (!this._raw) {
  4371. this._tangents[l - 1].normalize();
  4372. }
  4373. // normals and binormals at first point : arbitrary vector with _normalVector()
  4374. var tg0 = this._tangents[0];
  4375. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  4376. this._normals[0] = pp0;
  4377. if (!this._raw) {
  4378. this._normals[0].normalize();
  4379. }
  4380. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  4381. if (!this._raw) {
  4382. this._binormals[0].normalize();
  4383. }
  4384. this._distances[0] = 0.0;
  4385. // normals and binormals : next points
  4386. var prev; // previous vector (segment)
  4387. var cur; // current vector (segment)
  4388. var curTang; // current tangent
  4389. // previous normal
  4390. var prevBinor; // previous binormal
  4391. for (var i = 1; i < l; i++) {
  4392. // tangents
  4393. prev = this._getLastNonNullVector(i);
  4394. if (i < l - 1) {
  4395. cur = this._getFirstNonNullVector(i);
  4396. this._tangents[i] = prev.add(cur);
  4397. this._tangents[i].normalize();
  4398. }
  4399. this._distances[i] = this._distances[i - 1] + prev.length();
  4400. // normals and binormals
  4401. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  4402. curTang = this._tangents[i];
  4403. prevBinor = this._binormals[i - 1];
  4404. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  4405. if (!this._raw) {
  4406. this._normals[i].normalize();
  4407. }
  4408. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  4409. if (!this._raw) {
  4410. this._binormals[i].normalize();
  4411. }
  4412. }
  4413. };
  4414. // private function getFirstNonNullVector(index)
  4415. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  4416. Path3D.prototype._getFirstNonNullVector = function (index) {
  4417. var i = 1;
  4418. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  4419. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  4420. i++;
  4421. nNVector = this._curve[index + i].subtract(this._curve[index]);
  4422. }
  4423. return nNVector;
  4424. };
  4425. // private function getLastNonNullVector(index)
  4426. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  4427. Path3D.prototype._getLastNonNullVector = function (index) {
  4428. var i = 1;
  4429. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  4430. while (nLVector.length() === 0 && index > i + 1) {
  4431. i++;
  4432. nLVector = this._curve[index].subtract(this._curve[index - i]);
  4433. }
  4434. return nLVector;
  4435. };
  4436. // private function normalVector(v0, vt, va) :
  4437. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  4438. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  4439. Path3D.prototype._normalVector = function (v0, vt, va) {
  4440. var normal0;
  4441. var tgl = vt.length();
  4442. if (tgl === 0.0) {
  4443. tgl = 1.0;
  4444. }
  4445. if (va === undefined || va === null) {
  4446. var point;
  4447. if (!MathTools.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  4448. point = new Vector3(0.0, -1.0, 0.0);
  4449. }
  4450. else if (!MathTools.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  4451. point = new Vector3(1.0, 0.0, 0.0);
  4452. }
  4453. else if (!MathTools.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  4454. point = new Vector3(0.0, 0.0, 1.0);
  4455. }
  4456. normal0 = Vector3.Cross(vt, point);
  4457. }
  4458. else {
  4459. normal0 = Vector3.Cross(vt, va);
  4460. Vector3.CrossToRef(normal0, vt, normal0);
  4461. }
  4462. normal0.normalize();
  4463. return normal0;
  4464. };
  4465. return Path3D;
  4466. }());
  4467. BABYLON.Path3D = Path3D;
  4468. var Curve3 = (function () {
  4469. /**
  4470. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  4471. * A Curve3 is designed from a series of successive Vector3.
  4472. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  4473. */
  4474. function Curve3(points) {
  4475. this._length = 0.0;
  4476. this._points = points;
  4477. this._length = this._computeLength(points);
  4478. }
  4479. /**
  4480. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  4481. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  4482. * @param v1 (Vector3) the control point
  4483. * @param v2 (Vector3) the end point of the Quadratic Bezier
  4484. * @param nbPoints (integer) the wanted number of points in the curve
  4485. */
  4486. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  4487. nbPoints = nbPoints > 2 ? nbPoints : 3;
  4488. var bez = new Array();
  4489. var equation = function (t, val0, val1, val2) {
  4490. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  4491. return res;
  4492. };
  4493. for (var i = 0; i <= nbPoints; i++) {
  4494. 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)));
  4495. }
  4496. return new Curve3(bez);
  4497. };
  4498. /**
  4499. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  4500. * @param v0 (Vector3) the origin point of the Cubic Bezier
  4501. * @param v1 (Vector3) the first control point
  4502. * @param v2 (Vector3) the second control point
  4503. * @param v3 (Vector3) the end point of the Cubic Bezier
  4504. * @param nbPoints (integer) the wanted number of points in the curve
  4505. */
  4506. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  4507. nbPoints = nbPoints > 3 ? nbPoints : 4;
  4508. var bez = new Array();
  4509. var equation = function (t, val0, val1, val2, val3) {
  4510. 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;
  4511. return res;
  4512. };
  4513. for (var i = 0; i <= nbPoints; i++) {
  4514. 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)));
  4515. }
  4516. return new Curve3(bez);
  4517. };
  4518. /**
  4519. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  4520. * @param p1 (Vector3) the origin point of the Hermite Spline
  4521. * @param t1 (Vector3) the tangent vector at the origin point
  4522. * @param p2 (Vector3) the end point of the Hermite Spline
  4523. * @param t2 (Vector3) the tangent vector at the end point
  4524. * @param nbPoints (integer) the wanted number of points in the curve
  4525. */
  4526. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  4527. var hermite = new Array();
  4528. var step = 1.0 / nbPoints;
  4529. for (var i = 0; i <= nbPoints; i++) {
  4530. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  4531. }
  4532. return new Curve3(hermite);
  4533. };
  4534. /**
  4535. * Returns a Curve3 object along a CatmullRom Spline curve :
  4536. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  4537. * @param nbPoints (integer) the wanted number of points between each curve control points.
  4538. */
  4539. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  4540. var totalPoints = new Array();
  4541. totalPoints.push(points[0].clone());
  4542. Array.prototype.push.apply(totalPoints, points);
  4543. totalPoints.push(points[points.length - 1].clone());
  4544. var catmullRom = new Array();
  4545. var step = 1.0 / nbPoints;
  4546. for (var i = 0; i < totalPoints.length - 3; i++) {
  4547. var amount = 0.0;
  4548. for (var c = 0; c < nbPoints; c++) {
  4549. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4550. amount += step;
  4551. }
  4552. }
  4553. i--;
  4554. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4555. return new Curve3(catmullRom);
  4556. };
  4557. /**
  4558. * Returns the Curve3 stored array of successive Vector3
  4559. */
  4560. Curve3.prototype.getPoints = function () {
  4561. return this._points;
  4562. };
  4563. /**
  4564. * Returns the computed length (float) of the curve.
  4565. */
  4566. Curve3.prototype.length = function () {
  4567. return this._length;
  4568. };
  4569. /**
  4570. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  4571. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  4572. * curveA and curveB keep unchanged.
  4573. */
  4574. Curve3.prototype.continue = function (curve) {
  4575. var lastPoint = this._points[this._points.length - 1];
  4576. var continuedPoints = this._points.slice();
  4577. var curvePoints = curve.getPoints();
  4578. for (var i = 1; i < curvePoints.length; i++) {
  4579. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  4580. }
  4581. var continuedCurve = new Curve3(continuedPoints);
  4582. return continuedCurve;
  4583. };
  4584. Curve3.prototype._computeLength = function (path) {
  4585. var l = 0;
  4586. for (var i = 1; i < path.length; i++) {
  4587. l += (path[i].subtract(path[i - 1])).length();
  4588. }
  4589. return l;
  4590. };
  4591. return Curve3;
  4592. }());
  4593. BABYLON.Curve3 = Curve3;
  4594. // SphericalHarmonics
  4595. var SphericalHarmonics = (function () {
  4596. function SphericalHarmonics() {
  4597. this.L00 = Vector3.Zero();
  4598. this.L1_1 = Vector3.Zero();
  4599. this.L10 = Vector3.Zero();
  4600. this.L11 = Vector3.Zero();
  4601. this.L2_2 = Vector3.Zero();
  4602. this.L2_1 = Vector3.Zero();
  4603. this.L20 = Vector3.Zero();
  4604. this.L21 = Vector3.Zero();
  4605. this.L22 = Vector3.Zero();
  4606. }
  4607. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  4608. var colorVector = new Vector3(color.r, color.g, color.b);
  4609. var c = colorVector.scale(deltaSolidAngle);
  4610. this.L00 = this.L00.add(c.scale(0.282095));
  4611. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  4612. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  4613. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  4614. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  4615. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  4616. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  4617. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  4618. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  4619. };
  4620. SphericalHarmonics.prototype.scale = function (scale) {
  4621. this.L00 = this.L00.scale(scale);
  4622. this.L1_1 = this.L1_1.scale(scale);
  4623. this.L10 = this.L10.scale(scale);
  4624. this.L11 = this.L11.scale(scale);
  4625. this.L2_2 = this.L2_2.scale(scale);
  4626. this.L2_1 = this.L2_1.scale(scale);
  4627. this.L20 = this.L20.scale(scale);
  4628. this.L21 = this.L21.scale(scale);
  4629. this.L22 = this.L22.scale(scale);
  4630. };
  4631. return SphericalHarmonics;
  4632. }());
  4633. BABYLON.SphericalHarmonics = SphericalHarmonics;
  4634. // SphericalPolynomial
  4635. var SphericalPolynomial = (function () {
  4636. function SphericalPolynomial() {
  4637. this.x = Vector3.Zero();
  4638. this.y = Vector3.Zero();
  4639. this.z = Vector3.Zero();
  4640. this.xx = Vector3.Zero();
  4641. this.yy = Vector3.Zero();
  4642. this.zz = Vector3.Zero();
  4643. this.xy = Vector3.Zero();
  4644. this.yz = Vector3.Zero();
  4645. this.zx = Vector3.Zero();
  4646. }
  4647. SphericalPolynomial.prototype.addAmbient = function (color) {
  4648. var colorVector = new Vector3(color.r, color.g, color.b);
  4649. this.xx = this.xx.add(colorVector);
  4650. this.yy = this.yy.add(colorVector);
  4651. this.zz = this.zz.add(colorVector);
  4652. };
  4653. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  4654. var result = new SphericalPolynomial();
  4655. result.x = harmonics.L11.scale(1.02333);
  4656. result.y = harmonics.L1_1.scale(1.02333);
  4657. result.z = harmonics.L10.scale(1.02333);
  4658. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  4659. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  4660. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  4661. result.yz = harmonics.L2_1.scale(0.858086);
  4662. result.zx = harmonics.L21.scale(0.858086);
  4663. result.xy = harmonics.L2_2.scale(0.858086);
  4664. return result;
  4665. };
  4666. return SphericalPolynomial;
  4667. }());
  4668. BABYLON.SphericalPolynomial = SphericalPolynomial;
  4669. // Vertex formats
  4670. var PositionNormalVertex = (function () {
  4671. function PositionNormalVertex(position, normal) {
  4672. if (position === void 0) { position = Vector3.Zero(); }
  4673. if (normal === void 0) { normal = Vector3.Up(); }
  4674. this.position = position;
  4675. this.normal = normal;
  4676. }
  4677. PositionNormalVertex.prototype.clone = function () {
  4678. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  4679. };
  4680. return PositionNormalVertex;
  4681. }());
  4682. BABYLON.PositionNormalVertex = PositionNormalVertex;
  4683. var PositionNormalTextureVertex = (function () {
  4684. function PositionNormalTextureVertex(position, normal, uv) {
  4685. if (position === void 0) { position = Vector3.Zero(); }
  4686. if (normal === void 0) { normal = Vector3.Up(); }
  4687. if (uv === void 0) { uv = Vector2.Zero(); }
  4688. this.position = position;
  4689. this.normal = normal;
  4690. this.uv = uv;
  4691. }
  4692. PositionNormalTextureVertex.prototype.clone = function () {
  4693. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  4694. };
  4695. return PositionNormalTextureVertex;
  4696. }());
  4697. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  4698. // Temporary pre-allocated objects for engine internal use
  4699. // usage in any internal function :
  4700. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  4701. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  4702. var Tmp = (function () {
  4703. function Tmp() {
  4704. }
  4705. return Tmp;
  4706. }());
  4707. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  4708. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  4709. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  4710. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  4711. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  4712. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  4713. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  4714. Matrix.Zero(), Matrix.Zero(),
  4715. Matrix.Zero(), Matrix.Zero(),
  4716. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  4717. BABYLON.Tmp = Tmp;
  4718. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  4719. var MathTmp = (function () {
  4720. function MathTmp() {
  4721. }
  4722. return MathTmp;
  4723. }());
  4724. MathTmp.Vector3 = [Vector3.Zero()];
  4725. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  4726. MathTmp.Quaternion = [Quaternion.Zero()];
  4727. })(BABYLON || (BABYLON = {}));
  4728. //# sourceMappingURL=babylon.math.js.map
  4729. //# sourceMappingURL=babylon.mixins.js.map
  4730. var BABYLON;
  4731. (function (BABYLON) {
  4732. function generateSerializableMember(type, sourceName) {
  4733. return function (target, propertyKey) {
  4734. if (!target.__serializableMembers) {
  4735. target.__serializableMembers = {};
  4736. }
  4737. if (!target.__serializableMembers[propertyKey]) {
  4738. target.__serializableMembers[propertyKey] = { type: type, sourceName: sourceName };
  4739. }
  4740. };
  4741. }
  4742. function generateExpandMember(setCallback) {
  4743. return function (target, propertyKey) {
  4744. if (setCallback) {
  4745. var key = "_" + propertyKey;
  4746. Object.defineProperty(target, propertyKey, {
  4747. get: function () {
  4748. return this[key];
  4749. },
  4750. set: function (value) {
  4751. if (this[key] === value) {
  4752. return;
  4753. }
  4754. this[key] = value;
  4755. target[setCallback].apply(this);
  4756. },
  4757. enumerable: true,
  4758. configurable: true
  4759. });
  4760. }
  4761. };
  4762. }
  4763. function expandToProperty(callback) {
  4764. return generateExpandMember(callback);
  4765. }
  4766. BABYLON.expandToProperty = expandToProperty;
  4767. function serialize(sourceName) {
  4768. return generateSerializableMember(0, sourceName); // value member
  4769. }
  4770. BABYLON.serialize = serialize;
  4771. function serializeAsTexture(sourceName) {
  4772. return generateSerializableMember(1, sourceName); // texture member
  4773. }
  4774. BABYLON.serializeAsTexture = serializeAsTexture;
  4775. function serializeAsColor3(sourceName) {
  4776. return generateSerializableMember(2, sourceName); // color3 member
  4777. }
  4778. BABYLON.serializeAsColor3 = serializeAsColor3;
  4779. function serializeAsFresnelParameters(sourceName) {
  4780. return generateSerializableMember(3, sourceName); // fresnel parameters member
  4781. }
  4782. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  4783. function serializeAsVector2(sourceName) {
  4784. return generateSerializableMember(4, sourceName); // vector2 member
  4785. }
  4786. BABYLON.serializeAsVector2 = serializeAsVector2;
  4787. function serializeAsVector3(sourceName) {
  4788. return generateSerializableMember(5, sourceName); // vector3 member
  4789. }
  4790. BABYLON.serializeAsVector3 = serializeAsVector3;
  4791. function serializeAsMeshReference(sourceName) {
  4792. return generateSerializableMember(6, sourceName); // mesh reference member
  4793. }
  4794. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  4795. function serializeAsColorCurves(sourceName) {
  4796. return generateSerializableMember(7, sourceName); // color curves
  4797. }
  4798. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  4799. var SerializationHelper = (function () {
  4800. function SerializationHelper() {
  4801. }
  4802. SerializationHelper.Serialize = function (entity, serializationObject) {
  4803. if (!serializationObject) {
  4804. serializationObject = {};
  4805. }
  4806. // Tags
  4807. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  4808. // Properties
  4809. for (var property in entity.__serializableMembers) {
  4810. var propertyDescriptor = entity.__serializableMembers[property];
  4811. var targetPropertyName = propertyDescriptor.sourceName || property;
  4812. var propertyType = propertyDescriptor.type;
  4813. var sourceProperty = entity[property];
  4814. if (sourceProperty !== undefined && sourceProperty !== null) {
  4815. switch (propertyType) {
  4816. case 0:
  4817. serializationObject[targetPropertyName] = sourceProperty;
  4818. break;
  4819. case 1:
  4820. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4821. break;
  4822. case 2:
  4823. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4824. break;
  4825. case 3:
  4826. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4827. break;
  4828. case 4:
  4829. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4830. break;
  4831. case 5:
  4832. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4833. break;
  4834. case 6:
  4835. serializationObject[targetPropertyName] = sourceProperty.id;
  4836. break;
  4837. case 7:
  4838. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4839. break;
  4840. }
  4841. }
  4842. }
  4843. return serializationObject;
  4844. };
  4845. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  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[propertyDescriptor.sourceName || property];
  4853. var propertyType = propertyDescriptor.type;
  4854. if (sourceProperty !== undefined && sourceProperty !== null) {
  4855. switch (propertyType) {
  4856. case 0:
  4857. destination[property] = sourceProperty;
  4858. break;
  4859. case 1:
  4860. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  4861. break;
  4862. case 2:
  4863. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  4864. break;
  4865. case 3:
  4866. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  4867. break;
  4868. case 4:
  4869. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  4870. break;
  4871. case 5:
  4872. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  4873. break;
  4874. case 6:
  4875. destination[property] = scene.getLastMeshByID(sourceProperty);
  4876. break;
  4877. case 7:
  4878. destination[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  4879. break;
  4880. }
  4881. }
  4882. }
  4883. return destination;
  4884. };
  4885. SerializationHelper.Clone = function (creationFunction, source) {
  4886. var destination = creationFunction();
  4887. // Tags
  4888. BABYLON.Tags.AddTagsTo(destination, source.tags);
  4889. // Properties
  4890. for (var property in destination.__serializableMembers) {
  4891. var propertyDescriptor = destination.__serializableMembers[property];
  4892. var sourceProperty = source[property];
  4893. var propertyType = propertyDescriptor.type;
  4894. if (sourceProperty !== undefined && sourceProperty !== null) {
  4895. switch (propertyType) {
  4896. case 0: // Value
  4897. case 6:
  4898. destination[property] = sourceProperty;
  4899. break;
  4900. case 1: // Texture
  4901. case 2: // Color3
  4902. case 3: // FresnelParameters
  4903. case 4: // Vector2
  4904. case 5: // Vector3
  4905. case 7:
  4906. destination[property] = sourceProperty.clone();
  4907. break;
  4908. }
  4909. }
  4910. }
  4911. return destination;
  4912. };
  4913. return SerializationHelper;
  4914. }());
  4915. BABYLON.SerializationHelper = SerializationHelper;
  4916. })(BABYLON || (BABYLON = {}));
  4917. //# sourceMappingURL=babylon.decorators.js.map
  4918. var BABYLON;
  4919. (function (BABYLON) {
  4920. /**
  4921. * A class serves as a medium between the observable and its observers
  4922. */
  4923. var EventState = (function () {
  4924. /**
  4925. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  4926. */
  4927. function EventState(mask, skipNextObservers) {
  4928. if (skipNextObservers === void 0) { skipNextObservers = false; }
  4929. this.initalize(mask, skipNextObservers);
  4930. }
  4931. EventState.prototype.initalize = function (mask, skipNextObservers) {
  4932. if (skipNextObservers === void 0) { skipNextObservers = false; }
  4933. this.mask = mask;
  4934. this.skipNextObservers = skipNextObservers;
  4935. return this;
  4936. };
  4937. return EventState;
  4938. }());
  4939. BABYLON.EventState = EventState;
  4940. /**
  4941. * Represent an Observer registered to a given Observable object.
  4942. */
  4943. var Observer = (function () {
  4944. function Observer(callback, mask) {
  4945. this.callback = callback;
  4946. this.mask = mask;
  4947. }
  4948. return Observer;
  4949. }());
  4950. BABYLON.Observer = Observer;
  4951. /**
  4952. * The Observable class is a simple implementation of the Observable pattern.
  4953. * 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.
  4954. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  4955. * 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).
  4956. * 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.
  4957. */
  4958. var Observable = (function () {
  4959. function Observable() {
  4960. this._observers = new Array();
  4961. this._eventState = new EventState(0);
  4962. }
  4963. /**
  4964. * Create a new Observer with the specified callback
  4965. * @param callback the callback that will be executed for that Observer
  4966. * @param mask the mask used to filter observers
  4967. * @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.
  4968. */
  4969. Observable.prototype.add = function (callback, mask, insertFirst) {
  4970. if (mask === void 0) { mask = -1; }
  4971. if (insertFirst === void 0) { insertFirst = false; }
  4972. if (!callback) {
  4973. return null;
  4974. }
  4975. var observer = new Observer(callback, mask);
  4976. if (insertFirst) {
  4977. this._observers.unshift(observer);
  4978. }
  4979. else {
  4980. this._observers.push(observer);
  4981. }
  4982. return observer;
  4983. };
  4984. /**
  4985. * Remove an Observer from the Observable object
  4986. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  4987. */
  4988. Observable.prototype.remove = function (observer) {
  4989. var index = this._observers.indexOf(observer);
  4990. if (index !== -1) {
  4991. this._observers.splice(index, 1);
  4992. return true;
  4993. }
  4994. return false;
  4995. };
  4996. /**
  4997. * Remove a callback from the Observable object
  4998. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  4999. */
  5000. Observable.prototype.removeCallback = function (callback) {
  5001. for (var index = 0; index < this._observers.length; index++) {
  5002. if (this._observers[index].callback === callback) {
  5003. this._observers.splice(index, 1);
  5004. return true;
  5005. }
  5006. }
  5007. return false;
  5008. };
  5009. /**
  5010. * Notify all Observers by calling their respective callback with the given data
  5011. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  5012. * @param eventData
  5013. * @param mask
  5014. */
  5015. Observable.prototype.notifyObservers = function (eventData, mask) {
  5016. if (mask === void 0) { mask = -1; }
  5017. var state = this._eventState;
  5018. state.mask = mask;
  5019. state.skipNextObservers = false;
  5020. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5021. var obs = _a[_i];
  5022. if (obs.mask & mask) {
  5023. obs.callback(eventData, state);
  5024. }
  5025. if (state.skipNextObservers) {
  5026. return false;
  5027. }
  5028. }
  5029. return true;
  5030. };
  5031. /**
  5032. * return true is the Observable has at least one Observer registered
  5033. */
  5034. Observable.prototype.hasObservers = function () {
  5035. return this._observers.length > 0;
  5036. };
  5037. /**
  5038. * Clear the list of observers
  5039. */
  5040. Observable.prototype.clear = function () {
  5041. this._observers = new Array();
  5042. };
  5043. /**
  5044. * Clone the current observable
  5045. */
  5046. Observable.prototype.clone = function () {
  5047. var result = new Observable();
  5048. result._observers = this._observers.slice(0);
  5049. return result;
  5050. };
  5051. /**
  5052. * Does this observable handles observer registered with a given mask
  5053. * @param {number} trigger - the mask to be tested
  5054. * @return {boolean} whether or not one observer registered with the given mask is handeled
  5055. **/
  5056. Observable.prototype.hasSpecificMask = function (mask) {
  5057. if (mask === void 0) { mask = -1; }
  5058. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5059. var obs = _a[_i];
  5060. if (obs.mask & mask && obs.mask === mask) {
  5061. return true;
  5062. }
  5063. }
  5064. return false;
  5065. };
  5066. return Observable;
  5067. }());
  5068. BABYLON.Observable = Observable;
  5069. })(BABYLON || (BABYLON = {}));
  5070. //# sourceMappingURL=babylon.observable.js.map
  5071. var BABYLON;
  5072. (function (BABYLON) {
  5073. var SmartArray = (function () {
  5074. function SmartArray(capacity) {
  5075. this.length = 0;
  5076. this._duplicateId = 0;
  5077. this.data = new Array(capacity);
  5078. this._id = SmartArray._GlobalId++;
  5079. }
  5080. SmartArray.prototype.push = function (value) {
  5081. this.data[this.length++] = value;
  5082. if (this.length > this.data.length) {
  5083. this.data.length *= 2;
  5084. }
  5085. if (!value.__smartArrayFlags) {
  5086. value.__smartArrayFlags = {};
  5087. }
  5088. value.__smartArrayFlags[this._id] = this._duplicateId;
  5089. };
  5090. SmartArray.prototype.forEach = function (func) {
  5091. for (var index = 0; index < this.length; index++) {
  5092. func(this.data[index]);
  5093. }
  5094. };
  5095. SmartArray.prototype.pushNoDuplicate = function (value) {
  5096. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  5097. return false;
  5098. }
  5099. this.push(value);
  5100. return true;
  5101. };
  5102. SmartArray.prototype.sort = function (compareFn) {
  5103. this.data.sort(compareFn);
  5104. };
  5105. SmartArray.prototype.reset = function () {
  5106. this.length = 0;
  5107. this._duplicateId++;
  5108. };
  5109. SmartArray.prototype.dispose = function () {
  5110. this.reset();
  5111. this.data.length = 0;
  5112. };
  5113. SmartArray.prototype.concat = function (array) {
  5114. if (array.length === 0) {
  5115. return;
  5116. }
  5117. if (this.length + array.length > this.data.length) {
  5118. this.data.length = (this.length + array.length) * 2;
  5119. }
  5120. for (var index = 0; index < array.length; index++) {
  5121. this.data[this.length++] = (array.data || array)[index];
  5122. }
  5123. };
  5124. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  5125. if (array.length === 0) {
  5126. return;
  5127. }
  5128. if (this.length + array.length > this.data.length) {
  5129. this.data.length = (this.length + array.length) * 2;
  5130. }
  5131. for (var index = 0; index < array.length; index++) {
  5132. var item = (array.data || array)[index];
  5133. this.pushNoDuplicate(item);
  5134. }
  5135. };
  5136. SmartArray.prototype.indexOf = function (value) {
  5137. var position = this.data.indexOf(value);
  5138. if (position >= this.length) {
  5139. return -1;
  5140. }
  5141. return position;
  5142. };
  5143. SmartArray.prototype.contains = function (value) {
  5144. return this.data.indexOf(value) !== -1;
  5145. };
  5146. return SmartArray;
  5147. }());
  5148. // Statics
  5149. SmartArray._GlobalId = 0;
  5150. BABYLON.SmartArray = SmartArray;
  5151. })(BABYLON || (BABYLON = {}));
  5152. //# sourceMappingURL=babylon.smartArray.js.map
  5153. var BABYLON;
  5154. (function (BABYLON) {
  5155. // Screenshots
  5156. var screenshotCanvas;
  5157. var cloneValue = function (source, destinationObject) {
  5158. if (!source)
  5159. return null;
  5160. if (source instanceof BABYLON.Mesh) {
  5161. return null;
  5162. }
  5163. if (source instanceof BABYLON.SubMesh) {
  5164. return source.clone(destinationObject);
  5165. }
  5166. else if (source.clone) {
  5167. return source.clone();
  5168. }
  5169. return null;
  5170. };
  5171. var Tools = (function () {
  5172. function Tools() {
  5173. }
  5174. ;
  5175. Tools.Instantiate = function (className) {
  5176. var arr = className.split(".");
  5177. var fn = (window || this);
  5178. for (var i = 0, len = arr.length; i < len; i++) {
  5179. fn = fn[arr[i]];
  5180. }
  5181. if (typeof fn !== "function") {
  5182. return null;
  5183. }
  5184. return fn;
  5185. };
  5186. Tools.SetImmediate = function (action) {
  5187. if (window.setImmediate) {
  5188. window.setImmediate(action);
  5189. }
  5190. else {
  5191. setTimeout(action, 1);
  5192. }
  5193. };
  5194. Tools.IsExponentOfTwo = function (value) {
  5195. var count = 1;
  5196. do {
  5197. count *= 2;
  5198. } while (count < value);
  5199. return count === value;
  5200. };
  5201. Tools.GetExponentOfTwo = function (value, max) {
  5202. var count = 1;
  5203. do {
  5204. count *= 2;
  5205. } while (count < value);
  5206. if (count > max)
  5207. count = max;
  5208. return count;
  5209. };
  5210. Tools.GetFilename = function (path) {
  5211. var index = path.lastIndexOf("/");
  5212. if (index < 0)
  5213. return path;
  5214. return path.substring(index + 1);
  5215. };
  5216. Tools.GetDOMTextContent = function (element) {
  5217. var result = "";
  5218. var child = element.firstChild;
  5219. while (child) {
  5220. if (child.nodeType === 3) {
  5221. result += child.textContent;
  5222. }
  5223. child = child.nextSibling;
  5224. }
  5225. return result;
  5226. };
  5227. Tools.ToDegrees = function (angle) {
  5228. return angle * 180 / Math.PI;
  5229. };
  5230. Tools.ToRadians = function (angle) {
  5231. return angle * Math.PI / 180;
  5232. };
  5233. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  5234. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  5235. var output = "";
  5236. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  5237. var i = 0;
  5238. var bytes = new Uint8Array(buffer);
  5239. while (i < bytes.length) {
  5240. chr1 = bytes[i++];
  5241. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  5242. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  5243. enc1 = chr1 >> 2;
  5244. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  5245. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  5246. enc4 = chr3 & 63;
  5247. if (isNaN(chr2)) {
  5248. enc3 = enc4 = 64;
  5249. }
  5250. else if (isNaN(chr3)) {
  5251. enc4 = 64;
  5252. }
  5253. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  5254. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  5255. }
  5256. return "data:image/png;base64," + output;
  5257. };
  5258. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  5259. if (bias === void 0) { bias = null; }
  5260. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5261. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5262. for (var index = indexStart; index < indexStart + indexCount; index++) {
  5263. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  5264. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5265. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5266. }
  5267. if (bias) {
  5268. minimum.x -= minimum.x * bias.x + bias.y;
  5269. minimum.y -= minimum.y * bias.x + bias.y;
  5270. minimum.z -= minimum.z * bias.x + bias.y;
  5271. maximum.x += maximum.x * bias.x + bias.y;
  5272. maximum.y += maximum.y * bias.x + bias.y;
  5273. maximum.z += maximum.z * bias.x + bias.y;
  5274. }
  5275. return {
  5276. minimum: minimum,
  5277. maximum: maximum
  5278. };
  5279. };
  5280. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  5281. if (bias === void 0) { bias = null; }
  5282. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5283. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5284. if (!stride) {
  5285. stride = 3;
  5286. }
  5287. for (var index = start; index < start + count; index++) {
  5288. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  5289. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5290. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5291. }
  5292. if (bias) {
  5293. minimum.x -= minimum.x * bias.x + bias.y;
  5294. minimum.y -= minimum.y * bias.x + bias.y;
  5295. minimum.z -= minimum.z * bias.x + bias.y;
  5296. maximum.x += maximum.x * bias.x + bias.y;
  5297. maximum.y += maximum.y * bias.x + bias.y;
  5298. maximum.z += maximum.z * bias.x + bias.y;
  5299. }
  5300. return {
  5301. minimum: minimum,
  5302. maximum: maximum
  5303. };
  5304. };
  5305. Tools.Vector2ArrayFeeder = function (array) {
  5306. return function (index) {
  5307. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  5308. var length = isFloatArray ? array.length / 2 : array.length;
  5309. if (index >= length) {
  5310. return null;
  5311. }
  5312. if (isFloatArray) {
  5313. var fa = array;
  5314. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  5315. }
  5316. var a = array;
  5317. return a[index];
  5318. };
  5319. };
  5320. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  5321. if (bias === void 0) { bias = null; }
  5322. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  5323. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  5324. var i = 0;
  5325. var cur = feeder(i++);
  5326. while (cur) {
  5327. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  5328. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  5329. cur = feeder(i++);
  5330. }
  5331. if (bias) {
  5332. minimum.x -= minimum.x * bias.x + bias.y;
  5333. minimum.y -= minimum.y * bias.x + bias.y;
  5334. maximum.x += maximum.x * bias.x + bias.y;
  5335. maximum.y += maximum.y * bias.x + bias.y;
  5336. }
  5337. return {
  5338. minimum: minimum,
  5339. maximum: maximum
  5340. };
  5341. };
  5342. Tools.MakeArray = function (obj, allowsNullUndefined) {
  5343. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  5344. return undefined;
  5345. return Array.isArray(obj) ? obj : [obj];
  5346. };
  5347. // Misc.
  5348. Tools.GetPointerPrefix = function () {
  5349. var eventPrefix = "pointer";
  5350. // Check if pointer events are supported
  5351. if (!window.PointerEvent && !navigator.pointerEnabled) {
  5352. eventPrefix = "mouse";
  5353. }
  5354. return eventPrefix;
  5355. };
  5356. /**
  5357. * @param func - the function to be called
  5358. * @param requester - the object that will request the next frame. Falls back to window.
  5359. */
  5360. Tools.QueueNewFrame = function (func, requester) {
  5361. if (requester === void 0) { requester = window; }
  5362. //if WebVR is enabled AND presenting, requestAnimationFrame is triggered when enabled.
  5363. /*if(requester.isPresenting) {
  5364. return;
  5365. } else*/ if (requester.requestAnimationFrame)
  5366. requester.requestAnimationFrame(func);
  5367. else if (requester.msRequestAnimationFrame)
  5368. requester.msRequestAnimationFrame(func);
  5369. else if (requester.webkitRequestAnimationFrame)
  5370. requester.webkitRequestAnimationFrame(func);
  5371. else if (requester.mozRequestAnimationFrame)
  5372. requester.mozRequestAnimationFrame(func);
  5373. else if (requester.oRequestAnimationFrame)
  5374. requester.oRequestAnimationFrame(func);
  5375. else {
  5376. window.setTimeout(func, 16);
  5377. }
  5378. };
  5379. Tools.RequestFullscreen = function (element) {
  5380. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  5381. if (!requestFunction)
  5382. return;
  5383. requestFunction.call(element);
  5384. };
  5385. Tools.ExitFullscreen = function () {
  5386. if (document.exitFullscreen) {
  5387. document.exitFullscreen();
  5388. }
  5389. else if (document.mozCancelFullScreen) {
  5390. document.mozCancelFullScreen();
  5391. }
  5392. else if (document.webkitCancelFullScreen) {
  5393. document.webkitCancelFullScreen();
  5394. }
  5395. else if (document.msCancelFullScreen) {
  5396. document.msCancelFullScreen();
  5397. }
  5398. };
  5399. Tools.SetCorsBehavior = function (url, img) {
  5400. if (Tools.CorsBehavior) {
  5401. switch (typeof (Tools.CorsBehavior)) {
  5402. case "function":
  5403. var result = Tools.CorsBehavior(url);
  5404. if (result) {
  5405. img.crossOrigin = result;
  5406. }
  5407. break;
  5408. case "string":
  5409. default:
  5410. img.crossOrigin = Tools.CorsBehavior;
  5411. break;
  5412. }
  5413. }
  5414. };
  5415. // External files
  5416. Tools.CleanUrl = function (url) {
  5417. url = url.replace(/#/mg, "%23");
  5418. return url;
  5419. };
  5420. Tools.LoadImage = function (url, onload, onerror, database) {
  5421. if (url instanceof ArrayBuffer) {
  5422. url = Tools.EncodeArrayBufferTobase64(url);
  5423. }
  5424. url = Tools.CleanUrl(url);
  5425. var img = new Image();
  5426. if (url.substr(0, 5) !== "data:") {
  5427. Tools.SetCorsBehavior(url, img);
  5428. }
  5429. img.onload = function () {
  5430. onload(img);
  5431. };
  5432. img.onerror = function (err) {
  5433. Tools.Error("Error while trying to load image: " + url);
  5434. if (Tools.UseFallbackTexture) {
  5435. img.src = Tools.fallbackTexture;
  5436. onload(img);
  5437. }
  5438. else {
  5439. onerror();
  5440. }
  5441. };
  5442. var noIndexedDB = function () {
  5443. img.src = url;
  5444. };
  5445. var loadFromIndexedDB = function () {
  5446. database.loadImageFromDB(url, img);
  5447. };
  5448. //ANY database to do!
  5449. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  5450. database.openAsync(loadFromIndexedDB, noIndexedDB);
  5451. }
  5452. else {
  5453. if (url.indexOf("file:") === -1) {
  5454. noIndexedDB();
  5455. }
  5456. else {
  5457. var textureName = url.substring(5).toLowerCase();
  5458. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  5459. try {
  5460. var blobURL;
  5461. try {
  5462. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  5463. }
  5464. catch (ex) {
  5465. // Chrome doesn't support oneTimeOnly parameter
  5466. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  5467. }
  5468. img.src = blobURL;
  5469. }
  5470. catch (e) {
  5471. img.src = null;
  5472. }
  5473. }
  5474. else {
  5475. Tools.Error("Image: " + textureName + " not found. Did you forget to provide it?");
  5476. img.src = Tools.fallbackTexture;
  5477. }
  5478. }
  5479. }
  5480. return img;
  5481. };
  5482. //ANY
  5483. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  5484. url = Tools.CleanUrl(url);
  5485. var noIndexedDB = function () {
  5486. var request = new XMLHttpRequest();
  5487. var loadUrl = Tools.BaseUrl + url;
  5488. request.open('GET', loadUrl, true);
  5489. if (useArrayBuffer) {
  5490. request.responseType = "arraybuffer";
  5491. }
  5492. request.onprogress = progressCallBack;
  5493. request.onreadystatechange = function () {
  5494. // In case of undefined state in some browsers.
  5495. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  5496. request.onreadystatechange = null; //some browsers have issues where onreadystatechange can be called multiple times with the same value
  5497. if (request.status >= 200 && request.status < 300 || (navigator.isCocoonJS && (request.status === 0))) {
  5498. callback(!useArrayBuffer ? request.responseText : request.response);
  5499. }
  5500. else {
  5501. if (onError) {
  5502. onError(request);
  5503. }
  5504. else {
  5505. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  5506. }
  5507. }
  5508. }
  5509. };
  5510. request.send(null);
  5511. };
  5512. var loadFromIndexedDB = function () {
  5513. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  5514. };
  5515. if (url.indexOf("file:") !== -1) {
  5516. var fileName = url.substring(5).toLowerCase();
  5517. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  5518. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  5519. }
  5520. else {
  5521. Tools.Error("File: " + fileName + " not found. Did you forget to provide it?");
  5522. }
  5523. }
  5524. else {
  5525. // Caching all files
  5526. if (database && database.enableSceneOffline) {
  5527. database.openAsync(loadFromIndexedDB, noIndexedDB);
  5528. }
  5529. else {
  5530. noIndexedDB();
  5531. }
  5532. }
  5533. };
  5534. /**
  5535. * Load a script (identified by an url). When the url returns, the
  5536. * content of this file is added into a new script element, attached to the DOM (body element)
  5537. */
  5538. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  5539. var head = document.getElementsByTagName('head')[0];
  5540. var script = document.createElement('script');
  5541. script.type = 'text/javascript';
  5542. script.src = scriptUrl;
  5543. var self = this;
  5544. script.onload = function () {
  5545. if (onSuccess) {
  5546. onSuccess();
  5547. }
  5548. };
  5549. script.onerror = function () {
  5550. if (onError) {
  5551. onError();
  5552. }
  5553. };
  5554. head.appendChild(script);
  5555. };
  5556. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  5557. var reader = new FileReader();
  5558. reader.onload = function (e) {
  5559. //target doesn't have result from ts 1.3
  5560. callback(e.target['result']);
  5561. };
  5562. reader.onprogress = progressCallback;
  5563. reader.readAsDataURL(fileToLoad);
  5564. };
  5565. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  5566. var reader = new FileReader();
  5567. reader.onerror = function (e) {
  5568. Tools.Log("Error while reading file: " + fileToLoad.name);
  5569. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  5570. };
  5571. reader.onload = function (e) {
  5572. //target doesn't have result from ts 1.3
  5573. callback(e.target['result']);
  5574. };
  5575. reader.onprogress = progressCallBack;
  5576. if (!useArrayBuffer) {
  5577. // Asynchronous read
  5578. reader.readAsText(fileToLoad);
  5579. }
  5580. else {
  5581. reader.readAsArrayBuffer(fileToLoad);
  5582. }
  5583. };
  5584. //returns a downloadable url to a file content.
  5585. Tools.FileAsURL = function (content) {
  5586. var fileBlob = new Blob([content]);
  5587. var url = window.URL || window.webkitURL;
  5588. var link = url.createObjectURL(fileBlob);
  5589. return link;
  5590. };
  5591. // Misc.
  5592. Tools.Format = function (value, decimals) {
  5593. if (decimals === void 0) { decimals = 2; }
  5594. return value.toFixed(decimals);
  5595. };
  5596. Tools.CheckExtends = function (v, min, max) {
  5597. if (v.x < min.x)
  5598. min.x = v.x;
  5599. if (v.y < min.y)
  5600. min.y = v.y;
  5601. if (v.z < min.z)
  5602. min.z = v.z;
  5603. if (v.x > max.x)
  5604. max.x = v.x;
  5605. if (v.y > max.y)
  5606. max.y = v.y;
  5607. if (v.z > max.z)
  5608. max.z = v.z;
  5609. };
  5610. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  5611. for (var prop in source) {
  5612. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  5613. continue;
  5614. }
  5615. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  5616. continue;
  5617. }
  5618. var sourceValue = source[prop];
  5619. var typeOfSourceValue = typeof sourceValue;
  5620. if (typeOfSourceValue === "function") {
  5621. continue;
  5622. }
  5623. if (typeOfSourceValue === "object") {
  5624. if (sourceValue instanceof Array) {
  5625. destination[prop] = [];
  5626. if (sourceValue.length > 0) {
  5627. if (typeof sourceValue[0] == "object") {
  5628. for (var index = 0; index < sourceValue.length; index++) {
  5629. var clonedValue = cloneValue(sourceValue[index], destination);
  5630. if (destination[prop].indexOf(clonedValue) === -1) {
  5631. destination[prop].push(clonedValue);
  5632. }
  5633. }
  5634. }
  5635. else {
  5636. destination[prop] = sourceValue.slice(0);
  5637. }
  5638. }
  5639. }
  5640. else {
  5641. destination[prop] = cloneValue(sourceValue, destination);
  5642. }
  5643. }
  5644. else {
  5645. destination[prop] = sourceValue;
  5646. }
  5647. }
  5648. };
  5649. Tools.IsEmpty = function (obj) {
  5650. for (var i in obj) {
  5651. return false;
  5652. }
  5653. return true;
  5654. };
  5655. Tools.RegisterTopRootEvents = function (events) {
  5656. for (var index = 0; index < events.length; index++) {
  5657. var event = events[index];
  5658. window.addEventListener(event.name, event.handler, false);
  5659. try {
  5660. if (window.parent) {
  5661. window.parent.addEventListener(event.name, event.handler, false);
  5662. }
  5663. }
  5664. catch (e) {
  5665. // Silently fails...
  5666. }
  5667. }
  5668. };
  5669. Tools.UnregisterTopRootEvents = function (events) {
  5670. for (var index = 0; index < events.length; index++) {
  5671. var event = events[index];
  5672. window.removeEventListener(event.name, event.handler);
  5673. try {
  5674. if (window.parent) {
  5675. window.parent.removeEventListener(event.name, event.handler);
  5676. }
  5677. }
  5678. catch (e) {
  5679. // Silently fails...
  5680. }
  5681. }
  5682. };
  5683. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType) {
  5684. if (mimeType === void 0) { mimeType = "image/png"; }
  5685. // Read the contents of the framebuffer
  5686. var numberOfChannelsByLine = width * 4;
  5687. var halfHeight = height / 2;
  5688. //Reading datas from WebGL
  5689. var data = engine.readPixels(0, 0, width, height);
  5690. //To flip image on Y axis.
  5691. for (var i = 0; i < halfHeight; i++) {
  5692. for (var j = 0; j < numberOfChannelsByLine; j++) {
  5693. var currentCell = j + i * numberOfChannelsByLine;
  5694. var targetLine = height - i - 1;
  5695. var targetCell = j + targetLine * numberOfChannelsByLine;
  5696. var temp = data[currentCell];
  5697. data[currentCell] = data[targetCell];
  5698. data[targetCell] = temp;
  5699. }
  5700. }
  5701. // Create a 2D canvas to store the result
  5702. if (!screenshotCanvas) {
  5703. screenshotCanvas = document.createElement('canvas');
  5704. }
  5705. screenshotCanvas.width = width;
  5706. screenshotCanvas.height = height;
  5707. var context = screenshotCanvas.getContext('2d');
  5708. // Copy the pixels to a 2D canvas
  5709. var imageData = context.createImageData(width, height);
  5710. var castData = (imageData.data);
  5711. castData.set(data);
  5712. context.putImageData(imageData, 0, 0);
  5713. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  5714. };
  5715. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType) {
  5716. if (mimeType === void 0) { mimeType = "image/png"; }
  5717. var base64Image = screenshotCanvas.toDataURL(mimeType);
  5718. if (successCallback) {
  5719. successCallback(base64Image);
  5720. }
  5721. else {
  5722. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  5723. if (("download" in document.createElement("a"))) {
  5724. var a = window.document.createElement("a");
  5725. a.href = base64Image;
  5726. var date = new Date();
  5727. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  5728. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  5729. window.document.body.appendChild(a);
  5730. a.addEventListener("click", function () {
  5731. a.parentElement.removeChild(a);
  5732. });
  5733. a.click();
  5734. //Or opening a new tab with the image if it is not possible to automatically start download.
  5735. }
  5736. else {
  5737. var newWindow = window.open("");
  5738. var img = newWindow.document.createElement("img");
  5739. img.src = base64Image;
  5740. newWindow.document.body.appendChild(img);
  5741. }
  5742. }
  5743. };
  5744. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  5745. if (mimeType === void 0) { mimeType = "image/png"; }
  5746. var width;
  5747. var height;
  5748. // If a precision value is specified
  5749. if (size.precision) {
  5750. width = Math.round(engine.getRenderWidth() * size.precision);
  5751. height = Math.round(width / engine.getAspectRatio(camera));
  5752. }
  5753. else if (size.width && size.height) {
  5754. width = size.width;
  5755. height = size.height;
  5756. }
  5757. else if (size.width && !size.height) {
  5758. width = size.width;
  5759. height = Math.round(width / engine.getAspectRatio(camera));
  5760. }
  5761. else if (size.height && !size.width) {
  5762. height = size.height;
  5763. width = Math.round(height * engine.getAspectRatio(camera));
  5764. }
  5765. else if (!isNaN(size)) {
  5766. height = size;
  5767. width = size;
  5768. }
  5769. else {
  5770. Tools.Error("Invalid 'size' parameter !");
  5771. return;
  5772. }
  5773. if (!screenshotCanvas) {
  5774. screenshotCanvas = document.createElement('canvas');
  5775. }
  5776. screenshotCanvas.width = width;
  5777. screenshotCanvas.height = height;
  5778. var renderContext = screenshotCanvas.getContext("2d");
  5779. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  5780. var newWidth = width;
  5781. var newHeight = newWidth / ratio;
  5782. if (newHeight > height) {
  5783. newHeight = height;
  5784. newWidth = newHeight * ratio;
  5785. }
  5786. var offsetX = Math.max(0, width - newWidth) / 2;
  5787. var offsetY = Math.max(0, height - newHeight) / 2;
  5788. renderContext.drawImage(engine.getRenderingCanvas(), offsetX, offsetY, newWidth, newHeight);
  5789. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  5790. };
  5791. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples) {
  5792. if (mimeType === void 0) { mimeType = "image/png"; }
  5793. if (samples === void 0) { samples = 1; }
  5794. var width;
  5795. var height;
  5796. //If a precision value is specified
  5797. if (size.precision) {
  5798. width = Math.round(engine.getRenderWidth() * size.precision);
  5799. height = Math.round(width / engine.getAspectRatio(camera));
  5800. size = { width: width, height: height };
  5801. }
  5802. else if (size.width && size.height) {
  5803. width = size.width;
  5804. height = size.height;
  5805. }
  5806. else if (size.width && !size.height) {
  5807. width = size.width;
  5808. height = Math.round(width / engine.getAspectRatio(camera));
  5809. size = { width: width, height: height };
  5810. }
  5811. else if (size.height && !size.width) {
  5812. height = size.height;
  5813. width = Math.round(height * engine.getAspectRatio(camera));
  5814. size = { width: width, height: height };
  5815. }
  5816. else if (!isNaN(size)) {
  5817. height = size;
  5818. width = size;
  5819. }
  5820. else {
  5821. Tools.Error("Invalid 'size' parameter !");
  5822. return;
  5823. }
  5824. var scene = camera.getScene();
  5825. var previousCamera = null;
  5826. if (scene.activeCamera !== camera) {
  5827. previousCamera = scene.activeCamera;
  5828. scene.activeCamera = camera;
  5829. }
  5830. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  5831. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  5832. texture.renderList = scene.meshes;
  5833. texture.samples = samples;
  5834. texture.onAfterRenderObservable.add(function () {
  5835. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType);
  5836. });
  5837. scene.incrementRenderId();
  5838. scene.resetCachedMaterial();
  5839. texture.render(true);
  5840. texture.dispose();
  5841. if (previousCamera) {
  5842. scene.activeCamera = previousCamera;
  5843. }
  5844. camera.getProjectionMatrix(true); // Force cache refresh;
  5845. };
  5846. // XHR response validator for local file scenario
  5847. Tools.ValidateXHRData = function (xhr, dataType) {
  5848. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  5849. if (dataType === void 0) { dataType = 7; }
  5850. try {
  5851. if (dataType & 1) {
  5852. if (xhr.responseText && xhr.responseText.length > 0) {
  5853. return true;
  5854. }
  5855. else if (dataType === 1) {
  5856. return false;
  5857. }
  5858. }
  5859. if (dataType & 2) {
  5860. // Check header width and height since there is no "TGA" magic number
  5861. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  5862. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  5863. return true;
  5864. }
  5865. else if (dataType === 2) {
  5866. return false;
  5867. }
  5868. }
  5869. if (dataType & 4) {
  5870. // Check for the "DDS" magic number
  5871. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  5872. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  5873. return true;
  5874. }
  5875. else {
  5876. return false;
  5877. }
  5878. }
  5879. }
  5880. catch (e) {
  5881. // Global protection
  5882. }
  5883. return false;
  5884. };
  5885. /**
  5886. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  5887. * Be aware Math.random() could cause collisions, but:
  5888. * "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"
  5889. */
  5890. Tools.RandomId = function () {
  5891. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  5892. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  5893. return v.toString(16);
  5894. });
  5895. };
  5896. Object.defineProperty(Tools, "NoneLogLevel", {
  5897. get: function () {
  5898. return Tools._NoneLogLevel;
  5899. },
  5900. enumerable: true,
  5901. configurable: true
  5902. });
  5903. Object.defineProperty(Tools, "MessageLogLevel", {
  5904. get: function () {
  5905. return Tools._MessageLogLevel;
  5906. },
  5907. enumerable: true,
  5908. configurable: true
  5909. });
  5910. Object.defineProperty(Tools, "WarningLogLevel", {
  5911. get: function () {
  5912. return Tools._WarningLogLevel;
  5913. },
  5914. enumerable: true,
  5915. configurable: true
  5916. });
  5917. Object.defineProperty(Tools, "ErrorLogLevel", {
  5918. get: function () {
  5919. return Tools._ErrorLogLevel;
  5920. },
  5921. enumerable: true,
  5922. configurable: true
  5923. });
  5924. Object.defineProperty(Tools, "AllLogLevel", {
  5925. get: function () {
  5926. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  5927. },
  5928. enumerable: true,
  5929. configurable: true
  5930. });
  5931. Tools._AddLogEntry = function (entry) {
  5932. Tools._LogCache = entry + Tools._LogCache;
  5933. if (Tools.OnNewCacheEntry) {
  5934. Tools.OnNewCacheEntry(entry);
  5935. }
  5936. };
  5937. Tools._FormatMessage = function (message) {
  5938. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  5939. var date = new Date();
  5940. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  5941. };
  5942. Tools._LogDisabled = function (message) {
  5943. // nothing to do
  5944. };
  5945. Tools._LogEnabled = function (message) {
  5946. var formattedMessage = Tools._FormatMessage(message);
  5947. console.log("BJS - " + formattedMessage);
  5948. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  5949. Tools._AddLogEntry(entry);
  5950. };
  5951. Tools._WarnDisabled = function (message) {
  5952. // nothing to do
  5953. };
  5954. Tools._WarnEnabled = function (message) {
  5955. var formattedMessage = Tools._FormatMessage(message);
  5956. console.warn("BJS - " + formattedMessage);
  5957. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  5958. Tools._AddLogEntry(entry);
  5959. };
  5960. Tools._ErrorDisabled = function (message) {
  5961. // nothing to do
  5962. };
  5963. Tools._ErrorEnabled = function (message) {
  5964. Tools.errorsCount++;
  5965. var formattedMessage = Tools._FormatMessage(message);
  5966. console.error("BJS - " + formattedMessage);
  5967. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  5968. Tools._AddLogEntry(entry);
  5969. };
  5970. Object.defineProperty(Tools, "LogCache", {
  5971. get: function () {
  5972. return Tools._LogCache;
  5973. },
  5974. enumerable: true,
  5975. configurable: true
  5976. });
  5977. Tools.ClearLogCache = function () {
  5978. Tools._LogCache = "";
  5979. Tools.errorsCount = 0;
  5980. };
  5981. Object.defineProperty(Tools, "LogLevels", {
  5982. set: function (level) {
  5983. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  5984. Tools.Log = Tools._LogEnabled;
  5985. }
  5986. else {
  5987. Tools.Log = Tools._LogDisabled;
  5988. }
  5989. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  5990. Tools.Warn = Tools._WarnEnabled;
  5991. }
  5992. else {
  5993. Tools.Warn = Tools._WarnDisabled;
  5994. }
  5995. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  5996. Tools.Error = Tools._ErrorEnabled;
  5997. }
  5998. else {
  5999. Tools.Error = Tools._ErrorDisabled;
  6000. }
  6001. },
  6002. enumerable: true,
  6003. configurable: true
  6004. });
  6005. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  6006. get: function () {
  6007. return Tools._PerformanceNoneLogLevel;
  6008. },
  6009. enumerable: true,
  6010. configurable: true
  6011. });
  6012. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  6013. get: function () {
  6014. return Tools._PerformanceUserMarkLogLevel;
  6015. },
  6016. enumerable: true,
  6017. configurable: true
  6018. });
  6019. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  6020. get: function () {
  6021. return Tools._PerformanceConsoleLogLevel;
  6022. },
  6023. enumerable: true,
  6024. configurable: true
  6025. });
  6026. Object.defineProperty(Tools, "PerformanceLogLevel", {
  6027. set: function (level) {
  6028. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  6029. Tools.StartPerformanceCounter = Tools._StartUserMark;
  6030. Tools.EndPerformanceCounter = Tools._EndUserMark;
  6031. return;
  6032. }
  6033. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  6034. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  6035. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  6036. return;
  6037. }
  6038. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6039. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6040. },
  6041. enumerable: true,
  6042. configurable: true
  6043. });
  6044. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  6045. };
  6046. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  6047. };
  6048. Tools._StartUserMark = function (counterName, condition) {
  6049. if (condition === void 0) { condition = true; }
  6050. if (!condition || !Tools._performance.mark) {
  6051. return;
  6052. }
  6053. Tools._performance.mark(counterName + "-Begin");
  6054. };
  6055. Tools._EndUserMark = function (counterName, condition) {
  6056. if (condition === void 0) { condition = true; }
  6057. if (!condition || !Tools._performance.mark) {
  6058. return;
  6059. }
  6060. Tools._performance.mark(counterName + "-End");
  6061. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  6062. };
  6063. Tools._StartPerformanceConsole = function (counterName, condition) {
  6064. if (condition === void 0) { condition = true; }
  6065. if (!condition) {
  6066. return;
  6067. }
  6068. Tools._StartUserMark(counterName, condition);
  6069. if (console.time) {
  6070. console.time(counterName);
  6071. }
  6072. };
  6073. Tools._EndPerformanceConsole = function (counterName, condition) {
  6074. if (condition === void 0) { condition = true; }
  6075. if (!condition) {
  6076. return;
  6077. }
  6078. Tools._EndUserMark(counterName, condition);
  6079. if (console.time) {
  6080. console.timeEnd(counterName);
  6081. }
  6082. };
  6083. Object.defineProperty(Tools, "Now", {
  6084. get: function () {
  6085. if (window.performance && window.performance.now) {
  6086. return window.performance.now();
  6087. }
  6088. return new Date().getTime();
  6089. },
  6090. enumerable: true,
  6091. configurable: true
  6092. });
  6093. /**
  6094. * This method will return the name of the class used to create the instance of the given object.
  6095. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  6096. * @param object the object to get the class name from
  6097. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  6098. */
  6099. Tools.getClassName = function (object, isType) {
  6100. if (isType === void 0) { isType = false; }
  6101. var name = null;
  6102. if (!isType && object.getClassName) {
  6103. name = object.getClassName();
  6104. }
  6105. else {
  6106. if (object instanceof Object) {
  6107. var classObj = isType ? object : Object.getPrototypeOf(object);
  6108. name = classObj.constructor["__bjsclassName__"];
  6109. }
  6110. if (!name) {
  6111. name = typeof object;
  6112. }
  6113. }
  6114. return name;
  6115. };
  6116. Tools.first = function (array, predicate) {
  6117. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  6118. var el = array_1[_i];
  6119. if (predicate(el)) {
  6120. return el;
  6121. }
  6122. }
  6123. };
  6124. /**
  6125. * This method will return the name of the full name of the class, including its owning module (if any).
  6126. * 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).
  6127. * @param object the object to get the class name from
  6128. * @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.
  6129. */
  6130. Tools.getFullClassName = function (object, isType) {
  6131. if (isType === void 0) { isType = false; }
  6132. var className = null;
  6133. var moduleName = null;
  6134. if (!isType && object.getClassName) {
  6135. className = object.getClassName();
  6136. }
  6137. else {
  6138. if (object instanceof Object) {
  6139. var classObj = isType ? object : Object.getPrototypeOf(object);
  6140. className = classObj.constructor["__bjsclassName__"];
  6141. moduleName = classObj.constructor["__bjsmoduleName__"];
  6142. }
  6143. if (!className) {
  6144. className = typeof object;
  6145. }
  6146. }
  6147. if (!className) {
  6148. return null;
  6149. }
  6150. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  6151. };
  6152. /**
  6153. * 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.
  6154. * @param array
  6155. */
  6156. Tools.arrayOrStringFeeder = function (array) {
  6157. return function (index) {
  6158. if (index >= array.length) {
  6159. return null;
  6160. }
  6161. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  6162. if (val && val.getHashCode) {
  6163. val = val.getHashCode();
  6164. }
  6165. if (typeof val === "string") {
  6166. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  6167. }
  6168. return val;
  6169. };
  6170. };
  6171. /**
  6172. * Compute the hashCode of a stream of number
  6173. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  6174. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  6175. * @return the hash code computed
  6176. */
  6177. Tools.hashCodeFromStream = function (feeder) {
  6178. // Based from here: http://stackoverflow.com/a/7616484/802124
  6179. var hash = 0;
  6180. var index = 0;
  6181. var chr = feeder(index++);
  6182. while (chr != null) {
  6183. hash = ((hash << 5) - hash) + chr;
  6184. hash |= 0; // Convert to 32bit integer
  6185. chr = feeder(index++);
  6186. }
  6187. return hash;
  6188. };
  6189. return Tools;
  6190. }());
  6191. Tools.BaseUrl = "";
  6192. Tools.CorsBehavior = "anonymous";
  6193. Tools.UseFallbackTexture = true;
  6194. // Used in case of a texture loading problem
  6195. 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";
  6196. // Logs
  6197. Tools._NoneLogLevel = 0;
  6198. Tools._MessageLogLevel = 1;
  6199. Tools._WarningLogLevel = 2;
  6200. Tools._ErrorLogLevel = 4;
  6201. Tools._LogCache = "";
  6202. Tools.errorsCount = 0;
  6203. Tools.Log = Tools._LogEnabled;
  6204. Tools.Warn = Tools._WarnEnabled;
  6205. Tools.Error = Tools._ErrorEnabled;
  6206. // Performances
  6207. Tools._PerformanceNoneLogLevel = 0;
  6208. Tools._PerformanceUserMarkLogLevel = 1;
  6209. Tools._PerformanceConsoleLogLevel = 2;
  6210. Tools._performance = window.performance;
  6211. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6212. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6213. BABYLON.Tools = Tools;
  6214. /**
  6215. * This class is used to track a performance counter which is number based.
  6216. * The user has access to many properties which give statistics of different nature
  6217. *
  6218. * The implementer can track two kinds of Performance Counter: time and count
  6219. * 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.
  6220. * 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.
  6221. */
  6222. var PerfCounter = (function () {
  6223. function PerfCounter() {
  6224. this._startMonitoringTime = 0;
  6225. this._min = 0;
  6226. this._max = 0;
  6227. this._average = 0;
  6228. this._lastSecAverage = 0;
  6229. this._current = 0;
  6230. this._totalValueCount = 0;
  6231. this._totalAccumulated = 0;
  6232. this._lastSecAccumulated = 0;
  6233. this._lastSecTime = 0;
  6234. this._lastSecValueCount = 0;
  6235. }
  6236. Object.defineProperty(PerfCounter.prototype, "min", {
  6237. /**
  6238. * Returns the smallest value ever
  6239. */
  6240. get: function () {
  6241. return this._min;
  6242. },
  6243. enumerable: true,
  6244. configurable: true
  6245. });
  6246. Object.defineProperty(PerfCounter.prototype, "max", {
  6247. /**
  6248. * Returns the biggest value ever
  6249. */
  6250. get: function () {
  6251. return this._max;
  6252. },
  6253. enumerable: true,
  6254. configurable: true
  6255. });
  6256. Object.defineProperty(PerfCounter.prototype, "average", {
  6257. /**
  6258. * Returns the average value since the performance counter is running
  6259. */
  6260. get: function () {
  6261. return this._average;
  6262. },
  6263. enumerable: true,
  6264. configurable: true
  6265. });
  6266. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  6267. /**
  6268. * Returns the average value of the last second the counter was monitored
  6269. */
  6270. get: function () {
  6271. return this._lastSecAverage;
  6272. },
  6273. enumerable: true,
  6274. configurable: true
  6275. });
  6276. Object.defineProperty(PerfCounter.prototype, "current", {
  6277. /**
  6278. * Returns the current value
  6279. */
  6280. get: function () {
  6281. return this._current;
  6282. },
  6283. enumerable: true,
  6284. configurable: true
  6285. });
  6286. Object.defineProperty(PerfCounter.prototype, "total", {
  6287. get: function () {
  6288. return this._totalAccumulated;
  6289. },
  6290. enumerable: true,
  6291. configurable: true
  6292. });
  6293. /**
  6294. * Call this method to start monitoring a new frame.
  6295. * 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.
  6296. */
  6297. PerfCounter.prototype.fetchNewFrame = function () {
  6298. this._totalValueCount++;
  6299. this._current = 0;
  6300. this._lastSecValueCount++;
  6301. };
  6302. /**
  6303. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  6304. * @param newCount the count value to add to the monitored count
  6305. * @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.
  6306. */
  6307. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  6308. if (!PerfCounter.Enabled) {
  6309. return;
  6310. }
  6311. this._current += newCount;
  6312. if (fetchResult) {
  6313. this._fetchResult();
  6314. }
  6315. };
  6316. /**
  6317. * Start monitoring this performance counter
  6318. */
  6319. PerfCounter.prototype.beginMonitoring = function () {
  6320. if (!PerfCounter.Enabled) {
  6321. return;
  6322. }
  6323. this._startMonitoringTime = Tools.Now;
  6324. };
  6325. /**
  6326. * Compute the time lapsed since the previous beginMonitoring() call.
  6327. * @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
  6328. */
  6329. PerfCounter.prototype.endMonitoring = function (newFrame) {
  6330. if (newFrame === void 0) { newFrame = true; }
  6331. if (!PerfCounter.Enabled) {
  6332. return;
  6333. }
  6334. if (newFrame) {
  6335. this.fetchNewFrame();
  6336. }
  6337. var currentTime = Tools.Now;
  6338. this._current = currentTime - this._startMonitoringTime;
  6339. if (newFrame) {
  6340. this._fetchResult();
  6341. }
  6342. };
  6343. PerfCounter.prototype._fetchResult = function () {
  6344. this._totalAccumulated += this._current;
  6345. this._lastSecAccumulated += this._current;
  6346. // Min/Max update
  6347. this._min = Math.min(this._min, this._current);
  6348. this._max = Math.max(this._max, this._current);
  6349. this._average = this._totalAccumulated / this._totalValueCount;
  6350. // Reset last sec?
  6351. var now = Tools.Now;
  6352. if ((now - this._lastSecTime) > 1000) {
  6353. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  6354. this._lastSecTime = now;
  6355. this._lastSecAccumulated = 0;
  6356. this._lastSecValueCount = 0;
  6357. }
  6358. };
  6359. return PerfCounter;
  6360. }());
  6361. PerfCounter.Enabled = true;
  6362. BABYLON.PerfCounter = PerfCounter;
  6363. /**
  6364. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  6365. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  6366. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  6367. * @param name The name of the class, case should be preserved
  6368. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  6369. */
  6370. function className(name, module) {
  6371. return function (target) {
  6372. target["__bjsclassName__"] = name;
  6373. target["__bjsmoduleName__"] = (module != null) ? module : null;
  6374. };
  6375. }
  6376. BABYLON.className = className;
  6377. /**
  6378. * An implementation of a loop for asynchronous functions.
  6379. */
  6380. var AsyncLoop = (function () {
  6381. /**
  6382. * Constroctor.
  6383. * @param iterations the number of iterations.
  6384. * @param _fn the function to run each iteration
  6385. * @param _successCallback the callback that will be called upon succesful execution
  6386. * @param offset starting offset.
  6387. */
  6388. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  6389. if (offset === void 0) { offset = 0; }
  6390. this.iterations = iterations;
  6391. this._fn = _fn;
  6392. this._successCallback = _successCallback;
  6393. this.index = offset - 1;
  6394. this._done = false;
  6395. }
  6396. /**
  6397. * Execute the next iteration. Must be called after the last iteration was finished.
  6398. */
  6399. AsyncLoop.prototype.executeNext = function () {
  6400. if (!this._done) {
  6401. if (this.index + 1 < this.iterations) {
  6402. ++this.index;
  6403. this._fn(this);
  6404. }
  6405. else {
  6406. this.breakLoop();
  6407. }
  6408. }
  6409. };
  6410. /**
  6411. * Break the loop and run the success callback.
  6412. */
  6413. AsyncLoop.prototype.breakLoop = function () {
  6414. this._done = true;
  6415. this._successCallback();
  6416. };
  6417. /**
  6418. * Helper function
  6419. */
  6420. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  6421. if (offset === void 0) { offset = 0; }
  6422. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  6423. loop.executeNext();
  6424. return loop;
  6425. };
  6426. /**
  6427. * A for-loop that will run a given number of iterations synchronous and the rest async.
  6428. * @param iterations total number of iterations
  6429. * @param syncedIterations number of synchronous iterations in each async iteration.
  6430. * @param fn the function to call each iteration.
  6431. * @param callback a success call back that will be called when iterating stops.
  6432. * @param breakFunction a break condition (optional)
  6433. * @param timeout timeout settings for the setTimeout function. default - 0.
  6434. * @constructor
  6435. */
  6436. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  6437. if (timeout === void 0) { timeout = 0; }
  6438. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  6439. if (breakFunction && breakFunction())
  6440. loop.breakLoop();
  6441. else {
  6442. setTimeout(function () {
  6443. for (var i = 0; i < syncedIterations; ++i) {
  6444. var iteration = (loop.index * syncedIterations) + i;
  6445. if (iteration >= iterations)
  6446. break;
  6447. fn(iteration);
  6448. if (breakFunction && breakFunction()) {
  6449. loop.breakLoop();
  6450. break;
  6451. }
  6452. }
  6453. loop.executeNext();
  6454. }, timeout);
  6455. }
  6456. }, callback);
  6457. };
  6458. return AsyncLoop;
  6459. }());
  6460. BABYLON.AsyncLoop = AsyncLoop;
  6461. })(BABYLON || (BABYLON = {}));
  6462. //# sourceMappingURL=babylon.tools.js.map
  6463. var BABYLON;
  6464. (function (BABYLON) {
  6465. var Internals;
  6466. (function (Internals) {
  6467. var _AlphaState = (function () {
  6468. /**
  6469. * Initializes the state.
  6470. */
  6471. function _AlphaState() {
  6472. this._isAlphaBlendDirty = false;
  6473. this._isBlendFunctionParametersDirty = false;
  6474. this._alphaBlend = false;
  6475. this._blendFunctionParameters = new Array(4);
  6476. this.reset();
  6477. }
  6478. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  6479. get: function () {
  6480. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  6481. },
  6482. enumerable: true,
  6483. configurable: true
  6484. });
  6485. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  6486. get: function () {
  6487. return this._alphaBlend;
  6488. },
  6489. set: function (value) {
  6490. if (this._alphaBlend === value) {
  6491. return;
  6492. }
  6493. this._alphaBlend = value;
  6494. this._isAlphaBlendDirty = true;
  6495. },
  6496. enumerable: true,
  6497. configurable: true
  6498. });
  6499. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  6500. if (this._blendFunctionParameters[0] === value0 &&
  6501. this._blendFunctionParameters[1] === value1 &&
  6502. this._blendFunctionParameters[2] === value2 &&
  6503. this._blendFunctionParameters[3] === value3) {
  6504. return;
  6505. }
  6506. this._blendFunctionParameters[0] = value0;
  6507. this._blendFunctionParameters[1] = value1;
  6508. this._blendFunctionParameters[2] = value2;
  6509. this._blendFunctionParameters[3] = value3;
  6510. this._isBlendFunctionParametersDirty = true;
  6511. };
  6512. _AlphaState.prototype.reset = function () {
  6513. this._alphaBlend = false;
  6514. this._blendFunctionParameters[0] = null;
  6515. this._blendFunctionParameters[1] = null;
  6516. this._blendFunctionParameters[2] = null;
  6517. this._blendFunctionParameters[3] = null;
  6518. this._isAlphaBlendDirty = true;
  6519. this._isBlendFunctionParametersDirty = false;
  6520. };
  6521. _AlphaState.prototype.apply = function (gl) {
  6522. if (!this.isDirty) {
  6523. return;
  6524. }
  6525. // Alpha blend
  6526. if (this._isAlphaBlendDirty) {
  6527. if (this._alphaBlend) {
  6528. gl.enable(gl.BLEND);
  6529. }
  6530. else {
  6531. gl.disable(gl.BLEND);
  6532. }
  6533. this._isAlphaBlendDirty = false;
  6534. }
  6535. // Alpha function
  6536. if (this._isBlendFunctionParametersDirty) {
  6537. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  6538. this._isBlendFunctionParametersDirty = false;
  6539. }
  6540. };
  6541. return _AlphaState;
  6542. }());
  6543. Internals._AlphaState = _AlphaState;
  6544. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6545. })(BABYLON || (BABYLON = {}));
  6546. //# sourceMappingURL=babylon.alphaCullingState.js.map
  6547. var BABYLON;
  6548. (function (BABYLON) {
  6549. var Internals;
  6550. (function (Internals) {
  6551. var _DepthCullingState = (function () {
  6552. /**
  6553. * Initializes the state.
  6554. */
  6555. function _DepthCullingState() {
  6556. this._isDepthTestDirty = false;
  6557. this._isDepthMaskDirty = false;
  6558. this._isDepthFuncDirty = false;
  6559. this._isCullFaceDirty = false;
  6560. this._isCullDirty = false;
  6561. this._isZOffsetDirty = false;
  6562. this.reset();
  6563. }
  6564. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  6565. get: function () {
  6566. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  6567. },
  6568. enumerable: true,
  6569. configurable: true
  6570. });
  6571. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  6572. get: function () {
  6573. return this._zOffset;
  6574. },
  6575. set: function (value) {
  6576. if (this._zOffset === value) {
  6577. return;
  6578. }
  6579. this._zOffset = value;
  6580. this._isZOffsetDirty = true;
  6581. },
  6582. enumerable: true,
  6583. configurable: true
  6584. });
  6585. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  6586. get: function () {
  6587. return this._cullFace;
  6588. },
  6589. set: function (value) {
  6590. if (this._cullFace === value) {
  6591. return;
  6592. }
  6593. this._cullFace = value;
  6594. this._isCullFaceDirty = true;
  6595. },
  6596. enumerable: true,
  6597. configurable: true
  6598. });
  6599. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  6600. get: function () {
  6601. return this._cull;
  6602. },
  6603. set: function (value) {
  6604. if (this._cull === value) {
  6605. return;
  6606. }
  6607. this._cull = value;
  6608. this._isCullDirty = true;
  6609. },
  6610. enumerable: true,
  6611. configurable: true
  6612. });
  6613. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  6614. get: function () {
  6615. return this._depthFunc;
  6616. },
  6617. set: function (value) {
  6618. if (this._depthFunc === value) {
  6619. return;
  6620. }
  6621. this._depthFunc = value;
  6622. this._isDepthFuncDirty = true;
  6623. },
  6624. enumerable: true,
  6625. configurable: true
  6626. });
  6627. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  6628. get: function () {
  6629. return this._depthMask;
  6630. },
  6631. set: function (value) {
  6632. if (this._depthMask === value) {
  6633. return;
  6634. }
  6635. this._depthMask = value;
  6636. this._isDepthMaskDirty = true;
  6637. },
  6638. enumerable: true,
  6639. configurable: true
  6640. });
  6641. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  6642. get: function () {
  6643. return this._depthTest;
  6644. },
  6645. set: function (value) {
  6646. if (this._depthTest === value) {
  6647. return;
  6648. }
  6649. this._depthTest = value;
  6650. this._isDepthTestDirty = true;
  6651. },
  6652. enumerable: true,
  6653. configurable: true
  6654. });
  6655. _DepthCullingState.prototype.reset = function () {
  6656. this._depthMask = true;
  6657. this._depthTest = true;
  6658. this._depthFunc = null;
  6659. this._cullFace = null;
  6660. this._cull = null;
  6661. this._zOffset = 0;
  6662. this._isDepthTestDirty = true;
  6663. this._isDepthMaskDirty = true;
  6664. this._isDepthFuncDirty = false;
  6665. this._isCullFaceDirty = false;
  6666. this._isCullDirty = false;
  6667. this._isZOffsetDirty = false;
  6668. };
  6669. _DepthCullingState.prototype.apply = function (gl) {
  6670. if (!this.isDirty) {
  6671. return;
  6672. }
  6673. // Cull
  6674. if (this._isCullDirty) {
  6675. if (this.cull) {
  6676. gl.enable(gl.CULL_FACE);
  6677. }
  6678. else {
  6679. gl.disable(gl.CULL_FACE);
  6680. }
  6681. this._isCullDirty = false;
  6682. }
  6683. // Cull face
  6684. if (this._isCullFaceDirty) {
  6685. gl.cullFace(this.cullFace);
  6686. this._isCullFaceDirty = false;
  6687. }
  6688. // Depth mask
  6689. if (this._isDepthMaskDirty) {
  6690. gl.depthMask(this.depthMask);
  6691. this._isDepthMaskDirty = false;
  6692. }
  6693. // Depth test
  6694. if (this._isDepthTestDirty) {
  6695. if (this.depthTest) {
  6696. gl.enable(gl.DEPTH_TEST);
  6697. }
  6698. else {
  6699. gl.disable(gl.DEPTH_TEST);
  6700. }
  6701. this._isDepthTestDirty = false;
  6702. }
  6703. // Depth func
  6704. if (this._isDepthFuncDirty) {
  6705. gl.depthFunc(this.depthFunc);
  6706. this._isDepthFuncDirty = false;
  6707. }
  6708. // zOffset
  6709. if (this._isZOffsetDirty) {
  6710. if (this.zOffset) {
  6711. gl.enable(gl.POLYGON_OFFSET_FILL);
  6712. gl.polygonOffset(this.zOffset, 0);
  6713. }
  6714. else {
  6715. gl.disable(gl.POLYGON_OFFSET_FILL);
  6716. }
  6717. this._isZOffsetDirty = false;
  6718. }
  6719. };
  6720. return _DepthCullingState;
  6721. }());
  6722. Internals._DepthCullingState = _DepthCullingState;
  6723. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6724. })(BABYLON || (BABYLON = {}));
  6725. //# sourceMappingURL=babylon.depthCullingState.js.map
  6726. var BABYLON;
  6727. (function (BABYLON) {
  6728. var Internals;
  6729. (function (Internals) {
  6730. var _StencilState = (function () {
  6731. function _StencilState() {
  6732. this._isStencilTestDirty = false;
  6733. this._isStencilMaskDirty = false;
  6734. this._isStencilFuncDirty = false;
  6735. this._isStencilOpDirty = false;
  6736. this.reset();
  6737. }
  6738. Object.defineProperty(_StencilState.prototype, "isDirty", {
  6739. get: function () {
  6740. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  6741. },
  6742. enumerable: true,
  6743. configurable: true
  6744. });
  6745. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  6746. get: function () {
  6747. return this._stencilFunc;
  6748. },
  6749. set: function (value) {
  6750. if (this._stencilFunc === value) {
  6751. return;
  6752. }
  6753. this._stencilFunc = value;
  6754. this._isStencilFuncDirty = true;
  6755. },
  6756. enumerable: true,
  6757. configurable: true
  6758. });
  6759. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  6760. get: function () {
  6761. return this._stencilFuncRef;
  6762. },
  6763. set: function (value) {
  6764. if (this._stencilFuncRef === value) {
  6765. return;
  6766. }
  6767. this._stencilFuncRef = value;
  6768. this._isStencilFuncDirty = true;
  6769. },
  6770. enumerable: true,
  6771. configurable: true
  6772. });
  6773. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  6774. get: function () {
  6775. return this._stencilFuncMask;
  6776. },
  6777. set: function (value) {
  6778. if (this._stencilFuncMask === value) {
  6779. return;
  6780. }
  6781. this._stencilFuncMask = value;
  6782. this._isStencilFuncDirty = true;
  6783. },
  6784. enumerable: true,
  6785. configurable: true
  6786. });
  6787. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  6788. get: function () {
  6789. return this._stencilOpStencilFail;
  6790. },
  6791. set: function (value) {
  6792. if (this._stencilOpStencilFail === value) {
  6793. return;
  6794. }
  6795. this._stencilOpStencilFail = value;
  6796. this._isStencilOpDirty = true;
  6797. },
  6798. enumerable: true,
  6799. configurable: true
  6800. });
  6801. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  6802. get: function () {
  6803. return this._stencilOpDepthFail;
  6804. },
  6805. set: function (value) {
  6806. if (this._stencilOpDepthFail === value) {
  6807. return;
  6808. }
  6809. this._stencilOpDepthFail = value;
  6810. this._isStencilOpDirty = true;
  6811. },
  6812. enumerable: true,
  6813. configurable: true
  6814. });
  6815. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  6816. get: function () {
  6817. return this._stencilOpStencilDepthPass;
  6818. },
  6819. set: function (value) {
  6820. if (this._stencilOpStencilDepthPass === value) {
  6821. return;
  6822. }
  6823. this._stencilOpStencilDepthPass = value;
  6824. this._isStencilOpDirty = true;
  6825. },
  6826. enumerable: true,
  6827. configurable: true
  6828. });
  6829. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  6830. get: function () {
  6831. return this._stencilMask;
  6832. },
  6833. set: function (value) {
  6834. if (this._stencilMask === value) {
  6835. return;
  6836. }
  6837. this._stencilMask = value;
  6838. this._isStencilMaskDirty = true;
  6839. },
  6840. enumerable: true,
  6841. configurable: true
  6842. });
  6843. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  6844. get: function () {
  6845. return this._stencilTest;
  6846. },
  6847. set: function (value) {
  6848. if (this._stencilTest === value) {
  6849. return;
  6850. }
  6851. this._stencilTest = value;
  6852. this._isStencilTestDirty = true;
  6853. },
  6854. enumerable: true,
  6855. configurable: true
  6856. });
  6857. _StencilState.prototype.reset = function () {
  6858. this._stencilTest = false;
  6859. this._stencilMask = 0xFF;
  6860. this._stencilFunc = BABYLON.Engine.ALWAYS;
  6861. this._stencilFuncRef = 1;
  6862. this._stencilFuncMask = 0xFF;
  6863. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  6864. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  6865. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  6866. this._isStencilTestDirty = true;
  6867. this._isStencilMaskDirty = true;
  6868. this._isStencilFuncDirty = true;
  6869. this._isStencilOpDirty = true;
  6870. };
  6871. _StencilState.prototype.apply = function (gl) {
  6872. if (!this.isDirty) {
  6873. return;
  6874. }
  6875. // Stencil test
  6876. if (this._isStencilTestDirty) {
  6877. if (this.stencilTest) {
  6878. gl.enable(gl.STENCIL_TEST);
  6879. }
  6880. else {
  6881. gl.disable(gl.STENCIL_TEST);
  6882. }
  6883. this._isStencilTestDirty = false;
  6884. }
  6885. // Stencil mask
  6886. if (this._isStencilMaskDirty) {
  6887. gl.stencilMask(this.stencilMask);
  6888. this._isStencilMaskDirty = false;
  6889. }
  6890. // Stencil func
  6891. if (this._isStencilFuncDirty) {
  6892. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  6893. this._isStencilFuncDirty = false;
  6894. }
  6895. // Stencil op
  6896. if (this._isStencilOpDirty) {
  6897. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  6898. this._isStencilOpDirty = false;
  6899. }
  6900. };
  6901. return _StencilState;
  6902. }());
  6903. Internals._StencilState = _StencilState;
  6904. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6905. })(BABYLON || (BABYLON = {}));
  6906. //# sourceMappingURL=babylon.stencilState.js.map
  6907. var BABYLON;
  6908. (function (BABYLON) {
  6909. var compileShader = function (gl, source, type, defines, shaderVersion) {
  6910. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  6911. gl.shaderSource(shader, shaderVersion + (defines ? defines + "\n" : "") + source);
  6912. gl.compileShader(shader);
  6913. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  6914. throw new Error(gl.getShaderInfoLog(shader));
  6915. }
  6916. return shader;
  6917. };
  6918. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  6919. var magFilter = gl.NEAREST;
  6920. var minFilter = gl.NEAREST;
  6921. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6922. magFilter = gl.LINEAR;
  6923. if (generateMipMaps) {
  6924. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  6925. }
  6926. else {
  6927. minFilter = gl.LINEAR;
  6928. }
  6929. }
  6930. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6931. magFilter = gl.LINEAR;
  6932. if (generateMipMaps) {
  6933. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6934. }
  6935. else {
  6936. minFilter = gl.LINEAR;
  6937. }
  6938. }
  6939. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6940. magFilter = gl.NEAREST;
  6941. if (generateMipMaps) {
  6942. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  6943. }
  6944. else {
  6945. minFilter = gl.NEAREST;
  6946. }
  6947. }
  6948. return {
  6949. min: minFilter,
  6950. mag: magFilter
  6951. };
  6952. };
  6953. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  6954. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6955. var engine = scene.getEngine();
  6956. if (!engine) {
  6957. return;
  6958. }
  6959. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  6960. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  6961. engine._bindTextureDirectly(gl.TEXTURE_2D, texture);
  6962. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6963. texture._baseWidth = width;
  6964. texture._baseHeight = height;
  6965. texture._width = potWidth;
  6966. texture._height = potHeight;
  6967. texture.isReady = true;
  6968. processFunction(potWidth, potHeight);
  6969. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  6970. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6971. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6972. if (!noMipmap && !isCompressed) {
  6973. gl.generateMipmap(gl.TEXTURE_2D);
  6974. }
  6975. engine._bindTextureDirectly(gl.TEXTURE_2D, null);
  6976. engine.resetTextureCache();
  6977. scene._removePendingData(texture);
  6978. texture.onLoadedCallbacks.forEach(function (callback) {
  6979. callback();
  6980. });
  6981. texture.onLoadedCallbacks = [];
  6982. };
  6983. var partialLoad = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  6984. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  6985. var img;
  6986. var onload = function () {
  6987. loadedImages[index] = img;
  6988. loadedImages._internalCount++;
  6989. scene._removePendingData(img);
  6990. if (loadedImages._internalCount === 6) {
  6991. onfinish(loadedImages);
  6992. }
  6993. };
  6994. var onerror = function () {
  6995. scene._removePendingData(img);
  6996. if (onErrorCallBack) {
  6997. onErrorCallBack();
  6998. }
  6999. };
  7000. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  7001. scene._addPendingData(img);
  7002. };
  7003. var cascadeLoad = function (rootUrl, scene, onfinish, files, onError) {
  7004. if (onError === void 0) { onError = null; }
  7005. var loadedImages = [];
  7006. loadedImages._internalCount = 0;
  7007. for (var index = 0; index < 6; index++) {
  7008. partialLoad(files[index], index, loadedImages, scene, onfinish, onError);
  7009. }
  7010. };
  7011. var InstancingAttributeInfo = (function () {
  7012. function InstancingAttributeInfo() {
  7013. }
  7014. return InstancingAttributeInfo;
  7015. }());
  7016. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  7017. var EngineCapabilities = (function () {
  7018. function EngineCapabilities() {
  7019. }
  7020. return EngineCapabilities;
  7021. }());
  7022. BABYLON.EngineCapabilities = EngineCapabilities;
  7023. /**
  7024. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  7025. */
  7026. var Engine = (function () {
  7027. /**
  7028. * @constructor
  7029. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  7030. * @param {boolean} [antialias] - enable antialias
  7031. * @param options - further options to be sent to the getContext function
  7032. */
  7033. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  7034. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  7035. var _this = this;
  7036. // Public members
  7037. this.isFullscreen = false;
  7038. this.isPointerLock = false;
  7039. this.cullBackFaces = true;
  7040. this.renderEvenInBackground = true;
  7041. this.preventCacheWipeBetweenFrames = false;
  7042. // To enable/disable IDB support and avoid XHR on .manifest
  7043. this.enableOfflineSupport = BABYLON.Database;
  7044. this.scenes = new Array();
  7045. // Observables
  7046. /**
  7047. * Observable event triggered each time the rendering canvas is resized
  7048. */
  7049. this.onResizeObservable = new BABYLON.Observable();
  7050. this._windowIsBackground = false;
  7051. this._webGLVersion = 1.0;
  7052. this._badOS = false;
  7053. this._drawCalls = new BABYLON.PerfCounter();
  7054. this._renderingQueueLaunched = false;
  7055. this._activeRenderLoops = [];
  7056. // FPS
  7057. this.fpsRange = 60;
  7058. this.previousFramesDuration = [];
  7059. this.fps = 60;
  7060. this.deltaTime = 0;
  7061. // States
  7062. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  7063. this._stencilState = new BABYLON.Internals._StencilState();
  7064. this._alphaState = new BABYLON.Internals._AlphaState();
  7065. this._alphaMode = Engine.ALPHA_DISABLE;
  7066. // Cache
  7067. this._loadedTexturesCache = new Array();
  7068. this._maxTextureChannels = 16;
  7069. this._activeTexturesCache = new Array(this._maxTextureChannels);
  7070. this._compiledEffects = {};
  7071. this._vertexAttribArraysEnabled = [];
  7072. this._uintIndicesCurrentlySet = false;
  7073. this._currentBoundBuffer = new Array();
  7074. this._currentBufferPointers = [];
  7075. this._currentInstanceLocations = new Array();
  7076. this._currentInstanceBuffers = new Array();
  7077. this._vaoRecordInProgress = false;
  7078. this._mustWipeVertexAttributes = false;
  7079. // Hardware supported Compressed Textures
  7080. this._texturesSupported = new Array();
  7081. this._onVRFullScreenTriggered = function () {
  7082. if (_this._vrDisplayEnabled && _this._vrDisplayEnabled.isPresenting) {
  7083. //get the old size before we change
  7084. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  7085. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  7086. //get the width and height, change the render size
  7087. var leftEye = _this._vrDisplayEnabled.getEyeParameters('left');
  7088. var width, height;
  7089. _this.setHardwareScalingLevel(1);
  7090. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  7091. }
  7092. else {
  7093. //When the specs are implemented, need to uncomment this.
  7094. //this._vrDisplayEnabled.cancelAnimationFrame(this._vrAnimationFrameHandler);
  7095. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  7096. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  7097. _this._vrDisplayEnabled = undefined;
  7098. }
  7099. };
  7100. this._renderingCanvas = canvas;
  7101. Engine.Instances.push(this);
  7102. options = options || {};
  7103. if (antialias != null) {
  7104. options.antialias = antialias;
  7105. }
  7106. if (options.preserveDrawingBuffer === undefined) {
  7107. options.preserveDrawingBuffer = false;
  7108. }
  7109. if (options.audioEngine === undefined) {
  7110. options.audioEngine = true;
  7111. }
  7112. if (options.stencil === undefined) {
  7113. options.stencil = true;
  7114. }
  7115. // GL
  7116. if (!options.disableWebGL2Support) {
  7117. try {
  7118. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  7119. if (this._gl) {
  7120. this._webGLVersion = 2.0;
  7121. }
  7122. }
  7123. catch (e) {
  7124. // Do nothing
  7125. }
  7126. }
  7127. if (!this._gl) {
  7128. if (!canvas) {
  7129. throw new Error("The provided canvas is null or undefined.");
  7130. }
  7131. try {
  7132. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  7133. }
  7134. catch (e) {
  7135. throw new Error("WebGL not supported");
  7136. }
  7137. }
  7138. if (!this._gl) {
  7139. throw new Error("WebGL not supported");
  7140. }
  7141. this._onBlur = function () {
  7142. _this._windowIsBackground = true;
  7143. };
  7144. this._onFocus = function () {
  7145. _this._windowIsBackground = false;
  7146. };
  7147. window.addEventListener("blur", this._onBlur);
  7148. window.addEventListener("focus", this._onFocus);
  7149. // Viewport
  7150. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  7151. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  7152. this.resize();
  7153. // Caps
  7154. this._isStencilEnable = options.stencil;
  7155. this._caps = new EngineCapabilities();
  7156. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  7157. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  7158. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  7159. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  7160. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  7161. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  7162. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  7163. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  7164. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  7165. // Infos
  7166. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  7167. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  7168. if (rendererInfo != null) {
  7169. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  7170. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  7171. }
  7172. if (!this._glVendor) {
  7173. this._glVendor = "Unknown vendor";
  7174. }
  7175. if (!this._glRenderer) {
  7176. this._glRenderer = "Unknown renderer";
  7177. }
  7178. // Extensions
  7179. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  7180. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  7181. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  7182. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  7183. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  7184. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  7185. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  7186. 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');
  7187. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  7188. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  7189. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  7190. this._caps.highPrecisionShaderSupported = true;
  7191. this._caps.drawBuffersExtension = this._webGLVersion > 1 || this._gl.getExtension('WEBGL_draw_buffers');
  7192. // Checks if some of the format renders first to allow the use of webgl inspector.
  7193. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  7194. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  7195. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  7196. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  7197. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  7198. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  7199. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  7200. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  7201. // Vertex array object
  7202. if (this._webGLVersion > 1) {
  7203. this._caps.vertexArrayObject = true;
  7204. }
  7205. else {
  7206. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  7207. if (vertexArrayObjectExtension != null) {
  7208. this._caps.vertexArrayObject = true;
  7209. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  7210. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  7211. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  7212. }
  7213. else {
  7214. this._caps.vertexArrayObject = false;
  7215. }
  7216. }
  7217. // Instances count
  7218. if (this._webGLVersion > 1) {
  7219. this._caps.instancedArrays = true;
  7220. }
  7221. else {
  7222. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  7223. if (instanceExtension != null) {
  7224. this._caps.instancedArrays = true;
  7225. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  7226. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  7227. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  7228. }
  7229. else {
  7230. this._caps.instancedArrays = false;
  7231. }
  7232. }
  7233. // Intelligently add supported compressed formats in order to check for.
  7234. // Check for ASTC support first as it is most powerful and to be very cross platform.
  7235. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  7236. // Likely no hardware which supports both PVR & DXT, so order matters little.
  7237. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  7238. if (this._caps.astc)
  7239. this.texturesSupported.push('-astc.ktx');
  7240. if (this._caps.s3tc)
  7241. this.texturesSupported.push('-dxt.ktx');
  7242. if (this._caps.pvrtc)
  7243. this.texturesSupported.push('-pvrtc.ktx');
  7244. if (this._caps.etc2)
  7245. this.texturesSupported.push('-etc2.ktx');
  7246. if (this._caps.etc1)
  7247. this.texturesSupported.push('-etc1.ktx');
  7248. if (this._gl.getShaderPrecisionFormat) {
  7249. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  7250. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  7251. }
  7252. // Depth buffer
  7253. this.setDepthBuffer(true);
  7254. this.setDepthFunctionToLessOrEqual();
  7255. this.setDepthWrite(true);
  7256. // Fullscreen
  7257. this._onFullscreenChange = function () {
  7258. if (document.fullscreen !== undefined) {
  7259. _this.isFullscreen = document.fullscreen;
  7260. }
  7261. else if (document.mozFullScreen !== undefined) {
  7262. _this.isFullscreen = document.mozFullScreen;
  7263. }
  7264. else if (document.webkitIsFullScreen !== undefined) {
  7265. _this.isFullscreen = document.webkitIsFullScreen;
  7266. }
  7267. else if (document.msIsFullScreen !== undefined) {
  7268. _this.isFullscreen = document.msIsFullScreen;
  7269. }
  7270. // Pointer lock
  7271. if (_this.isFullscreen && _this._pointerLockRequested) {
  7272. canvas.requestPointerLock = canvas.requestPointerLock ||
  7273. canvas.msRequestPointerLock ||
  7274. canvas.mozRequestPointerLock ||
  7275. canvas.webkitRequestPointerLock;
  7276. if (canvas.requestPointerLock) {
  7277. canvas.requestPointerLock();
  7278. }
  7279. }
  7280. };
  7281. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  7282. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  7283. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  7284. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  7285. // Pointer lock
  7286. this._onPointerLockChange = function () {
  7287. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  7288. document.webkitPointerLockElement === canvas ||
  7289. document.msPointerLockElement === canvas ||
  7290. document.pointerLockElement === canvas);
  7291. };
  7292. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  7293. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  7294. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  7295. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  7296. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  7297. Engine.audioEngine = new BABYLON.AudioEngine();
  7298. }
  7299. //Load WebVR Devices
  7300. if (options.autoEnableWebVR) {
  7301. this.initWebVR();
  7302. }
  7303. //Detect if we are running on a faulty buggy OS.
  7304. var regexp = /AppleWebKit.*10.[\d] Mobile/;
  7305. //ua sniffing is the tool of the devil.
  7306. this._badOS = regexp.test(navigator.userAgent);
  7307. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  7308. }
  7309. Object.defineProperty(Engine, "LastCreatedEngine", {
  7310. get: function () {
  7311. if (Engine.Instances.length === 0) {
  7312. return null;
  7313. }
  7314. return Engine.Instances[Engine.Instances.length - 1];
  7315. },
  7316. enumerable: true,
  7317. configurable: true
  7318. });
  7319. Object.defineProperty(Engine, "LastCreatedScene", {
  7320. get: function () {
  7321. var lastCreatedEngine = Engine.LastCreatedEngine;
  7322. if (!lastCreatedEngine) {
  7323. return null;
  7324. }
  7325. if (lastCreatedEngine.scenes.length === 0) {
  7326. return null;
  7327. }
  7328. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  7329. },
  7330. enumerable: true,
  7331. configurable: true
  7332. });
  7333. /**
  7334. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  7335. */
  7336. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  7337. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  7338. var engine = Engine.Instances[engineIndex];
  7339. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  7340. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  7341. }
  7342. }
  7343. };
  7344. Object.defineProperty(Engine, "NEVER", {
  7345. get: function () {
  7346. return Engine._NEVER;
  7347. },
  7348. enumerable: true,
  7349. configurable: true
  7350. });
  7351. Object.defineProperty(Engine, "ALWAYS", {
  7352. get: function () {
  7353. return Engine._ALWAYS;
  7354. },
  7355. enumerable: true,
  7356. configurable: true
  7357. });
  7358. Object.defineProperty(Engine, "LESS", {
  7359. get: function () {
  7360. return Engine._LESS;
  7361. },
  7362. enumerable: true,
  7363. configurable: true
  7364. });
  7365. Object.defineProperty(Engine, "EQUAL", {
  7366. get: function () {
  7367. return Engine._EQUAL;
  7368. },
  7369. enumerable: true,
  7370. configurable: true
  7371. });
  7372. Object.defineProperty(Engine, "LEQUAL", {
  7373. get: function () {
  7374. return Engine._LEQUAL;
  7375. },
  7376. enumerable: true,
  7377. configurable: true
  7378. });
  7379. Object.defineProperty(Engine, "GREATER", {
  7380. get: function () {
  7381. return Engine._GREATER;
  7382. },
  7383. enumerable: true,
  7384. configurable: true
  7385. });
  7386. Object.defineProperty(Engine, "GEQUAL", {
  7387. get: function () {
  7388. return Engine._GEQUAL;
  7389. },
  7390. enumerable: true,
  7391. configurable: true
  7392. });
  7393. Object.defineProperty(Engine, "NOTEQUAL", {
  7394. get: function () {
  7395. return Engine._NOTEQUAL;
  7396. },
  7397. enumerable: true,
  7398. configurable: true
  7399. });
  7400. Object.defineProperty(Engine, "KEEP", {
  7401. get: function () {
  7402. return Engine._KEEP;
  7403. },
  7404. enumerable: true,
  7405. configurable: true
  7406. });
  7407. Object.defineProperty(Engine, "REPLACE", {
  7408. get: function () {
  7409. return Engine._REPLACE;
  7410. },
  7411. enumerable: true,
  7412. configurable: true
  7413. });
  7414. Object.defineProperty(Engine, "INCR", {
  7415. get: function () {
  7416. return Engine._INCR;
  7417. },
  7418. enumerable: true,
  7419. configurable: true
  7420. });
  7421. Object.defineProperty(Engine, "DECR", {
  7422. get: function () {
  7423. return Engine._DECR;
  7424. },
  7425. enumerable: true,
  7426. configurable: true
  7427. });
  7428. Object.defineProperty(Engine, "INVERT", {
  7429. get: function () {
  7430. return Engine._INVERT;
  7431. },
  7432. enumerable: true,
  7433. configurable: true
  7434. });
  7435. Object.defineProperty(Engine, "INCR_WRAP", {
  7436. get: function () {
  7437. return Engine._INCR_WRAP;
  7438. },
  7439. enumerable: true,
  7440. configurable: true
  7441. });
  7442. Object.defineProperty(Engine, "DECR_WRAP", {
  7443. get: function () {
  7444. return Engine._DECR_WRAP;
  7445. },
  7446. enumerable: true,
  7447. configurable: true
  7448. });
  7449. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  7450. get: function () {
  7451. return Engine._ALPHA_DISABLE;
  7452. },
  7453. enumerable: true,
  7454. configurable: true
  7455. });
  7456. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  7457. get: function () {
  7458. return Engine._ALPHA_ONEONE;
  7459. },
  7460. enumerable: true,
  7461. configurable: true
  7462. });
  7463. Object.defineProperty(Engine, "ALPHA_ADD", {
  7464. get: function () {
  7465. return Engine._ALPHA_ADD;
  7466. },
  7467. enumerable: true,
  7468. configurable: true
  7469. });
  7470. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  7471. get: function () {
  7472. return Engine._ALPHA_COMBINE;
  7473. },
  7474. enumerable: true,
  7475. configurable: true
  7476. });
  7477. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  7478. get: function () {
  7479. return Engine._ALPHA_SUBTRACT;
  7480. },
  7481. enumerable: true,
  7482. configurable: true
  7483. });
  7484. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  7485. get: function () {
  7486. return Engine._ALPHA_MULTIPLY;
  7487. },
  7488. enumerable: true,
  7489. configurable: true
  7490. });
  7491. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  7492. get: function () {
  7493. return Engine._ALPHA_MAXIMIZED;
  7494. },
  7495. enumerable: true,
  7496. configurable: true
  7497. });
  7498. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  7499. get: function () {
  7500. return Engine._ALPHA_PREMULTIPLIED;
  7501. },
  7502. enumerable: true,
  7503. configurable: true
  7504. });
  7505. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  7506. get: function () {
  7507. return Engine._DELAYLOADSTATE_NONE;
  7508. },
  7509. enumerable: true,
  7510. configurable: true
  7511. });
  7512. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  7513. get: function () {
  7514. return Engine._DELAYLOADSTATE_LOADED;
  7515. },
  7516. enumerable: true,
  7517. configurable: true
  7518. });
  7519. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  7520. get: function () {
  7521. return Engine._DELAYLOADSTATE_LOADING;
  7522. },
  7523. enumerable: true,
  7524. configurable: true
  7525. });
  7526. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  7527. get: function () {
  7528. return Engine._DELAYLOADSTATE_NOTLOADED;
  7529. },
  7530. enumerable: true,
  7531. configurable: true
  7532. });
  7533. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  7534. get: function () {
  7535. return Engine._TEXTUREFORMAT_ALPHA;
  7536. },
  7537. enumerable: true,
  7538. configurable: true
  7539. });
  7540. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  7541. get: function () {
  7542. return Engine._TEXTUREFORMAT_LUMINANCE;
  7543. },
  7544. enumerable: true,
  7545. configurable: true
  7546. });
  7547. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  7548. get: function () {
  7549. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  7550. },
  7551. enumerable: true,
  7552. configurable: true
  7553. });
  7554. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  7555. get: function () {
  7556. return Engine._TEXTUREFORMAT_RGB;
  7557. },
  7558. enumerable: true,
  7559. configurable: true
  7560. });
  7561. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  7562. get: function () {
  7563. return Engine._TEXTUREFORMAT_RGBA;
  7564. },
  7565. enumerable: true,
  7566. configurable: true
  7567. });
  7568. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  7569. get: function () {
  7570. return Engine._TEXTURETYPE_UNSIGNED_INT;
  7571. },
  7572. enumerable: true,
  7573. configurable: true
  7574. });
  7575. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  7576. get: function () {
  7577. return Engine._TEXTURETYPE_FLOAT;
  7578. },
  7579. enumerable: true,
  7580. configurable: true
  7581. });
  7582. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  7583. get: function () {
  7584. return Engine._TEXTURETYPE_HALF_FLOAT;
  7585. },
  7586. enumerable: true,
  7587. configurable: true
  7588. });
  7589. Object.defineProperty(Engine, "Version", {
  7590. get: function () {
  7591. return "3.0-alpha";
  7592. },
  7593. enumerable: true,
  7594. configurable: true
  7595. });
  7596. Object.defineProperty(Engine.prototype, "texturesSupported", {
  7597. get: function () {
  7598. return this._texturesSupported;
  7599. },
  7600. enumerable: true,
  7601. configurable: true
  7602. });
  7603. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  7604. get: function () {
  7605. return this._textureFormatInUse;
  7606. },
  7607. enumerable: true,
  7608. configurable: true
  7609. });
  7610. Object.defineProperty(Engine.prototype, "webGLVersion", {
  7611. get: function () {
  7612. return this._webGLVersion;
  7613. },
  7614. enumerable: true,
  7615. configurable: true
  7616. });
  7617. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  7618. /**
  7619. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  7620. */
  7621. get: function () {
  7622. return this._isStencilEnable;
  7623. },
  7624. enumerable: true,
  7625. configurable: true
  7626. });
  7627. Engine.prototype._prepareWorkingCanvas = function () {
  7628. if (this._workingCanvas) {
  7629. return;
  7630. }
  7631. this._workingCanvas = document.createElement("canvas");
  7632. this._workingContext = this._workingCanvas.getContext("2d");
  7633. };
  7634. Engine.prototype.resetTextureCache = function () {
  7635. for (var index = 0; index < this._maxTextureChannels; index++) {
  7636. this._activeTexturesCache[index] = null;
  7637. }
  7638. };
  7639. Engine.prototype.getGlInfo = function () {
  7640. return {
  7641. vendor: this._glVendor,
  7642. renderer: this._glRenderer,
  7643. version: this._glVersion
  7644. };
  7645. };
  7646. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  7647. if (useScreen === void 0) { useScreen = false; }
  7648. var viewport = camera.viewport;
  7649. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  7650. };
  7651. Engine.prototype.getRenderWidth = function (useScreen) {
  7652. if (useScreen === void 0) { useScreen = false; }
  7653. if (!useScreen && this._currentRenderTarget) {
  7654. return this._currentRenderTarget._width;
  7655. }
  7656. return this._renderingCanvas.width;
  7657. };
  7658. Engine.prototype.getRenderHeight = function (useScreen) {
  7659. if (useScreen === void 0) { useScreen = false; }
  7660. if (!useScreen && this._currentRenderTarget) {
  7661. return this._currentRenderTarget._height;
  7662. }
  7663. return this._renderingCanvas.height;
  7664. };
  7665. Engine.prototype.getRenderingCanvas = function () {
  7666. return this._renderingCanvas;
  7667. };
  7668. Engine.prototype.getRenderingCanvasClientRect = function () {
  7669. return this._renderingCanvas.getBoundingClientRect();
  7670. };
  7671. Engine.prototype.setHardwareScalingLevel = function (level) {
  7672. this._hardwareScalingLevel = level;
  7673. this.resize();
  7674. };
  7675. Engine.prototype.getHardwareScalingLevel = function () {
  7676. return this._hardwareScalingLevel;
  7677. };
  7678. Engine.prototype.getLoadedTexturesCache = function () {
  7679. return this._loadedTexturesCache;
  7680. };
  7681. Engine.prototype.getCaps = function () {
  7682. return this._caps;
  7683. };
  7684. Object.defineProperty(Engine.prototype, "drawCalls", {
  7685. get: function () {
  7686. return this._drawCalls.current;
  7687. },
  7688. enumerable: true,
  7689. configurable: true
  7690. });
  7691. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  7692. get: function () {
  7693. return this._drawCalls;
  7694. },
  7695. enumerable: true,
  7696. configurable: true
  7697. });
  7698. Engine.prototype.getDepthFunction = function () {
  7699. return this._depthCullingState.depthFunc;
  7700. };
  7701. Engine.prototype.setDepthFunction = function (depthFunc) {
  7702. this._depthCullingState.depthFunc = depthFunc;
  7703. };
  7704. Engine.prototype.setDepthFunctionToGreater = function () {
  7705. this._depthCullingState.depthFunc = this._gl.GREATER;
  7706. };
  7707. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  7708. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  7709. };
  7710. Engine.prototype.setDepthFunctionToLess = function () {
  7711. this._depthCullingState.depthFunc = this._gl.LESS;
  7712. };
  7713. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  7714. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  7715. };
  7716. Engine.prototype.getStencilBuffer = function () {
  7717. return this._stencilState.stencilTest;
  7718. };
  7719. Engine.prototype.setStencilBuffer = function (enable) {
  7720. this._stencilState.stencilTest = enable;
  7721. };
  7722. Engine.prototype.getStencilMask = function () {
  7723. return this._stencilState.stencilMask;
  7724. };
  7725. Engine.prototype.setStencilMask = function (mask) {
  7726. this._stencilState.stencilMask = mask;
  7727. };
  7728. Engine.prototype.getStencilFunction = function () {
  7729. return this._stencilState.stencilFunc;
  7730. };
  7731. Engine.prototype.getStencilFunctionReference = function () {
  7732. return this._stencilState.stencilFuncRef;
  7733. };
  7734. Engine.prototype.getStencilFunctionMask = function () {
  7735. return this._stencilState.stencilFuncMask;
  7736. };
  7737. Engine.prototype.setStencilFunction = function (stencilFunc) {
  7738. this._stencilState.stencilFunc = stencilFunc;
  7739. };
  7740. Engine.prototype.setStencilFunctionReference = function (reference) {
  7741. this._stencilState.stencilFuncRef = reference;
  7742. };
  7743. Engine.prototype.setStencilFunctionMask = function (mask) {
  7744. this._stencilState.stencilFuncMask = mask;
  7745. };
  7746. Engine.prototype.getStencilOperationFail = function () {
  7747. return this._stencilState.stencilOpStencilFail;
  7748. };
  7749. Engine.prototype.getStencilOperationDepthFail = function () {
  7750. return this._stencilState.stencilOpDepthFail;
  7751. };
  7752. Engine.prototype.getStencilOperationPass = function () {
  7753. return this._stencilState.stencilOpStencilDepthPass;
  7754. };
  7755. Engine.prototype.setStencilOperationFail = function (operation) {
  7756. this._stencilState.stencilOpStencilFail = operation;
  7757. };
  7758. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  7759. this._stencilState.stencilOpDepthFail = operation;
  7760. };
  7761. Engine.prototype.setStencilOperationPass = function (operation) {
  7762. this._stencilState.stencilOpStencilDepthPass = operation;
  7763. };
  7764. Engine.prototype.setDitheringState = function (value) {
  7765. if (value) {
  7766. this._gl.enable(this._gl.DITHER);
  7767. }
  7768. else {
  7769. this._gl.disable(this._gl.DITHER);
  7770. }
  7771. };
  7772. /**
  7773. * stop executing a render loop function and remove it from the execution array
  7774. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  7775. */
  7776. Engine.prototype.stopRenderLoop = function (renderFunction) {
  7777. if (!renderFunction) {
  7778. this._activeRenderLoops = [];
  7779. return;
  7780. }
  7781. var index = this._activeRenderLoops.indexOf(renderFunction);
  7782. if (index >= 0) {
  7783. this._activeRenderLoops.splice(index, 1);
  7784. }
  7785. };
  7786. Engine.prototype._renderLoop = function () {
  7787. var shouldRender = true;
  7788. if (!this.renderEvenInBackground && this._windowIsBackground) {
  7789. shouldRender = false;
  7790. }
  7791. if (shouldRender) {
  7792. // Start new frame
  7793. this.beginFrame();
  7794. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  7795. var renderFunction = this._activeRenderLoops[index];
  7796. renderFunction();
  7797. }
  7798. // Present
  7799. this.endFrame();
  7800. }
  7801. if (this._activeRenderLoops.length > 0) {
  7802. // Register new frame
  7803. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, this._vrDisplayEnabled);
  7804. }
  7805. else {
  7806. this._renderingQueueLaunched = false;
  7807. }
  7808. };
  7809. /**
  7810. * Register and execute a render loop. The engine can have more than one render function.
  7811. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  7812. * @example
  7813. * engine.runRenderLoop(function () {
  7814. * scene.render()
  7815. * })
  7816. */
  7817. Engine.prototype.runRenderLoop = function (renderFunction) {
  7818. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  7819. return;
  7820. }
  7821. this._activeRenderLoops.push(renderFunction);
  7822. if (!this._renderingQueueLaunched) {
  7823. this._renderingQueueLaunched = true;
  7824. this._bindedRenderFunction = this._renderLoop.bind(this);
  7825. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  7826. }
  7827. };
  7828. /**
  7829. * Toggle full screen mode.
  7830. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  7831. * @param {any} options - an options object to be sent to the requestFullscreen function
  7832. */
  7833. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  7834. if (this.isFullscreen) {
  7835. BABYLON.Tools.ExitFullscreen();
  7836. }
  7837. else {
  7838. this._pointerLockRequested = requestPointerLock;
  7839. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  7840. }
  7841. };
  7842. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  7843. if (stencil === void 0) { stencil = false; }
  7844. this.applyStates();
  7845. var mode = 0;
  7846. if (backBuffer && color) {
  7847. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  7848. mode |= this._gl.COLOR_BUFFER_BIT;
  7849. }
  7850. if (depth) {
  7851. this._gl.clearDepth(1.0);
  7852. mode |= this._gl.DEPTH_BUFFER_BIT;
  7853. }
  7854. if (stencil) {
  7855. this._gl.clearStencil(0);
  7856. mode |= this._gl.STENCIL_BUFFER_BIT;
  7857. }
  7858. this._gl.clear(mode);
  7859. };
  7860. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  7861. var gl = this._gl;
  7862. // Save state
  7863. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  7864. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  7865. // Change state
  7866. gl.enable(gl.SCISSOR_TEST);
  7867. gl.scissor(x, y, width, height);
  7868. // Clear
  7869. this.clear(clearColor, true, true, true);
  7870. // Restore state
  7871. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  7872. if (curScissor === true) {
  7873. gl.enable(gl.SCISSOR_TEST);
  7874. }
  7875. else {
  7876. gl.disable(gl.SCISSOR_TEST);
  7877. }
  7878. };
  7879. /**
  7880. * Set the WebGL's viewport
  7881. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  7882. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  7883. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  7884. */
  7885. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  7886. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this.getRenderWidth());
  7887. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this.getRenderHeight());
  7888. var x = viewport.x || 0;
  7889. var y = viewport.y || 0;
  7890. this._cachedViewport = viewport;
  7891. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  7892. };
  7893. /**
  7894. * Directly set the WebGL Viewport
  7895. * The x, y, width & height are directly passed to the WebGL call
  7896. * @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.
  7897. */
  7898. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  7899. var currentViewport = this._cachedViewport;
  7900. this._cachedViewport = null;
  7901. this._gl.viewport(x, y, width, height);
  7902. return currentViewport;
  7903. };
  7904. Engine.prototype.beginFrame = function () {
  7905. this._measureFps();
  7906. };
  7907. Engine.prototype.endFrame = function () {
  7908. //force a flush in case we are using a bad OS.
  7909. if (this._badOS) {
  7910. this.flushFramebuffer();
  7911. }
  7912. //submit frame to the vr device, if enabled
  7913. if (this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting) {
  7914. this._vrDisplayEnabled.submitFrame();
  7915. }
  7916. };
  7917. /**
  7918. * resize the view according to the canvas' size.
  7919. * @example
  7920. * window.addEventListener("resize", function () {
  7921. * engine.resize();
  7922. * });
  7923. */
  7924. Engine.prototype.resize = function () {
  7925. // We're not resizing the size of the canvas while in VR mode & presenting
  7926. if (!(this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting)) {
  7927. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  7928. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  7929. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  7930. }
  7931. };
  7932. /**
  7933. * force a specific size of the canvas
  7934. * @param {number} width - the new canvas' width
  7935. * @param {number} height - the new canvas' height
  7936. */
  7937. Engine.prototype.setSize = function (width, height) {
  7938. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  7939. return;
  7940. }
  7941. this._renderingCanvas.width = width;
  7942. this._renderingCanvas.height = height;
  7943. for (var index = 0; index < this.scenes.length; index++) {
  7944. var scene = this.scenes[index];
  7945. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  7946. var cam = scene.cameras[camIndex];
  7947. cam._currentRenderId = 0;
  7948. }
  7949. }
  7950. if (this.onResizeObservable.hasObservers) {
  7951. this.onResizeObservable.notifyObservers(this);
  7952. }
  7953. };
  7954. //WebVR functions
  7955. Engine.prototype.isVRDevicePresent = function (callback) {
  7956. this.getVRDevice(null, function (device) {
  7957. callback(device !== null);
  7958. });
  7959. };
  7960. Engine.prototype.getVRDevice = function (name, callback) {
  7961. if (!this.vrDisplaysPromise) {
  7962. callback(null);
  7963. return;
  7964. }
  7965. this.vrDisplaysPromise.then(function (devices) {
  7966. if (devices.length > 0) {
  7967. if (name) {
  7968. var found = devices.some(function (device) {
  7969. if (device.displayName === name) {
  7970. callback(device);
  7971. return true;
  7972. }
  7973. else {
  7974. return false;
  7975. }
  7976. });
  7977. if (!found) {
  7978. BABYLON.Tools.Warn("Display " + name + " was not found. Using " + devices[0].displayName);
  7979. callback(devices[0]);
  7980. }
  7981. }
  7982. else {
  7983. //choose the first one
  7984. callback(devices[0]);
  7985. }
  7986. }
  7987. else {
  7988. BABYLON.Tools.Error("No WebVR devices found!");
  7989. callback(null);
  7990. }
  7991. });
  7992. };
  7993. Engine.prototype.initWebVR = function () {
  7994. if (!this.vrDisplaysPromise) {
  7995. this._getVRDisplays();
  7996. }
  7997. };
  7998. Engine.prototype.enableVR = function (vrDevice) {
  7999. this._vrDisplayEnabled = vrDevice;
  8000. this._vrDisplayEnabled.requestPresent([{ source: this.getRenderingCanvas() }]).then(this._onVRFullScreenTriggered);
  8001. };
  8002. Engine.prototype.disableVR = function () {
  8003. if (this._vrDisplayEnabled) {
  8004. this._vrDisplayEnabled.exitPresent().then(this._onVRFullScreenTriggered);
  8005. }
  8006. };
  8007. Engine.prototype._getVRDisplays = function () {
  8008. var _this = this;
  8009. var getWebVRDevices = function (devices) {
  8010. var size = devices.length;
  8011. var i = 0;
  8012. _this._vrDisplays = devices.filter(function (device) {
  8013. return devices[i] instanceof VRDisplay;
  8014. });
  8015. return _this._vrDisplays;
  8016. };
  8017. //using a key due to typescript
  8018. if (navigator.getVRDisplays) {
  8019. this.vrDisplaysPromise = navigator.getVRDisplays().then(getWebVRDevices);
  8020. }
  8021. };
  8022. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight) {
  8023. this._currentRenderTarget = texture;
  8024. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  8025. var gl = this._gl;
  8026. if (texture.isCube) {
  8027. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  8028. }
  8029. gl.viewport(0, 0, requiredWidth || texture._width, requiredHeight || texture._height);
  8030. this.wipeCaches();
  8031. };
  8032. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  8033. if (this._currentFramebuffer !== framebuffer) {
  8034. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  8035. this._currentFramebuffer = framebuffer;
  8036. }
  8037. };
  8038. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  8039. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  8040. this._currentRenderTarget = null;
  8041. // If MSAA, we need to bitblt back to main texture
  8042. var gl = this._gl;
  8043. if (texture._MSAAFramebuffer) {
  8044. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  8045. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  8046. gl.blitFramebuffer(0, 0, texture._width, texture._height, 0, 0, texture._width, texture._height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  8047. }
  8048. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  8049. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  8050. gl.generateMipmap(gl.TEXTURE_2D);
  8051. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  8052. }
  8053. if (onBeforeUnbind) {
  8054. if (texture._MSAAFramebuffer) {
  8055. // Bind the correct framebuffer
  8056. this.bindUnboundFramebuffer(texture._framebuffer);
  8057. }
  8058. onBeforeUnbind();
  8059. }
  8060. this.bindUnboundFramebuffer(null);
  8061. };
  8062. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  8063. if (texture.generateMipMaps) {
  8064. var gl = this._gl;
  8065. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8066. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8067. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8068. }
  8069. };
  8070. Engine.prototype.flushFramebuffer = function () {
  8071. this._gl.flush();
  8072. };
  8073. Engine.prototype.restoreDefaultFramebuffer = function () {
  8074. this._currentRenderTarget = null;
  8075. this.bindUnboundFramebuffer(null);
  8076. this.setViewport(this._cachedViewport);
  8077. this.wipeCaches();
  8078. };
  8079. // UBOs
  8080. Engine.prototype.createUniformBuffer = function (elements) {
  8081. var ubo = this._gl.createBuffer();
  8082. this.bindUniformBuffer(ubo);
  8083. if (elements instanceof Float32Array) {
  8084. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  8085. }
  8086. else {
  8087. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  8088. }
  8089. this.bindUniformBuffer(null);
  8090. ubo.references = 1;
  8091. return ubo;
  8092. };
  8093. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  8094. var ubo = this._gl.createBuffer();
  8095. this.bindUniformBuffer(ubo);
  8096. if (elements instanceof Float32Array) {
  8097. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  8098. }
  8099. else {
  8100. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  8101. }
  8102. this.bindUniformBuffer(null);
  8103. ubo.references = 1;
  8104. return ubo;
  8105. };
  8106. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  8107. this.bindUniformBuffer(uniformBuffer);
  8108. if (offset === undefined) {
  8109. offset = 0;
  8110. }
  8111. if (count === undefined) {
  8112. if (elements instanceof Float32Array) {
  8113. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  8114. }
  8115. else {
  8116. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  8117. }
  8118. }
  8119. else {
  8120. if (elements instanceof Float32Array) {
  8121. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  8122. }
  8123. else {
  8124. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  8125. }
  8126. }
  8127. this.bindUniformBuffer(null);
  8128. };
  8129. // VBOs
  8130. Engine.prototype._resetVertexBufferBinding = function () {
  8131. this.bindArrayBuffer(null);
  8132. this._cachedVertexBuffers = null;
  8133. };
  8134. Engine.prototype.createVertexBuffer = function (vertices) {
  8135. var vbo = this._gl.createBuffer();
  8136. this.bindArrayBuffer(vbo);
  8137. if (vertices instanceof Float32Array) {
  8138. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  8139. }
  8140. else {
  8141. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  8142. }
  8143. this._resetVertexBufferBinding();
  8144. vbo.references = 1;
  8145. return vbo;
  8146. };
  8147. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  8148. var vbo = this._gl.createBuffer();
  8149. this.bindArrayBuffer(vbo);
  8150. if (vertices instanceof Float32Array) {
  8151. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  8152. }
  8153. else {
  8154. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  8155. }
  8156. this._resetVertexBufferBinding();
  8157. vbo.references = 1;
  8158. return vbo;
  8159. };
  8160. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  8161. this.bindArrayBuffer(vertexBuffer);
  8162. if (offset === undefined) {
  8163. offset = 0;
  8164. }
  8165. if (count === undefined) {
  8166. if (vertices instanceof Float32Array) {
  8167. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  8168. }
  8169. else {
  8170. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  8171. }
  8172. }
  8173. else {
  8174. if (vertices instanceof Float32Array) {
  8175. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  8176. }
  8177. else {
  8178. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  8179. }
  8180. }
  8181. this._resetVertexBufferBinding();
  8182. };
  8183. Engine.prototype._resetIndexBufferBinding = function () {
  8184. this.bindIndexBuffer(null);
  8185. this._cachedIndexBuffer = null;
  8186. };
  8187. Engine.prototype.createIndexBuffer = function (indices) {
  8188. var vbo = this._gl.createBuffer();
  8189. this.bindIndexBuffer(vbo);
  8190. // Check for 32 bits indices
  8191. var arrayBuffer;
  8192. var need32Bits = false;
  8193. if (indices instanceof Uint16Array) {
  8194. arrayBuffer = indices;
  8195. }
  8196. else {
  8197. //check 32 bit support
  8198. if (this._caps.uintIndices) {
  8199. if (indices instanceof Uint32Array) {
  8200. arrayBuffer = indices;
  8201. need32Bits = true;
  8202. }
  8203. else {
  8204. //number[] or Int32Array, check if 32 bit is necessary
  8205. for (var index = 0; index < indices.length; index++) {
  8206. if (indices[index] > 65535) {
  8207. need32Bits = true;
  8208. break;
  8209. }
  8210. }
  8211. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  8212. }
  8213. }
  8214. else {
  8215. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  8216. arrayBuffer = new Uint16Array(indices);
  8217. }
  8218. }
  8219. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  8220. this._resetIndexBufferBinding();
  8221. vbo.references = 1;
  8222. vbo.is32Bits = need32Bits;
  8223. return vbo;
  8224. };
  8225. Engine.prototype.bindArrayBuffer = function (buffer) {
  8226. if (!this._vaoRecordInProgress) {
  8227. this._unBindVertexArrayObject();
  8228. }
  8229. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  8230. };
  8231. Engine.prototype.bindUniformBuffer = function (buffer) {
  8232. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  8233. };
  8234. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  8235. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  8236. };
  8237. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  8238. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  8239. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  8240. };
  8241. ;
  8242. Engine.prototype.bindIndexBuffer = function (buffer) {
  8243. if (!this._vaoRecordInProgress) {
  8244. this._unBindVertexArrayObject();
  8245. }
  8246. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  8247. };
  8248. Engine.prototype.bindBuffer = function (buffer, target) {
  8249. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  8250. this._gl.bindBuffer(target, buffer);
  8251. this._currentBoundBuffer[target] = buffer;
  8252. }
  8253. };
  8254. Engine.prototype.updateArrayBuffer = function (data) {
  8255. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  8256. };
  8257. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  8258. var pointer = this._currentBufferPointers[indx];
  8259. var changed = false;
  8260. if (!pointer) {
  8261. changed = true;
  8262. this._currentBufferPointers[indx] = { indx: indx, size: size, type: type, normalized: normalized, stride: stride, offset: offset, buffer: buffer };
  8263. }
  8264. else {
  8265. if (pointer.buffer !== buffer) {
  8266. pointer.buffer = buffer;
  8267. changed = true;
  8268. }
  8269. if (pointer.size !== size) {
  8270. pointer.size = size;
  8271. changed = true;
  8272. }
  8273. if (pointer.type !== type) {
  8274. pointer.type = type;
  8275. changed = true;
  8276. }
  8277. if (pointer.normalized !== normalized) {
  8278. pointer.normalized = normalized;
  8279. changed = true;
  8280. }
  8281. if (pointer.stride !== stride) {
  8282. pointer.stride = stride;
  8283. changed = true;
  8284. }
  8285. if (pointer.offset !== offset) {
  8286. pointer.offset = offset;
  8287. changed = true;
  8288. }
  8289. }
  8290. if (changed || this._vaoRecordInProgress) {
  8291. this.bindArrayBuffer(buffer);
  8292. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  8293. }
  8294. };
  8295. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  8296. if (indexBuffer == null) {
  8297. return;
  8298. }
  8299. if (this._cachedIndexBuffer !== indexBuffer) {
  8300. this._cachedIndexBuffer = indexBuffer;
  8301. this.bindIndexBuffer(indexBuffer);
  8302. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  8303. }
  8304. };
  8305. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  8306. var attributes = effect.getAttributesNames();
  8307. if (!this._vaoRecordInProgress) {
  8308. this._unBindVertexArrayObject();
  8309. }
  8310. this.unbindAllAttributes();
  8311. for (var index = 0; index < attributes.length; index++) {
  8312. var order = effect.getAttributeLocation(index);
  8313. if (order >= 0) {
  8314. var vertexBuffer = vertexBuffers[attributes[index]];
  8315. if (!vertexBuffer) {
  8316. continue;
  8317. }
  8318. this._gl.enableVertexAttribArray(order);
  8319. if (!this._vaoRecordInProgress) {
  8320. this._vertexAttribArraysEnabled[order] = true;
  8321. }
  8322. var buffer = vertexBuffer.getBuffer();
  8323. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  8324. if (vertexBuffer.getIsInstanced()) {
  8325. this._gl.vertexAttribDivisor(order, 1);
  8326. if (!this._vaoRecordInProgress) {
  8327. this._currentInstanceLocations.push(order);
  8328. this._currentInstanceBuffers.push(buffer);
  8329. }
  8330. }
  8331. }
  8332. }
  8333. };
  8334. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  8335. var vao = this._gl.createVertexArray();
  8336. this._vaoRecordInProgress = true;
  8337. this._gl.bindVertexArray(vao);
  8338. this._mustWipeVertexAttributes = true;
  8339. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  8340. this.bindIndexBuffer(indexBuffer);
  8341. this._vaoRecordInProgress = false;
  8342. this._gl.bindVertexArray(null);
  8343. return vao;
  8344. };
  8345. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  8346. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  8347. this._cachedVertexArrayObject = vertexArrayObject;
  8348. this._gl.bindVertexArray(vertexArrayObject);
  8349. this._cachedVertexBuffers = null;
  8350. this._cachedIndexBuffer = null;
  8351. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  8352. this._mustWipeVertexAttributes = true;
  8353. }
  8354. };
  8355. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  8356. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  8357. this._cachedVertexBuffers = vertexBuffer;
  8358. this._cachedEffectForVertexBuffers = effect;
  8359. var attributesCount = effect.getAttributesCount();
  8360. this._unBindVertexArrayObject();
  8361. this.unbindAllAttributes();
  8362. var offset = 0;
  8363. for (var index = 0; index < attributesCount; index++) {
  8364. if (index < vertexDeclaration.length) {
  8365. var order = effect.getAttributeLocation(index);
  8366. if (order >= 0) {
  8367. this._gl.enableVertexAttribArray(order);
  8368. this._vertexAttribArraysEnabled[order] = true;
  8369. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  8370. }
  8371. offset += vertexDeclaration[index] * 4;
  8372. }
  8373. }
  8374. }
  8375. this._bindIndexBufferWithCache(indexBuffer);
  8376. };
  8377. Engine.prototype._unBindVertexArrayObject = function () {
  8378. if (!this._cachedVertexArrayObject) {
  8379. return;
  8380. }
  8381. this._cachedVertexArrayObject = null;
  8382. this._gl.bindVertexArray(null);
  8383. };
  8384. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  8385. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  8386. this._cachedVertexBuffers = vertexBuffers;
  8387. this._cachedEffectForVertexBuffers = effect;
  8388. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  8389. }
  8390. this._bindIndexBufferWithCache(indexBuffer);
  8391. };
  8392. Engine.prototype.unbindInstanceAttributes = function () {
  8393. var boundBuffer;
  8394. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  8395. var instancesBuffer = this._currentInstanceBuffers[i];
  8396. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  8397. boundBuffer = instancesBuffer;
  8398. this.bindArrayBuffer(instancesBuffer);
  8399. }
  8400. var offsetLocation = this._currentInstanceLocations[i];
  8401. this._gl.vertexAttribDivisor(offsetLocation, 0);
  8402. }
  8403. this._currentInstanceBuffers.length = 0;
  8404. this._currentInstanceLocations.length = 0;
  8405. };
  8406. Engine.prototype.releaseVertexArrayObject = function (vao) {
  8407. this._gl.deleteVertexArray(vao);
  8408. };
  8409. Engine.prototype._releaseBuffer = function (buffer) {
  8410. buffer.references--;
  8411. if (buffer.references === 0) {
  8412. this._gl.deleteBuffer(buffer);
  8413. return true;
  8414. }
  8415. return false;
  8416. };
  8417. Engine.prototype.createInstancesBuffer = function (capacity) {
  8418. var buffer = this._gl.createBuffer();
  8419. buffer.capacity = capacity;
  8420. this.bindArrayBuffer(buffer);
  8421. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  8422. return buffer;
  8423. };
  8424. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  8425. this._gl.deleteBuffer(buffer);
  8426. };
  8427. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  8428. this.bindArrayBuffer(instancesBuffer);
  8429. if (data) {
  8430. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  8431. }
  8432. if (offsetLocations[0].index !== undefined) {
  8433. var stride = 0;
  8434. for (var i = 0; i < offsetLocations.length; i++) {
  8435. var ai = offsetLocations[i];
  8436. stride += ai.attributeSize * 4;
  8437. }
  8438. for (var i = 0; i < offsetLocations.length; i++) {
  8439. var ai = offsetLocations[i];
  8440. if (!this._vertexAttribArraysEnabled[ai.index]) {
  8441. this._gl.enableVertexAttribArray(ai.index);
  8442. this._vertexAttribArraysEnabled[ai.index] = true;
  8443. }
  8444. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  8445. this._gl.vertexAttribDivisor(ai.index, 1);
  8446. this._currentInstanceLocations.push(ai.index);
  8447. this._currentInstanceBuffers.push(instancesBuffer);
  8448. }
  8449. }
  8450. else {
  8451. for (var index = 0; index < 4; index++) {
  8452. var offsetLocation = offsetLocations[index];
  8453. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  8454. this._gl.enableVertexAttribArray(offsetLocation);
  8455. this._vertexAttribArraysEnabled[offsetLocation] = true;
  8456. }
  8457. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  8458. this._gl.vertexAttribDivisor(offsetLocation, 1);
  8459. this._currentInstanceLocations.push(offsetLocation);
  8460. this._currentInstanceBuffers.push(instancesBuffer);
  8461. }
  8462. }
  8463. };
  8464. Engine.prototype.applyStates = function () {
  8465. this._depthCullingState.apply(this._gl);
  8466. this._stencilState.apply(this._gl);
  8467. this._alphaState.apply(this._gl);
  8468. };
  8469. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  8470. // Apply states
  8471. this.applyStates();
  8472. this._drawCalls.addCount(1, false);
  8473. // Render
  8474. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  8475. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  8476. if (instancesCount) {
  8477. this._gl.drawElementsInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  8478. return;
  8479. }
  8480. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  8481. };
  8482. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  8483. // Apply states
  8484. this.applyStates();
  8485. this._drawCalls.addCount(1, false);
  8486. if (instancesCount) {
  8487. this._gl.drawArraysInstanced(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  8488. return;
  8489. }
  8490. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  8491. };
  8492. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  8493. // Apply states
  8494. this.applyStates();
  8495. this._drawCalls.addCount(1, false);
  8496. if (instancesCount) {
  8497. this._gl.drawArraysInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  8498. return;
  8499. }
  8500. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  8501. };
  8502. // Shaders
  8503. Engine.prototype._releaseEffect = function (effect) {
  8504. if (this._compiledEffects[effect._key]) {
  8505. delete this._compiledEffects[effect._key];
  8506. if (effect.getProgram()) {
  8507. this._gl.deleteProgram(effect.getProgram());
  8508. }
  8509. }
  8510. };
  8511. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  8512. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  8513. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  8514. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  8515. if (this._compiledEffects[name]) {
  8516. return this._compiledEffects[name];
  8517. }
  8518. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  8519. effect._key = name;
  8520. this._compiledEffects[name] = effect;
  8521. return effect;
  8522. };
  8523. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  8524. if (uniformsNames === void 0) { uniformsNames = []; }
  8525. if (samplers === void 0) { samplers = []; }
  8526. if (defines === void 0) { defines = ""; }
  8527. return this.createEffect({
  8528. vertex: "particles",
  8529. fragmentElement: fragmentName
  8530. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  8531. };
  8532. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  8533. context = context || this._gl;
  8534. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  8535. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  8536. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  8537. var shaderProgram = context.createProgram();
  8538. context.attachShader(shaderProgram, vertexShader);
  8539. context.attachShader(shaderProgram, fragmentShader);
  8540. context.linkProgram(shaderProgram);
  8541. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  8542. if (!linked) {
  8543. var error = context.getProgramInfoLog(shaderProgram);
  8544. if (error) {
  8545. throw new Error(error);
  8546. }
  8547. }
  8548. context.deleteShader(vertexShader);
  8549. context.deleteShader(fragmentShader);
  8550. return shaderProgram;
  8551. };
  8552. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  8553. var results = [];
  8554. for (var index = 0; index < uniformsNames.length; index++) {
  8555. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  8556. }
  8557. return results;
  8558. };
  8559. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  8560. var results = [];
  8561. for (var index = 0; index < attributesNames.length; index++) {
  8562. try {
  8563. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  8564. }
  8565. catch (e) {
  8566. results.push(-1);
  8567. }
  8568. }
  8569. return results;
  8570. };
  8571. Engine.prototype.enableEffect = function (effect) {
  8572. // Use program
  8573. this.setProgram(effect.getProgram());
  8574. this._currentEffect = effect;
  8575. if (effect.onBind) {
  8576. effect.onBind(effect);
  8577. }
  8578. };
  8579. Engine.prototype.setIntArray = function (uniform, array) {
  8580. if (!uniform)
  8581. return;
  8582. this._gl.uniform1iv(uniform, array);
  8583. };
  8584. Engine.prototype.setIntArray2 = function (uniform, array) {
  8585. if (!uniform || array.length % 2 !== 0)
  8586. return;
  8587. this._gl.uniform2iv(uniform, array);
  8588. };
  8589. Engine.prototype.setIntArray3 = function (uniform, array) {
  8590. if (!uniform || array.length % 3 !== 0)
  8591. return;
  8592. this._gl.uniform3iv(uniform, array);
  8593. };
  8594. Engine.prototype.setIntArray4 = function (uniform, array) {
  8595. if (!uniform || array.length % 4 !== 0)
  8596. return;
  8597. this._gl.uniform4iv(uniform, array);
  8598. };
  8599. Engine.prototype.setFloatArray = function (uniform, array) {
  8600. if (!uniform)
  8601. return;
  8602. this._gl.uniform1fv(uniform, array);
  8603. };
  8604. Engine.prototype.setFloatArray2 = function (uniform, array) {
  8605. if (!uniform || array.length % 2 !== 0)
  8606. return;
  8607. this._gl.uniform2fv(uniform, array);
  8608. };
  8609. Engine.prototype.setFloatArray3 = function (uniform, array) {
  8610. if (!uniform || array.length % 3 !== 0)
  8611. return;
  8612. this._gl.uniform3fv(uniform, array);
  8613. };
  8614. Engine.prototype.setFloatArray4 = function (uniform, array) {
  8615. if (!uniform || array.length % 4 !== 0)
  8616. return;
  8617. this._gl.uniform4fv(uniform, array);
  8618. };
  8619. Engine.prototype.setArray = function (uniform, array) {
  8620. if (!uniform)
  8621. return;
  8622. this._gl.uniform1fv(uniform, array);
  8623. };
  8624. Engine.prototype.setArray2 = function (uniform, array) {
  8625. if (!uniform || array.length % 2 !== 0)
  8626. return;
  8627. this._gl.uniform2fv(uniform, array);
  8628. };
  8629. Engine.prototype.setArray3 = function (uniform, array) {
  8630. if (!uniform || array.length % 3 !== 0)
  8631. return;
  8632. this._gl.uniform3fv(uniform, array);
  8633. };
  8634. Engine.prototype.setArray4 = function (uniform, array) {
  8635. if (!uniform || array.length % 4 !== 0)
  8636. return;
  8637. this._gl.uniform4fv(uniform, array);
  8638. };
  8639. Engine.prototype.setMatrices = function (uniform, matrices) {
  8640. if (!uniform)
  8641. return;
  8642. this._gl.uniformMatrix4fv(uniform, false, matrices);
  8643. };
  8644. Engine.prototype.setMatrix = function (uniform, matrix) {
  8645. if (!uniform)
  8646. return;
  8647. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  8648. };
  8649. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  8650. if (!uniform)
  8651. return;
  8652. this._gl.uniformMatrix3fv(uniform, false, matrix);
  8653. };
  8654. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  8655. if (!uniform)
  8656. return;
  8657. this._gl.uniformMatrix2fv(uniform, false, matrix);
  8658. };
  8659. Engine.prototype.setFloat = function (uniform, value) {
  8660. if (!uniform)
  8661. return;
  8662. this._gl.uniform1f(uniform, value);
  8663. };
  8664. Engine.prototype.setFloat2 = function (uniform, x, y) {
  8665. if (!uniform)
  8666. return;
  8667. this._gl.uniform2f(uniform, x, y);
  8668. };
  8669. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  8670. if (!uniform)
  8671. return;
  8672. this._gl.uniform3f(uniform, x, y, z);
  8673. };
  8674. Engine.prototype.setBool = function (uniform, bool) {
  8675. if (!uniform)
  8676. return;
  8677. this._gl.uniform1i(uniform, bool);
  8678. };
  8679. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  8680. if (!uniform)
  8681. return;
  8682. this._gl.uniform4f(uniform, x, y, z, w);
  8683. };
  8684. Engine.prototype.setColor3 = function (uniform, color3) {
  8685. if (!uniform)
  8686. return;
  8687. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  8688. };
  8689. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  8690. if (!uniform)
  8691. return;
  8692. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  8693. };
  8694. // States
  8695. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  8696. if (zOffset === void 0) { zOffset = 0; }
  8697. if (reverseSide === void 0) { reverseSide = false; }
  8698. // Culling
  8699. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  8700. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  8701. var cullFace = this.cullBackFaces ? showSide : hideSide;
  8702. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  8703. if (culling) {
  8704. this._depthCullingState.cullFace = cullFace;
  8705. this._depthCullingState.cull = true;
  8706. }
  8707. else {
  8708. this._depthCullingState.cull = false;
  8709. }
  8710. }
  8711. // Z offset
  8712. this._depthCullingState.zOffset = zOffset;
  8713. };
  8714. Engine.prototype.setDepthBuffer = function (enable) {
  8715. this._depthCullingState.depthTest = enable;
  8716. };
  8717. Engine.prototype.getDepthWrite = function () {
  8718. return this._depthCullingState.depthMask;
  8719. };
  8720. Engine.prototype.setDepthWrite = function (enable) {
  8721. this._depthCullingState.depthMask = enable;
  8722. };
  8723. Engine.prototype.setColorWrite = function (enable) {
  8724. this._gl.colorMask(enable, enable, enable, enable);
  8725. };
  8726. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  8727. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  8728. if (this._alphaMode === mode) {
  8729. return;
  8730. }
  8731. switch (mode) {
  8732. case Engine.ALPHA_DISABLE:
  8733. this._alphaState.alphaBlend = false;
  8734. break;
  8735. case Engine.ALPHA_PREMULTIPLIED:
  8736. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  8737. this._alphaState.alphaBlend = true;
  8738. break;
  8739. case Engine.ALPHA_COMBINE:
  8740. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  8741. this._alphaState.alphaBlend = true;
  8742. break;
  8743. case Engine.ALPHA_ONEONE:
  8744. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  8745. this._alphaState.alphaBlend = true;
  8746. break;
  8747. case Engine.ALPHA_ADD:
  8748. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  8749. this._alphaState.alphaBlend = true;
  8750. break;
  8751. case Engine.ALPHA_SUBTRACT:
  8752. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  8753. this._alphaState.alphaBlend = true;
  8754. break;
  8755. case Engine.ALPHA_MULTIPLY:
  8756. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  8757. this._alphaState.alphaBlend = true;
  8758. break;
  8759. case Engine.ALPHA_MAXIMIZED:
  8760. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  8761. this._alphaState.alphaBlend = true;
  8762. break;
  8763. }
  8764. if (!noDepthWriteChange) {
  8765. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  8766. }
  8767. this._alphaMode = mode;
  8768. };
  8769. Engine.prototype.getAlphaMode = function () {
  8770. return this._alphaMode;
  8771. };
  8772. Engine.prototype.setAlphaTesting = function (enable) {
  8773. this._alphaTest = enable;
  8774. };
  8775. Engine.prototype.getAlphaTesting = function () {
  8776. return !!this._alphaTest;
  8777. };
  8778. // Textures
  8779. Engine.prototype.wipeCaches = function () {
  8780. if (this.preventCacheWipeBetweenFrames) {
  8781. return;
  8782. }
  8783. this.resetTextureCache();
  8784. this._currentEffect = null;
  8785. this._stencilState.reset();
  8786. this._depthCullingState.reset();
  8787. this.setDepthFunctionToLessOrEqual();
  8788. this._alphaState.reset();
  8789. this._cachedVertexBuffers = null;
  8790. this._cachedIndexBuffer = null;
  8791. this._cachedEffectForVertexBuffers = null;
  8792. this._unBindVertexArrayObject();
  8793. this.bindIndexBuffer(null);
  8794. this.bindArrayBuffer(null);
  8795. };
  8796. /**
  8797. * Set the compressed texture format to use, based on the formats you have, and the formats
  8798. * supported by the hardware / browser.
  8799. *
  8800. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  8801. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  8802. * to API arguments needed to compressed textures. This puts the burden on the container
  8803. * generator to house the arcane code for determining these for current & future formats.
  8804. *
  8805. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  8806. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  8807. *
  8808. * Note: The result of this call is not taken into account when a texture is base64.
  8809. *
  8810. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  8811. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  8812. *
  8813. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  8814. * @returns The extension selected.
  8815. */
  8816. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  8817. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  8818. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  8819. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  8820. return this._textureFormatInUse = this._texturesSupported[i];
  8821. }
  8822. }
  8823. }
  8824. // actively set format to nothing, to allow this to be called more than once
  8825. // and possibly fail the 2nd time
  8826. return this._textureFormatInUse = null;
  8827. };
  8828. /**
  8829. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  8830. * @param {string} urlArg- This contains one of the following:
  8831. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  8832. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  8833. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  8834. *
  8835. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  8836. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  8837. * @param {Scene} scene- Needed for loading to the correct scene.
  8838. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  8839. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  8840. * @param {callback} onError- Optional callback to be called upon failure.
  8841. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  8842. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  8843. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  8844. *
  8845. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  8846. */
  8847. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  8848. var _this = this;
  8849. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  8850. if (onLoad === void 0) { onLoad = null; }
  8851. if (onError === void 0) { onError = null; }
  8852. if (buffer === void 0) { buffer = null; }
  8853. var texture = fallBack ? fallBack : this._gl.createTexture();
  8854. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  8855. var fromData = url.substr(0, 5) === "data:";
  8856. var isBase64 = fromData && url.indexOf("base64") !== -1;
  8857. // establish the file extension, if possible
  8858. var lastDot = url.lastIndexOf('.');
  8859. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  8860. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  8861. if (isDDS) {
  8862. BABYLON.Tools.Warn("DDS files deprecated since 3.0, use KTX files");
  8863. }
  8864. var isTGA = (extension === ".tga");
  8865. // determine if a ktx file should be substituted
  8866. var isKTX = false;
  8867. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  8868. url = url.substring(0, lastDot) + this._textureFormatInUse;
  8869. isKTX = true;
  8870. }
  8871. scene._addPendingData(texture);
  8872. texture.url = url;
  8873. texture.noMipmap = noMipmap;
  8874. texture.references = 1;
  8875. texture.samplingMode = samplingMode;
  8876. texture.onLoadedCallbacks = [];
  8877. if (onLoad) {
  8878. texture.onLoadedCallbacks.push(onLoad);
  8879. }
  8880. if (!fallBack)
  8881. this._loadedTexturesCache.push(texture);
  8882. var onerror = function () {
  8883. scene._removePendingData(texture);
  8884. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  8885. if (isKTX) {
  8886. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  8887. }
  8888. else if (onError) {
  8889. onError();
  8890. }
  8891. };
  8892. var callback;
  8893. // processing for non-image formats
  8894. if (isKTX || isTGA || isDDS) {
  8895. if (isKTX) {
  8896. callback = function (data) {
  8897. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 1);
  8898. prepareWebGLTexture(texture, _this._gl, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  8899. ktx.uploadLevels(_this._gl, !noMipmap);
  8900. }, samplingMode);
  8901. };
  8902. }
  8903. else if (isTGA) {
  8904. callback = function (arrayBuffer) {
  8905. var data = new Uint8Array(arrayBuffer);
  8906. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  8907. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  8908. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  8909. }, samplingMode);
  8910. };
  8911. }
  8912. else if (isDDS) {
  8913. callback = function (data) {
  8914. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  8915. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  8916. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  8917. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  8918. }, samplingMode);
  8919. };
  8920. }
  8921. if (!buffer) {
  8922. BABYLON.Tools.LoadFile(url, function (data) {
  8923. callback(data);
  8924. }, null, scene.database, true, onerror);
  8925. }
  8926. else {
  8927. callback(buffer);
  8928. }
  8929. // image format processing
  8930. }
  8931. else {
  8932. var onload = function (img) {
  8933. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  8934. var isPot = (img.width === potWidth && img.height === potHeight);
  8935. if (!isPot) {
  8936. _this._prepareWorkingCanvas();
  8937. _this._workingCanvas.width = potWidth;
  8938. _this._workingCanvas.height = potHeight;
  8939. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  8940. _this._workingContext.imageSmoothingEnabled = false;
  8941. _this._workingContext.mozImageSmoothingEnabled = false;
  8942. _this._workingContext.oImageSmoothingEnabled = false;
  8943. _this._workingContext.webkitImageSmoothingEnabled = false;
  8944. _this._workingContext.msImageSmoothingEnabled = false;
  8945. }
  8946. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  8947. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  8948. _this._workingContext.imageSmoothingEnabled = true;
  8949. _this._workingContext.mozImageSmoothingEnabled = true;
  8950. _this._workingContext.oImageSmoothingEnabled = true;
  8951. _this._workingContext.webkitImageSmoothingEnabled = true;
  8952. _this._workingContext.msImageSmoothingEnabled = true;
  8953. }
  8954. }
  8955. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? _this._gl.RGB : _this._gl.RGBA);
  8956. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  8957. }, samplingMode);
  8958. };
  8959. if (!fromData || isBase64)
  8960. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  8961. else if (buffer instanceof Array || typeof buffer === "string")
  8962. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  8963. else
  8964. onload(buffer);
  8965. }
  8966. return texture;
  8967. };
  8968. Engine.prototype._getInternalFormat = function (format) {
  8969. var internalFormat = this._gl.RGBA;
  8970. switch (format) {
  8971. case Engine.TEXTUREFORMAT_ALPHA:
  8972. internalFormat = this._gl.ALPHA;
  8973. break;
  8974. case Engine.TEXTUREFORMAT_LUMINANCE:
  8975. internalFormat = this._gl.LUMINANCE;
  8976. break;
  8977. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  8978. internalFormat = this._gl.LUMINANCE_ALPHA;
  8979. break;
  8980. case Engine.TEXTUREFORMAT_RGB:
  8981. internalFormat = this._gl.RGB;
  8982. break;
  8983. case Engine.TEXTUREFORMAT_RGBA:
  8984. internalFormat = this._gl.RGBA;
  8985. break;
  8986. }
  8987. return internalFormat;
  8988. };
  8989. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  8990. if (compression === void 0) { compression = null; }
  8991. var internalFormat = this._getInternalFormat(format);
  8992. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8993. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  8994. if (texture._width % 4 !== 0) {
  8995. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  8996. }
  8997. if (compression) {
  8998. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  8999. }
  9000. else {
  9001. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  9002. }
  9003. if (texture.generateMipMaps) {
  9004. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9005. }
  9006. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9007. this.resetTextureCache();
  9008. texture.isReady = true;
  9009. };
  9010. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  9011. if (compression === void 0) { compression = null; }
  9012. var texture = this._gl.createTexture();
  9013. texture._baseWidth = width;
  9014. texture._baseHeight = height;
  9015. texture._width = width;
  9016. texture._height = height;
  9017. texture.references = 1;
  9018. this.updateRawTexture(texture, data, format, invertY, compression);
  9019. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9020. // Filters
  9021. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  9022. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9023. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9024. if (generateMipMaps) {
  9025. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9026. }
  9027. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9028. texture.samplingMode = samplingMode;
  9029. this._loadedTexturesCache.push(texture);
  9030. return texture;
  9031. };
  9032. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  9033. var texture = this._gl.createTexture();
  9034. texture._baseWidth = width;
  9035. texture._baseHeight = height;
  9036. if (generateMipMaps) {
  9037. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  9038. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  9039. }
  9040. this.resetTextureCache();
  9041. texture._width = width;
  9042. texture._height = height;
  9043. texture.isReady = false;
  9044. texture.generateMipMaps = generateMipMaps;
  9045. texture.references = 1;
  9046. texture.samplingMode = samplingMode;
  9047. this.updateTextureSamplingMode(samplingMode, texture);
  9048. this._loadedTexturesCache.push(texture);
  9049. return texture;
  9050. };
  9051. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  9052. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  9053. if (texture.isCube) {
  9054. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  9055. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9056. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9057. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  9058. }
  9059. else {
  9060. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9061. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9062. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9063. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9064. }
  9065. texture.samplingMode = samplingMode;
  9066. };
  9067. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  9068. if (premulAlpha === void 0) { premulAlpha = false; }
  9069. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9070. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  9071. if (premulAlpha) {
  9072. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  9073. }
  9074. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  9075. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  9076. if (texture.generateMipMaps) {
  9077. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9078. }
  9079. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9080. if (premulAlpha) {
  9081. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  9082. }
  9083. this.resetTextureCache();
  9084. texture.isReady = true;
  9085. };
  9086. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  9087. if (texture._isDisabled) {
  9088. return;
  9089. }
  9090. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9091. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  9092. try {
  9093. // Testing video texture support
  9094. if (this._videoTextureSupported === undefined) {
  9095. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  9096. if (this._gl.getError() !== 0) {
  9097. this._videoTextureSupported = false;
  9098. }
  9099. else {
  9100. this._videoTextureSupported = true;
  9101. }
  9102. }
  9103. // Copy video through the current working canvas if video texture is not supported
  9104. if (!this._videoTextureSupported) {
  9105. if (!texture._workingCanvas) {
  9106. texture._workingCanvas = document.createElement("canvas");
  9107. texture._workingContext = texture._workingCanvas.getContext("2d");
  9108. texture._workingCanvas.width = texture._width;
  9109. texture._workingCanvas.height = texture._height;
  9110. }
  9111. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  9112. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  9113. }
  9114. else {
  9115. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  9116. }
  9117. if (texture.generateMipMaps) {
  9118. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9119. }
  9120. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9121. this.resetTextureCache();
  9122. texture.isReady = true;
  9123. }
  9124. catch (ex) {
  9125. // Something unexpected
  9126. // Let's disable the texture
  9127. texture._isDisabled = true;
  9128. }
  9129. };
  9130. Engine.prototype.createRenderTargetTexture = function (size, options) {
  9131. // old version had a "generateMipMaps" arg instead of options.
  9132. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  9133. // in the same way, generateDepthBuffer is defaulted to true
  9134. var generateMipMaps = false;
  9135. var generateDepthBuffer = true;
  9136. var generateStencilBuffer = false;
  9137. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9138. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9139. if (options !== undefined) {
  9140. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  9141. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9142. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  9143. type = options.type === undefined ? type : options.type;
  9144. if (options.samplingMode !== undefined) {
  9145. samplingMode = options.samplingMode;
  9146. }
  9147. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  9148. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  9149. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9150. }
  9151. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  9152. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  9153. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9154. }
  9155. }
  9156. var gl = this._gl;
  9157. var texture = gl.createTexture();
  9158. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  9159. var width = size.width || size;
  9160. var height = size.height || size;
  9161. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9162. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  9163. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9164. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  9165. }
  9166. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  9167. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  9168. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9169. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9170. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  9171. // Create the framebuffer
  9172. var framebuffer = gl.createFramebuffer();
  9173. this.bindUnboundFramebuffer(framebuffer);
  9174. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  9175. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  9176. if (generateMipMaps) {
  9177. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9178. }
  9179. // Unbind
  9180. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9181. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9182. this.bindUnboundFramebuffer(null);
  9183. texture._framebuffer = framebuffer;
  9184. texture._baseWidth = width;
  9185. texture._baseHeight = height;
  9186. texture._width = width;
  9187. texture._height = height;
  9188. texture.isReady = true;
  9189. texture.samples = 1;
  9190. texture.generateMipMaps = generateMipMaps;
  9191. texture.references = 1;
  9192. texture.samplingMode = samplingMode;
  9193. texture.type = type;
  9194. texture._generateDepthBuffer = generateDepthBuffer;
  9195. texture._generateStencilBuffer = generateStencilBuffer;
  9196. this.resetTextureCache();
  9197. this._loadedTexturesCache.push(texture);
  9198. return texture;
  9199. };
  9200. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  9201. if (samples === void 0) { samples = 1; }
  9202. var depthStencilBuffer = null;
  9203. var gl = this._gl;
  9204. // Create the depth/stencil buffer
  9205. if (generateStencilBuffer) {
  9206. depthStencilBuffer = gl.createRenderbuffer();
  9207. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  9208. if (samples > 1) {
  9209. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_STENCIL, width, height);
  9210. }
  9211. else {
  9212. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  9213. }
  9214. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  9215. }
  9216. else if (generateDepthBuffer) {
  9217. depthStencilBuffer = gl.createRenderbuffer();
  9218. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  9219. if (samples > 1) {
  9220. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  9221. }
  9222. else {
  9223. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  9224. }
  9225. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  9226. }
  9227. return depthStencilBuffer;
  9228. };
  9229. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  9230. if (this.webGLVersion < 2) {
  9231. return 1;
  9232. }
  9233. if (texture.samples === samples) {
  9234. return samples;
  9235. }
  9236. var gl = this._gl;
  9237. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  9238. // Dispose previous render buffers
  9239. if (texture._depthStencilBuffer) {
  9240. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  9241. }
  9242. if (texture._MSAAFramebuffer) {
  9243. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  9244. }
  9245. if (texture._MSAARenderBuffer) {
  9246. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  9247. }
  9248. if (samples > 1) {
  9249. texture._MSAAFramebuffer = gl.createFramebuffer();
  9250. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  9251. var colorRenderbuffer = gl.createRenderbuffer();
  9252. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  9253. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.RGBA8, texture._width, texture._height);
  9254. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  9255. texture._MSAARenderBuffer = colorRenderbuffer;
  9256. }
  9257. else {
  9258. this.bindUnboundFramebuffer(texture._framebuffer);
  9259. }
  9260. texture.samples = samples;
  9261. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture._width, texture._height, samples);
  9262. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9263. this.bindUnboundFramebuffer(null);
  9264. return samples;
  9265. };
  9266. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  9267. var gl = this._gl;
  9268. var texture = gl.createTexture();
  9269. var generateMipMaps = true;
  9270. var generateDepthBuffer = true;
  9271. var generateStencilBuffer = false;
  9272. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9273. if (options !== undefined) {
  9274. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  9275. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9276. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  9277. if (options.samplingMode !== undefined) {
  9278. samplingMode = options.samplingMode;
  9279. }
  9280. }
  9281. texture.isCube = true;
  9282. texture.references = 1;
  9283. texture.generateMipMaps = generateMipMaps;
  9284. texture.references = 1;
  9285. texture.samples = 1;
  9286. texture.samplingMode = samplingMode;
  9287. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9288. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9289. for (var face = 0; face < 6; face++) {
  9290. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  9291. }
  9292. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  9293. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  9294. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9295. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9296. // Create the framebuffer
  9297. var framebuffer = gl.createFramebuffer();
  9298. this.bindUnboundFramebuffer(framebuffer);
  9299. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  9300. // Mipmaps
  9301. if (texture.generateMipMaps) {
  9302. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9303. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9304. }
  9305. // Unbind
  9306. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9307. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9308. this.bindUnboundFramebuffer(null);
  9309. texture._framebuffer = framebuffer;
  9310. texture._width = size;
  9311. texture._height = size;
  9312. texture.isReady = true;
  9313. this.resetTextureCache();
  9314. this._loadedTexturesCache.push(texture);
  9315. return texture;
  9316. };
  9317. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format) {
  9318. var _this = this;
  9319. if (onLoad === void 0) { onLoad = null; }
  9320. if (onError === void 0) { onError = null; }
  9321. var gl = this._gl;
  9322. var texture = gl.createTexture();
  9323. texture.isCube = true;
  9324. texture.url = rootUrl;
  9325. texture.references = 1;
  9326. texture.onLoadedCallbacks = [];
  9327. var isKTX = false;
  9328. var lastDot = rootUrl.lastIndexOf('.');
  9329. var extension = rootUrl.substring(lastDot).toLowerCase();
  9330. if (this._textureFormatInUse) {
  9331. extension = this._textureFormatInUse;
  9332. rootUrl = rootUrl.substring(0, lastDot) + this._textureFormatInUse;
  9333. isKTX = true;
  9334. }
  9335. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  9336. if (isDDS) {
  9337. BABYLON.Tools.Warn("DDS files deprecated since 3.0, use KTX files");
  9338. }
  9339. if (isKTX) {
  9340. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  9341. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 6);
  9342. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  9343. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9344. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  9345. ktx.uploadLevels(_this._gl, !noMipmap);
  9346. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9347. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  9348. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9349. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9350. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9351. _this.resetTextureCache();
  9352. texture._width = ktx.pixelWidth;
  9353. texture._height = ktx.pixelHeight;
  9354. texture.isReady = true;
  9355. }, null, null, true, onError);
  9356. }
  9357. else if (isDDS) {
  9358. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  9359. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  9360. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  9361. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9362. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  9363. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  9364. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  9365. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9366. }
  9367. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9368. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  9369. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9370. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9371. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9372. _this.resetTextureCache();
  9373. texture._width = info.width;
  9374. texture._height = info.height;
  9375. texture.isReady = true;
  9376. }, null, null, true, onError);
  9377. }
  9378. else {
  9379. cascadeLoad(rootUrl, scene, function (imgs) {
  9380. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  9381. var height = width;
  9382. _this._prepareWorkingCanvas();
  9383. _this._workingCanvas.width = width;
  9384. _this._workingCanvas.height = height;
  9385. var faces = [
  9386. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  9387. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  9388. ];
  9389. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9390. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  9391. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  9392. for (var index = 0; index < faces.length; index++) {
  9393. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  9394. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  9395. }
  9396. if (!noMipmap) {
  9397. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9398. }
  9399. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9400. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  9401. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9402. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9403. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9404. _this.resetTextureCache();
  9405. texture._width = width;
  9406. texture._height = height;
  9407. texture.isReady = true;
  9408. texture.onLoadedCallbacks.forEach(function (callback) {
  9409. callback();
  9410. });
  9411. if (onLoad) {
  9412. onLoad();
  9413. }
  9414. }, files, onError);
  9415. }
  9416. this._loadedTexturesCache.push(texture);
  9417. return texture;
  9418. };
  9419. Engine.prototype.updateTextureSize = function (texture, width, height) {
  9420. texture._width = width;
  9421. texture._height = height;
  9422. texture._size = width * height;
  9423. texture._baseWidth = width;
  9424. texture._baseHeight = height;
  9425. };
  9426. Engine.prototype.createRawCubeTexture = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError) {
  9427. var _this = this;
  9428. if (onLoad === void 0) { onLoad = null; }
  9429. if (onError === void 0) { onError = null; }
  9430. var gl = this._gl;
  9431. var texture = gl.createTexture();
  9432. scene._addPendingData(texture);
  9433. texture.isCube = true;
  9434. texture.references = 1;
  9435. texture.url = url;
  9436. var textureType = gl.UNSIGNED_BYTE;
  9437. if (type === Engine.TEXTURETYPE_FLOAT) {
  9438. textureType = gl.FLOAT;
  9439. }
  9440. var internalFormat = this._getInternalFormat(format);
  9441. var needConversion = false;
  9442. if (internalFormat === gl.RGB) {
  9443. internalFormat = gl.RGBA;
  9444. needConversion = true;
  9445. }
  9446. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  9447. var width = size;
  9448. var height = width;
  9449. var isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  9450. texture._width = width;
  9451. texture._height = height;
  9452. var onerror = function () {
  9453. scene._removePendingData(texture);
  9454. if (onError) {
  9455. onError();
  9456. }
  9457. };
  9458. var internalCallback = function (data) {
  9459. var rgbeDataArrays = callback(data);
  9460. var facesIndex = [
  9461. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  9462. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  9463. ];
  9464. width = texture._width;
  9465. height = texture._height;
  9466. isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  9467. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9468. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  9469. if (mipmmapGenerator) {
  9470. var arrayTemp = [];
  9471. // Data are known to be in +X +Y +Z -X -Y -Z
  9472. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  9473. arrayTemp.push(rgbeDataArrays[0]); // +X
  9474. arrayTemp.push(rgbeDataArrays[3]); // -X
  9475. arrayTemp.push(rgbeDataArrays[1]); // +Y
  9476. arrayTemp.push(rgbeDataArrays[4]); // -Y
  9477. arrayTemp.push(rgbeDataArrays[2]); // +Z
  9478. arrayTemp.push(rgbeDataArrays[5]); // -Z
  9479. var mipData = mipmmapGenerator(arrayTemp);
  9480. // mipData is order in +X -X +Y -Y +Z -Z
  9481. var mipFaces = [0, 2, 4, 1, 3, 5];
  9482. for (var level = 0; level < mipData.length; level++) {
  9483. var mipSize = width >> level;
  9484. for (var mipIndex in mipFaces) {
  9485. var mipFaceData = mipData[level][mipFaces[mipIndex]];
  9486. if (needConversion) {
  9487. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  9488. }
  9489. gl.texImage2D(facesIndex[mipIndex], level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  9490. }
  9491. }
  9492. }
  9493. else {
  9494. // Data are known to be in +X +Y +Z -X -Y -Z
  9495. for (var index = 0; index < facesIndex.length; index++) {
  9496. var faceData = rgbeDataArrays[index];
  9497. if (needConversion) {
  9498. faceData = _this._convertRGBtoRGBATextureData(faceData, width, height, type);
  9499. }
  9500. gl.texImage2D(facesIndex[index], 0, internalSizedFomat, width, height, 0, internalFormat, textureType, faceData);
  9501. }
  9502. if (!noMipmap && isPot) {
  9503. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9504. }
  9505. else {
  9506. noMipmap = true;
  9507. }
  9508. }
  9509. if (textureType === gl.FLOAT && !_this._caps.textureFloatLinearFiltering) {
  9510. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  9511. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  9512. }
  9513. else if (textureType === Engine.HALF_FLOAT_OES && !_this._caps.textureHalfFloatLinearFiltering) {
  9514. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  9515. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  9516. }
  9517. else {
  9518. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9519. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  9520. }
  9521. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9522. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9523. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9524. texture.isReady = true;
  9525. _this.resetTextureCache();
  9526. scene._removePendingData(texture);
  9527. if (onLoad) {
  9528. onLoad();
  9529. }
  9530. };
  9531. BABYLON.Tools.LoadFile(url, function (data) {
  9532. internalCallback(data);
  9533. }, onerror, scene.database, true);
  9534. return texture;
  9535. };
  9536. ;
  9537. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  9538. // Create new RGBA data container.
  9539. var rgbaData;
  9540. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  9541. rgbaData = new Float32Array(width * height * 4);
  9542. }
  9543. else {
  9544. rgbaData = new Uint32Array(width * height * 4);
  9545. }
  9546. // Convert each pixel.
  9547. for (var x = 0; x < width; x++) {
  9548. for (var y = 0; y < height; y++) {
  9549. var index = (y * width + x) * 3;
  9550. var newIndex = (y * width + x) * 4;
  9551. // Map Old Value to new value.
  9552. rgbaData[newIndex + 0] = rgbData[index + 0];
  9553. rgbaData[newIndex + 1] = rgbData[index + 1];
  9554. rgbaData[newIndex + 2] = rgbData[index + 2];
  9555. // Add fully opaque alpha channel.
  9556. rgbaData[newIndex + 3] = 1;
  9557. }
  9558. }
  9559. return rgbaData;
  9560. };
  9561. Engine.prototype._releaseTexture = function (texture) {
  9562. var gl = this._gl;
  9563. if (texture._framebuffer) {
  9564. gl.deleteFramebuffer(texture._framebuffer);
  9565. }
  9566. if (texture._depthStencilBuffer) {
  9567. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  9568. }
  9569. if (texture._MSAAFramebuffer) {
  9570. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  9571. }
  9572. if (texture._MSAARenderBuffer) {
  9573. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  9574. }
  9575. gl.deleteTexture(texture);
  9576. // Unbind channels
  9577. this.unbindAllTextures();
  9578. var index = this._loadedTexturesCache.indexOf(texture);
  9579. if (index !== -1) {
  9580. this._loadedTexturesCache.splice(index, 1);
  9581. }
  9582. };
  9583. Engine.prototype.setProgram = function (program) {
  9584. if (this._currentProgram !== program) {
  9585. this._gl.useProgram(program);
  9586. this._currentProgram = program;
  9587. }
  9588. };
  9589. Engine.prototype.bindSamplers = function (effect) {
  9590. this.setProgram(effect.getProgram());
  9591. var samplers = effect.getSamplers();
  9592. for (var index = 0; index < samplers.length; index++) {
  9593. var uniform = effect.getUniform(samplers[index]);
  9594. this._gl.uniform1i(uniform, index);
  9595. }
  9596. this._currentEffect = null;
  9597. };
  9598. Engine.prototype.activateTexture = function (texture) {
  9599. if (this._activeTexture !== texture) {
  9600. this._gl.activeTexture(texture);
  9601. this._activeTexture = texture;
  9602. }
  9603. };
  9604. Engine.prototype._bindTextureDirectly = function (target, texture) {
  9605. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  9606. this._gl.bindTexture(target, texture);
  9607. this._activeTexturesCache[this._activeTexture] = texture;
  9608. }
  9609. };
  9610. Engine.prototype._bindTexture = function (channel, texture) {
  9611. if (channel < 0) {
  9612. return;
  9613. }
  9614. this.activateTexture(this._gl.TEXTURE0 + channel);
  9615. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9616. };
  9617. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  9618. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  9619. };
  9620. Engine.prototype.unbindAllTextures = function () {
  9621. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  9622. this.activateTexture(this._gl["TEXTURE" + channel]);
  9623. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9624. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  9625. }
  9626. };
  9627. Engine.prototype.setTexture = function (channel, uniform, texture) {
  9628. if (channel < 0) {
  9629. return;
  9630. }
  9631. this._gl.uniform1i(uniform, channel);
  9632. this._setTexture(channel, texture);
  9633. };
  9634. Engine.prototype._setTexture = function (channel, texture) {
  9635. // Not ready?
  9636. if (!texture || !texture.isReady()) {
  9637. if (this._activeTexturesCache[channel] != null) {
  9638. this.activateTexture(this._gl["TEXTURE" + channel]);
  9639. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9640. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  9641. }
  9642. return;
  9643. }
  9644. // Video
  9645. var alreadyActivated = false;
  9646. if (texture.video) {
  9647. this.activateTexture(this._gl["TEXTURE" + channel]);
  9648. alreadyActivated = true;
  9649. texture.update();
  9650. }
  9651. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  9652. texture.delayLoad();
  9653. return;
  9654. }
  9655. var internalTexture = texture.getInternalTexture();
  9656. if (this._activeTexturesCache[channel] === internalTexture) {
  9657. return;
  9658. }
  9659. if (!alreadyActivated) {
  9660. this.activateTexture(this._gl["TEXTURE" + channel]);
  9661. }
  9662. if (internalTexture.isCube) {
  9663. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  9664. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  9665. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  9666. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  9667. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  9668. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  9669. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  9670. }
  9671. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  9672. }
  9673. else {
  9674. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  9675. if (internalTexture._cachedWrapU !== texture.wrapU) {
  9676. internalTexture._cachedWrapU = texture.wrapU;
  9677. switch (texture.wrapU) {
  9678. case BABYLON.Texture.WRAP_ADDRESSMODE:
  9679. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  9680. break;
  9681. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  9682. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  9683. break;
  9684. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  9685. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  9686. break;
  9687. }
  9688. }
  9689. if (internalTexture._cachedWrapV !== texture.wrapV) {
  9690. internalTexture._cachedWrapV = texture.wrapV;
  9691. switch (texture.wrapV) {
  9692. case BABYLON.Texture.WRAP_ADDRESSMODE:
  9693. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  9694. break;
  9695. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  9696. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  9697. break;
  9698. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  9699. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  9700. break;
  9701. }
  9702. }
  9703. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  9704. }
  9705. };
  9706. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  9707. if (channel < 0) {
  9708. return;
  9709. }
  9710. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  9711. this._textureUnits = new Int32Array(textures.length);
  9712. }
  9713. for (var i = 0; i < textures.length; i++) {
  9714. this._textureUnits[i] = channel + i;
  9715. }
  9716. this._gl.uniform1iv(uniform, this._textureUnits);
  9717. for (var index = 0; index < textures.length; index++) {
  9718. this._setTexture(channel + index, textures[index]);
  9719. }
  9720. };
  9721. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  9722. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  9723. var value = texture.anisotropicFilteringLevel;
  9724. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  9725. value = 1;
  9726. }
  9727. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  9728. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  9729. texture._cachedAnisotropicFilteringLevel = value;
  9730. }
  9731. };
  9732. Engine.prototype.readPixels = function (x, y, width, height) {
  9733. var data = new Uint8Array(height * width * 4);
  9734. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  9735. return data;
  9736. };
  9737. /**
  9738. * Add an externaly attached data from its key.
  9739. * This method call will fail and return false, if such key already exists.
  9740. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  9741. * @param key the unique key that identifies the data
  9742. * @param data the data object to associate to the key for this Engine instance
  9743. * @return true if no such key were already present and the data was added successfully, false otherwise
  9744. */
  9745. Engine.prototype.addExternalData = function (key, data) {
  9746. if (!this._externalData) {
  9747. this._externalData = new BABYLON.StringDictionary();
  9748. }
  9749. return this._externalData.add(key, data);
  9750. };
  9751. /**
  9752. * Get an externaly attached data from its key
  9753. * @param key the unique key that identifies the data
  9754. * @return the associated data, if present (can be null), or undefined if not present
  9755. */
  9756. Engine.prototype.getExternalData = function (key) {
  9757. if (!this._externalData) {
  9758. this._externalData = new BABYLON.StringDictionary();
  9759. }
  9760. return this._externalData.get(key);
  9761. };
  9762. /**
  9763. * Get an externaly attached data from its key, create it using a factory if it's not already present
  9764. * @param key the unique key that identifies the data
  9765. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  9766. * @return the associated data, can be null if the factory returned null.
  9767. */
  9768. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  9769. if (!this._externalData) {
  9770. this._externalData = new BABYLON.StringDictionary();
  9771. }
  9772. return this._externalData.getOrAddWithFactory(key, factory);
  9773. };
  9774. /**
  9775. * Remove an externaly attached data from the Engine instance
  9776. * @param key the unique key that identifies the data
  9777. * @return true if the data was successfully removed, false if it doesn't exist
  9778. */
  9779. Engine.prototype.removeExternalData = function (key) {
  9780. if (!this._externalData) {
  9781. this._externalData = new BABYLON.StringDictionary();
  9782. }
  9783. return this._externalData.remove(key);
  9784. };
  9785. Engine.prototype.releaseInternalTexture = function (texture) {
  9786. if (!texture) {
  9787. return;
  9788. }
  9789. texture.references--;
  9790. // Final reference ?
  9791. if (texture.references === 0) {
  9792. var texturesCache = this.getLoadedTexturesCache();
  9793. var index = texturesCache.indexOf(texture);
  9794. if (index > -1) {
  9795. texturesCache.splice(index, 1);
  9796. }
  9797. this._releaseTexture(texture);
  9798. }
  9799. };
  9800. Engine.prototype.unbindAllAttributes = function () {
  9801. if (this._mustWipeVertexAttributes) {
  9802. this._mustWipeVertexAttributes = false;
  9803. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  9804. this._gl.disableVertexAttribArray(i);
  9805. this._vertexAttribArraysEnabled[i] = false;
  9806. this._currentBufferPointers[i] = null;
  9807. }
  9808. return;
  9809. }
  9810. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  9811. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  9812. continue;
  9813. }
  9814. this._gl.disableVertexAttribArray(i);
  9815. this._vertexAttribArraysEnabled[i] = false;
  9816. this._currentBufferPointers[i] = null;
  9817. }
  9818. };
  9819. Engine.prototype.releaseEffects = function () {
  9820. for (var name in this._compiledEffects) {
  9821. this._gl.deleteProgram(this._compiledEffects[name]._program);
  9822. }
  9823. this._compiledEffects = {};
  9824. };
  9825. // Dispose
  9826. Engine.prototype.dispose = function () {
  9827. this.hideLoadingUI();
  9828. this.stopRenderLoop();
  9829. // Release scenes
  9830. while (this.scenes.length) {
  9831. this.scenes[0].dispose();
  9832. }
  9833. // Release audio engine
  9834. if (Engine.audioEngine) {
  9835. Engine.audioEngine.dispose();
  9836. }
  9837. // Release effects
  9838. this.releaseEffects();
  9839. // Unbind
  9840. this.unbindAllAttributes();
  9841. this._gl = null;
  9842. //WebVR
  9843. this.disableVR();
  9844. // Events
  9845. window.removeEventListener("blur", this._onBlur);
  9846. window.removeEventListener("focus", this._onFocus);
  9847. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  9848. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  9849. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  9850. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  9851. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  9852. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  9853. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  9854. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  9855. // Remove from Instances
  9856. var index = Engine.Instances.indexOf(this);
  9857. if (index >= 0) {
  9858. Engine.Instances.splice(index, 1);
  9859. }
  9860. };
  9861. // Loading screen
  9862. Engine.prototype.displayLoadingUI = function () {
  9863. var loadingScreen = this.loadingScreen;
  9864. if (loadingScreen) {
  9865. loadingScreen.displayLoadingUI();
  9866. }
  9867. };
  9868. Engine.prototype.hideLoadingUI = function () {
  9869. var loadingScreen = this.loadingScreen;
  9870. if (loadingScreen) {
  9871. loadingScreen.hideLoadingUI();
  9872. }
  9873. };
  9874. Object.defineProperty(Engine.prototype, "loadingScreen", {
  9875. get: function () {
  9876. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen)
  9877. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  9878. return this._loadingScreen;
  9879. },
  9880. set: function (loadingScreen) {
  9881. this._loadingScreen = loadingScreen;
  9882. },
  9883. enumerable: true,
  9884. configurable: true
  9885. });
  9886. Object.defineProperty(Engine.prototype, "loadingUIText", {
  9887. set: function (text) {
  9888. this.loadingScreen.loadingUIText = text;
  9889. },
  9890. enumerable: true,
  9891. configurable: true
  9892. });
  9893. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  9894. set: function (color) {
  9895. this.loadingScreen.loadingUIBackgroundColor = color;
  9896. },
  9897. enumerable: true,
  9898. configurable: true
  9899. });
  9900. Engine.prototype.attachContextLostEvent = function (callback) {
  9901. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  9902. };
  9903. Engine.prototype.attachContextRestoredEvent = function (callback) {
  9904. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  9905. };
  9906. Engine.prototype.getVertexShaderSource = function (program) {
  9907. var shaders = this._gl.getAttachedShaders(program);
  9908. return this._gl.getShaderSource(shaders[0]);
  9909. };
  9910. Engine.prototype.getFragmentShaderSource = function (program) {
  9911. var shaders = this._gl.getAttachedShaders(program);
  9912. return this._gl.getShaderSource(shaders[1]);
  9913. };
  9914. // FPS
  9915. Engine.prototype.getFps = function () {
  9916. return this.fps;
  9917. };
  9918. Engine.prototype.getDeltaTime = function () {
  9919. return this.deltaTime;
  9920. };
  9921. Engine.prototype._measureFps = function () {
  9922. this.previousFramesDuration.push(BABYLON.Tools.Now);
  9923. var length = this.previousFramesDuration.length;
  9924. if (length >= 2) {
  9925. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  9926. }
  9927. if (length >= this.fpsRange) {
  9928. if (length > this.fpsRange) {
  9929. this.previousFramesDuration.splice(0, 1);
  9930. length = this.previousFramesDuration.length;
  9931. }
  9932. var sum = 0;
  9933. for (var id = 0; id < length - 1; id++) {
  9934. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  9935. }
  9936. this.fps = 1000.0 / (sum / (length - 1));
  9937. }
  9938. };
  9939. Engine.prototype._canRenderToFloatFramebuffer = function () {
  9940. if (this._webGLVersion > 1) {
  9941. return this._caps.colorBufferFloat;
  9942. }
  9943. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_FLOAT);
  9944. };
  9945. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  9946. if (this._webGLVersion > 1) {
  9947. return this._caps.colorBufferFloat;
  9948. }
  9949. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  9950. };
  9951. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  9952. Engine.prototype._canRenderToFramebuffer = function (type) {
  9953. var gl = this._gl;
  9954. //clear existing errors
  9955. while (gl.getError() !== gl.NO_ERROR) { }
  9956. var successful = true;
  9957. var texture = gl.createTexture();
  9958. gl.bindTexture(gl.TEXTURE_2D, texture);
  9959. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  9960. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  9961. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  9962. var fb = gl.createFramebuffer();
  9963. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  9964. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  9965. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  9966. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  9967. successful = successful && (gl.getError() === gl.NO_ERROR);
  9968. //try render by clearing frame buffer's color buffer
  9969. if (successful) {
  9970. gl.clear(gl.COLOR_BUFFER_BIT);
  9971. successful = successful && (gl.getError() === gl.NO_ERROR);
  9972. }
  9973. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  9974. if (successful) {
  9975. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  9976. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  9977. var readFormat = gl.RGBA;
  9978. var readType = gl.UNSIGNED_BYTE;
  9979. var buffer = new Uint8Array(4);
  9980. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  9981. successful = successful && (gl.getError() === gl.NO_ERROR);
  9982. }
  9983. //clean up
  9984. gl.deleteTexture(texture);
  9985. gl.deleteFramebuffer(fb);
  9986. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  9987. //clear accumulated errors
  9988. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  9989. return successful;
  9990. };
  9991. Engine.prototype._getWebGLTextureType = function (type) {
  9992. if (type === Engine.TEXTURETYPE_FLOAT) {
  9993. return this._gl.FLOAT;
  9994. }
  9995. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  9996. // Add Half Float Constant.
  9997. return Engine.HALF_FLOAT_OES;
  9998. }
  9999. return this._gl.UNSIGNED_BYTE;
  10000. };
  10001. ;
  10002. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  10003. if (this._webGLVersion === 1) {
  10004. return this._gl.RGBA;
  10005. }
  10006. if (type === Engine.TEXTURETYPE_FLOAT) {
  10007. return Engine.RGBA32F;
  10008. }
  10009. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  10010. return Engine.RGBA16F;
  10011. }
  10012. return this._gl.RGBA;
  10013. };
  10014. ;
  10015. // Statics
  10016. Engine.isSupported = function () {
  10017. try {
  10018. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  10019. if (navigator.isCocoonJS) {
  10020. return true;
  10021. }
  10022. var tempcanvas = document.createElement("canvas");
  10023. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  10024. return gl != null && !!window.WebGLRenderingContext;
  10025. }
  10026. catch (e) {
  10027. return false;
  10028. }
  10029. };
  10030. return Engine;
  10031. }());
  10032. Engine.Instances = new Array();
  10033. // Const statics
  10034. Engine._ALPHA_DISABLE = 0;
  10035. Engine._ALPHA_ADD = 1;
  10036. Engine._ALPHA_COMBINE = 2;
  10037. Engine._ALPHA_SUBTRACT = 3;
  10038. Engine._ALPHA_MULTIPLY = 4;
  10039. Engine._ALPHA_MAXIMIZED = 5;
  10040. Engine._ALPHA_ONEONE = 6;
  10041. Engine._ALPHA_PREMULTIPLIED = 7;
  10042. Engine._DELAYLOADSTATE_NONE = 0;
  10043. Engine._DELAYLOADSTATE_LOADED = 1;
  10044. Engine._DELAYLOADSTATE_LOADING = 2;
  10045. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  10046. Engine._TEXTUREFORMAT_ALPHA = 0;
  10047. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  10048. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  10049. Engine._TEXTUREFORMAT_RGB = 4;
  10050. Engine._TEXTUREFORMAT_RGBA = 5;
  10051. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  10052. Engine._TEXTURETYPE_FLOAT = 1;
  10053. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  10054. // Depht or Stencil test Constants.
  10055. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  10056. 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.
  10057. 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.
  10058. 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.
  10059. 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.
  10060. 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.
  10061. 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.
  10062. 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.
  10063. Engine.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  10064. Engine.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  10065. Engine.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  10066. // Stencil Actions Constants.
  10067. Engine._KEEP = 0x1E00;
  10068. Engine._REPLACE = 0x1E01;
  10069. Engine._INCR = 0x1E02;
  10070. Engine._DECR = 0x1E03;
  10071. Engine._INVERT = 0x150A;
  10072. Engine._INCR_WRAP = 0x8507;
  10073. Engine._DECR_WRAP = 0x8508;
  10074. // Updatable statics so stick with vars here
  10075. Engine.CollisionsEpsilon = 0.001;
  10076. Engine.CodeRepository = "src/";
  10077. Engine.ShadersRepository = "src/Shaders/";
  10078. BABYLON.Engine = Engine;
  10079. })(BABYLON || (BABYLON = {}));
  10080. //# sourceMappingURL=babylon.engine.js.map
  10081. /// <reference path="Tools\babylon.decorators.ts" />
  10082. var BABYLON;
  10083. (function (BABYLON) {
  10084. /**
  10085. * Node is the basic class for all scene objects (Mesh, Light Camera).
  10086. */
  10087. var Node = (function () {
  10088. /**
  10089. * @constructor
  10090. * @param {string} name - the name and id to be given to this node
  10091. * @param {BABYLON.Scene} the scene this node will be added to
  10092. */
  10093. function Node(name, scene) {
  10094. this.state = "";
  10095. this.metadata = null;
  10096. this.doNotSerialize = false;
  10097. this.animations = new Array();
  10098. this._ranges = {};
  10099. this._childrenFlag = -1;
  10100. this._isEnabled = true;
  10101. this._isReady = true;
  10102. this._currentRenderId = -1;
  10103. this._parentRenderId = -1;
  10104. /**
  10105. * An event triggered when the mesh is disposed.
  10106. * @type {BABYLON.Observable}
  10107. */
  10108. this.onDisposeObservable = new BABYLON.Observable();
  10109. this.name = name;
  10110. this.id = name;
  10111. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  10112. this._initCache();
  10113. }
  10114. Object.defineProperty(Node.prototype, "parent", {
  10115. get: function () {
  10116. return this._parentNode;
  10117. },
  10118. set: function (parent) {
  10119. if (this._parentNode === parent) {
  10120. return;
  10121. }
  10122. if (this._parentNode) {
  10123. var index = this._parentNode._children.indexOf(this);
  10124. if (index !== -1) {
  10125. this._parentNode._children.splice(index, 1);
  10126. }
  10127. }
  10128. this._parentNode = parent;
  10129. if (this._parentNode) {
  10130. if (!this._parentNode._children) {
  10131. this._parentNode._children = new Array();
  10132. }
  10133. this._parentNode._children.push(this);
  10134. }
  10135. },
  10136. enumerable: true,
  10137. configurable: true
  10138. });
  10139. Node.prototype.getClassName = function () {
  10140. return "Node";
  10141. };
  10142. Object.defineProperty(Node.prototype, "onDispose", {
  10143. set: function (callback) {
  10144. if (this._onDisposeObserver) {
  10145. this.onDisposeObservable.remove(this._onDisposeObserver);
  10146. }
  10147. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  10148. },
  10149. enumerable: true,
  10150. configurable: true
  10151. });
  10152. Node.prototype.getScene = function () {
  10153. return this._scene;
  10154. };
  10155. Node.prototype.getEngine = function () {
  10156. return this._scene.getEngine();
  10157. };
  10158. // override it in derived class
  10159. Node.prototype.getWorldMatrix = function () {
  10160. return BABYLON.Matrix.Identity();
  10161. };
  10162. // override it in derived class if you add new variables to the cache
  10163. // and call the parent class method
  10164. Node.prototype._initCache = function () {
  10165. this._cache = {};
  10166. this._cache.parent = undefined;
  10167. };
  10168. Node.prototype.updateCache = function (force) {
  10169. if (!force && this.isSynchronized())
  10170. return;
  10171. this._cache.parent = this.parent;
  10172. this._updateCache();
  10173. };
  10174. // override it in derived class if you add new variables to the cache
  10175. // and call the parent class method if !ignoreParentClass
  10176. Node.prototype._updateCache = function (ignoreParentClass) {
  10177. };
  10178. // override it in derived class if you add new variables to the cache
  10179. Node.prototype._isSynchronized = function () {
  10180. return true;
  10181. };
  10182. Node.prototype._markSyncedWithParent = function () {
  10183. this._parentRenderId = this.parent._currentRenderId;
  10184. };
  10185. Node.prototype.isSynchronizedWithParent = function () {
  10186. if (!this.parent) {
  10187. return true;
  10188. }
  10189. if (this._parentRenderId !== this.parent._currentRenderId) {
  10190. return false;
  10191. }
  10192. return this.parent.isSynchronized();
  10193. };
  10194. Node.prototype.isSynchronized = function (updateCache) {
  10195. var check = this.hasNewParent();
  10196. check = check || !this.isSynchronizedWithParent();
  10197. check = check || !this._isSynchronized();
  10198. if (updateCache)
  10199. this.updateCache(true);
  10200. return !check;
  10201. };
  10202. Node.prototype.hasNewParent = function (update) {
  10203. if (this._cache.parent === this.parent)
  10204. return false;
  10205. if (update)
  10206. this._cache.parent = this.parent;
  10207. return true;
  10208. };
  10209. /**
  10210. * Is this node ready to be used/rendered
  10211. * @return {boolean} is it ready
  10212. */
  10213. Node.prototype.isReady = function () {
  10214. return this._isReady;
  10215. };
  10216. /**
  10217. * Is this node enabled.
  10218. * If the node has a parent and is enabled, the parent will be inspected as well.
  10219. * @return {boolean} whether this node (and its parent) is enabled.
  10220. * @see setEnabled
  10221. */
  10222. Node.prototype.isEnabled = function () {
  10223. if (!this._isEnabled) {
  10224. return false;
  10225. }
  10226. if (this.parent) {
  10227. return this.parent.isEnabled();
  10228. }
  10229. return true;
  10230. };
  10231. /**
  10232. * Set the enabled state of this node.
  10233. * @param {boolean} value - the new enabled state
  10234. * @see isEnabled
  10235. */
  10236. Node.prototype.setEnabled = function (value) {
  10237. this._isEnabled = value;
  10238. };
  10239. /**
  10240. * Is this node a descendant of the given node.
  10241. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  10242. * @param {BABYLON.Node} ancestor - The parent node to inspect
  10243. * @see parent
  10244. */
  10245. Node.prototype.isDescendantOf = function (ancestor) {
  10246. if (this.parent) {
  10247. if (this.parent === ancestor) {
  10248. return true;
  10249. }
  10250. return this.parent.isDescendantOf(ancestor);
  10251. }
  10252. return false;
  10253. };
  10254. /**
  10255. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  10256. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  10257. * @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.
  10258. * @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.
  10259. */
  10260. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  10261. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  10262. if (!this._children) {
  10263. return;
  10264. }
  10265. for (var index = 0; index < this._children.length; index++) {
  10266. var item = this._children[index];
  10267. if (!predicate || predicate(item)) {
  10268. results.push(item);
  10269. }
  10270. if (!directDescendantsOnly) {
  10271. item._getDescendants(results, false, predicate);
  10272. }
  10273. }
  10274. };
  10275. /**
  10276. * Will return all nodes that have this node as ascendant.
  10277. * @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.
  10278. * @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.
  10279. * @return {BABYLON.Node[]} all children nodes of all types.
  10280. */
  10281. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  10282. var results = [];
  10283. this._getDescendants(results, directDescendantsOnly, predicate);
  10284. return results;
  10285. };
  10286. /**
  10287. * Get all child-meshes of this node.
  10288. */
  10289. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  10290. var results = [];
  10291. this._getDescendants(results, directDecendantsOnly, function (node) {
  10292. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  10293. });
  10294. return results;
  10295. };
  10296. /**
  10297. * Get all direct children of this node.
  10298. */
  10299. Node.prototype.getChildren = function (predicate) {
  10300. return this.getDescendants(true, predicate);
  10301. };
  10302. Node.prototype._setReady = function (state) {
  10303. if (state === this._isReady) {
  10304. return;
  10305. }
  10306. if (!state) {
  10307. this._isReady = false;
  10308. return;
  10309. }
  10310. this._isReady = true;
  10311. if (this.onReady) {
  10312. this.onReady(this);
  10313. }
  10314. };
  10315. Node.prototype.getAnimationByName = function (name) {
  10316. for (var i = 0; i < this.animations.length; i++) {
  10317. var animation = this.animations[i];
  10318. if (animation.name === name) {
  10319. return animation;
  10320. }
  10321. }
  10322. return null;
  10323. };
  10324. Node.prototype.createAnimationRange = function (name, from, to) {
  10325. // check name not already in use
  10326. if (!this._ranges[name]) {
  10327. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  10328. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  10329. if (this.animations[i]) {
  10330. this.animations[i].createRange(name, from, to);
  10331. }
  10332. }
  10333. }
  10334. };
  10335. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  10336. if (deleteFrames === void 0) { deleteFrames = true; }
  10337. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  10338. if (this.animations[i]) {
  10339. this.animations[i].deleteRange(name, deleteFrames);
  10340. }
  10341. }
  10342. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  10343. };
  10344. Node.prototype.getAnimationRange = function (name) {
  10345. return this._ranges[name];
  10346. };
  10347. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  10348. var range = this.getAnimationRange(name);
  10349. if (!range) {
  10350. return null;
  10351. }
  10352. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  10353. };
  10354. Node.prototype.serializeAnimationRanges = function () {
  10355. var serializationRanges = [];
  10356. for (var name in this._ranges) {
  10357. var range = {};
  10358. range.name = name;
  10359. range.from = this._ranges[name].from;
  10360. range.to = this._ranges[name].to;
  10361. serializationRanges.push(range);
  10362. }
  10363. return serializationRanges;
  10364. };
  10365. Node.prototype.dispose = function () {
  10366. this.parent = null;
  10367. // Callback
  10368. this.onDisposeObservable.notifyObservers(this);
  10369. this.onDisposeObservable.clear();
  10370. };
  10371. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  10372. if (parsedNode.ranges) {
  10373. for (var index = 0; index < parsedNode.ranges.length; index++) {
  10374. var data = parsedNode.ranges[index];
  10375. node.createAnimationRange(data.name, data.from, data.to);
  10376. }
  10377. }
  10378. };
  10379. return Node;
  10380. }());
  10381. __decorate([
  10382. BABYLON.serialize()
  10383. ], Node.prototype, "name", void 0);
  10384. __decorate([
  10385. BABYLON.serialize()
  10386. ], Node.prototype, "id", void 0);
  10387. __decorate([
  10388. BABYLON.serialize()
  10389. ], Node.prototype, "uniqueId", void 0);
  10390. __decorate([
  10391. BABYLON.serialize()
  10392. ], Node.prototype, "state", void 0);
  10393. __decorate([
  10394. BABYLON.serialize()
  10395. ], Node.prototype, "metadata", void 0);
  10396. BABYLON.Node = Node;
  10397. })(BABYLON || (BABYLON = {}));
  10398. //# sourceMappingURL=babylon.node.js.map
  10399. var BABYLON;
  10400. (function (BABYLON) {
  10401. var BoundingSphere = (function () {
  10402. function BoundingSphere(minimum, maximum) {
  10403. this.minimum = minimum;
  10404. this.maximum = maximum;
  10405. this._tempRadiusVector = BABYLON.Vector3.Zero();
  10406. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  10407. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  10408. this.radius = distance * 0.5;
  10409. this.centerWorld = BABYLON.Vector3.Zero();
  10410. this._update(BABYLON.Matrix.Identity());
  10411. }
  10412. // Methods
  10413. BoundingSphere.prototype._update = function (world) {
  10414. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  10415. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  10416. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  10417. };
  10418. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  10419. for (var i = 0; i < 6; i++) {
  10420. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  10421. return false;
  10422. }
  10423. return true;
  10424. };
  10425. BoundingSphere.prototype.intersectsPoint = function (point) {
  10426. var x = this.centerWorld.x - point.x;
  10427. var y = this.centerWorld.y - point.y;
  10428. var z = this.centerWorld.z - point.z;
  10429. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  10430. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  10431. return false;
  10432. return true;
  10433. };
  10434. // Statics
  10435. BoundingSphere.Intersects = function (sphere0, sphere1) {
  10436. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  10437. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  10438. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  10439. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  10440. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  10441. return false;
  10442. return true;
  10443. };
  10444. return BoundingSphere;
  10445. }());
  10446. BABYLON.BoundingSphere = BoundingSphere;
  10447. })(BABYLON || (BABYLON = {}));
  10448. //# sourceMappingURL=babylon.boundingSphere.js.map
  10449. var BABYLON;
  10450. (function (BABYLON) {
  10451. var BoundingBox = (function () {
  10452. function BoundingBox(minimum, maximum) {
  10453. this.minimum = minimum;
  10454. this.maximum = maximum;
  10455. this.vectors = new Array();
  10456. this.vectorsWorld = new Array();
  10457. // Bounding vectors
  10458. this.vectors.push(this.minimum.clone());
  10459. this.vectors.push(this.maximum.clone());
  10460. this.vectors.push(this.minimum.clone());
  10461. this.vectors[2].x = this.maximum.x;
  10462. this.vectors.push(this.minimum.clone());
  10463. this.vectors[3].y = this.maximum.y;
  10464. this.vectors.push(this.minimum.clone());
  10465. this.vectors[4].z = this.maximum.z;
  10466. this.vectors.push(this.maximum.clone());
  10467. this.vectors[5].z = this.minimum.z;
  10468. this.vectors.push(this.maximum.clone());
  10469. this.vectors[6].x = this.minimum.x;
  10470. this.vectors.push(this.maximum.clone());
  10471. this.vectors[7].y = this.minimum.y;
  10472. // OBB
  10473. this.center = this.maximum.add(this.minimum).scale(0.5);
  10474. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  10475. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  10476. // World
  10477. for (var index = 0; index < this.vectors.length; index++) {
  10478. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  10479. }
  10480. this.minimumWorld = BABYLON.Vector3.Zero();
  10481. this.maximumWorld = BABYLON.Vector3.Zero();
  10482. this.centerWorld = BABYLON.Vector3.Zero();
  10483. this.extendSizeWorld = BABYLON.Vector3.Zero();
  10484. this._update(BABYLON.Matrix.Identity());
  10485. }
  10486. // Methods
  10487. BoundingBox.prototype.getWorldMatrix = function () {
  10488. return this._worldMatrix;
  10489. };
  10490. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  10491. this._worldMatrix.copyFrom(matrix);
  10492. return this;
  10493. };
  10494. BoundingBox.prototype._update = function (world) {
  10495. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  10496. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  10497. for (var index = 0; index < this.vectors.length; index++) {
  10498. var v = this.vectorsWorld[index];
  10499. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  10500. if (v.x < this.minimumWorld.x)
  10501. this.minimumWorld.x = v.x;
  10502. if (v.y < this.minimumWorld.y)
  10503. this.minimumWorld.y = v.y;
  10504. if (v.z < this.minimumWorld.z)
  10505. this.minimumWorld.z = v.z;
  10506. if (v.x > this.maximumWorld.x)
  10507. this.maximumWorld.x = v.x;
  10508. if (v.y > this.maximumWorld.y)
  10509. this.maximumWorld.y = v.y;
  10510. if (v.z > this.maximumWorld.z)
  10511. this.maximumWorld.z = v.z;
  10512. }
  10513. // Extend
  10514. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  10515. this.extendSizeWorld.scaleInPlace(0.5);
  10516. // OBB
  10517. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  10518. this.centerWorld.scaleInPlace(0.5);
  10519. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  10520. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  10521. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  10522. this._worldMatrix = world;
  10523. };
  10524. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  10525. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  10526. };
  10527. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  10528. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  10529. };
  10530. BoundingBox.prototype.intersectsPoint = function (point) {
  10531. var delta = -BABYLON.Epsilon;
  10532. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  10533. return false;
  10534. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  10535. return false;
  10536. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  10537. return false;
  10538. return true;
  10539. };
  10540. BoundingBox.prototype.intersectsSphere = function (sphere) {
  10541. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  10542. };
  10543. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  10544. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  10545. return false;
  10546. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  10547. return false;
  10548. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  10549. return false;
  10550. return true;
  10551. };
  10552. // Statics
  10553. BoundingBox.Intersects = function (box0, box1) {
  10554. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  10555. return false;
  10556. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  10557. return false;
  10558. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  10559. return false;
  10560. return true;
  10561. };
  10562. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  10563. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  10564. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  10565. return (num <= (sphereRadius * sphereRadius));
  10566. };
  10567. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  10568. for (var p = 0; p < 6; p++) {
  10569. for (var i = 0; i < 8; i++) {
  10570. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  10571. return false;
  10572. }
  10573. }
  10574. }
  10575. return true;
  10576. };
  10577. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  10578. for (var p = 0; p < 6; p++) {
  10579. var inCount = 8;
  10580. for (var i = 0; i < 8; i++) {
  10581. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  10582. --inCount;
  10583. }
  10584. else {
  10585. break;
  10586. }
  10587. }
  10588. if (inCount === 0)
  10589. return false;
  10590. }
  10591. return true;
  10592. };
  10593. return BoundingBox;
  10594. }());
  10595. BABYLON.BoundingBox = BoundingBox;
  10596. })(BABYLON || (BABYLON = {}));
  10597. //# sourceMappingURL=babylon.boundingBox.js.map
  10598. var BABYLON;
  10599. (function (BABYLON) {
  10600. var computeBoxExtents = function (axis, box) {
  10601. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  10602. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  10603. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  10604. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  10605. var r = r0 + r1 + r2;
  10606. return {
  10607. min: p - r,
  10608. max: p + r
  10609. };
  10610. };
  10611. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  10612. var axisOverlap = function (axis, box0, box1) {
  10613. var result0 = computeBoxExtents(axis, box0);
  10614. var result1 = computeBoxExtents(axis, box1);
  10615. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  10616. };
  10617. var BoundingInfo = (function () {
  10618. function BoundingInfo(minimum, maximum) {
  10619. this.minimum = minimum;
  10620. this.maximum = maximum;
  10621. this._isLocked = false;
  10622. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  10623. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  10624. }
  10625. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  10626. get: function () {
  10627. return this._isLocked;
  10628. },
  10629. set: function (value) {
  10630. this._isLocked = value;
  10631. },
  10632. enumerable: true,
  10633. configurable: true
  10634. });
  10635. // Methods
  10636. BoundingInfo.prototype.update = function (world) {
  10637. if (this._isLocked) {
  10638. return;
  10639. }
  10640. this.boundingBox._update(world);
  10641. this.boundingSphere._update(world);
  10642. };
  10643. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  10644. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  10645. return false;
  10646. return this.boundingBox.isInFrustum(frustumPlanes);
  10647. };
  10648. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  10649. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  10650. };
  10651. BoundingInfo.prototype._checkCollision = function (collider) {
  10652. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  10653. };
  10654. BoundingInfo.prototype.intersectsPoint = function (point) {
  10655. if (!this.boundingSphere.centerWorld) {
  10656. return false;
  10657. }
  10658. if (!this.boundingSphere.intersectsPoint(point)) {
  10659. return false;
  10660. }
  10661. if (!this.boundingBox.intersectsPoint(point)) {
  10662. return false;
  10663. }
  10664. return true;
  10665. };
  10666. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  10667. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  10668. return false;
  10669. }
  10670. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  10671. return false;
  10672. }
  10673. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  10674. return false;
  10675. }
  10676. if (!precise) {
  10677. return true;
  10678. }
  10679. var box0 = this.boundingBox;
  10680. var box1 = boundingInfo.boundingBox;
  10681. if (!axisOverlap(box0.directions[0], box0, box1))
  10682. return false;
  10683. if (!axisOverlap(box0.directions[1], box0, box1))
  10684. return false;
  10685. if (!axisOverlap(box0.directions[2], box0, box1))
  10686. return false;
  10687. if (!axisOverlap(box1.directions[0], box0, box1))
  10688. return false;
  10689. if (!axisOverlap(box1.directions[1], box0, box1))
  10690. return false;
  10691. if (!axisOverlap(box1.directions[2], box0, box1))
  10692. return false;
  10693. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  10694. return false;
  10695. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  10696. return false;
  10697. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  10698. return false;
  10699. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  10700. return false;
  10701. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  10702. return false;
  10703. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  10704. return false;
  10705. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  10706. return false;
  10707. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  10708. return false;
  10709. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  10710. return false;
  10711. return true;
  10712. };
  10713. return BoundingInfo;
  10714. }());
  10715. BABYLON.BoundingInfo = BoundingInfo;
  10716. })(BABYLON || (BABYLON = {}));
  10717. //# sourceMappingURL=babylon.boundingInfo.js.map
  10718. var BABYLON;
  10719. (function (BABYLON) {
  10720. var AbstractMesh = (function (_super) {
  10721. __extends(AbstractMesh, _super);
  10722. // Constructor
  10723. function AbstractMesh(name, scene) {
  10724. var _this = _super.call(this, name, scene) || this;
  10725. _this._facetNb = 0; // facet number
  10726. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  10727. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  10728. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  10729. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  10730. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  10731. _this._subDiv = {
  10732. max: 1,
  10733. X: 1,
  10734. Y: 1,
  10735. Z: 1
  10736. };
  10737. // Events
  10738. /**
  10739. * An event triggered when this mesh collides with another one
  10740. * @type {BABYLON.Observable}
  10741. */
  10742. _this.onCollideObservable = new BABYLON.Observable();
  10743. /**
  10744. * An event triggered when the collision's position changes
  10745. * @type {BABYLON.Observable}
  10746. */
  10747. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  10748. /**
  10749. * An event triggered after the world matrix is updated
  10750. * @type {BABYLON.Observable}
  10751. */
  10752. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  10753. // Properties
  10754. _this.definedFacingForward = true; // orientation for POV movement & rotation
  10755. _this.position = new BABYLON.Vector3(0.0, 0.0, 0.0);
  10756. _this._rotation = new BABYLON.Vector3(0.0, 0.0, 0.0);
  10757. _this._scaling = new BABYLON.Vector3(1.0, 1.0, 1.0);
  10758. _this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  10759. _this.visibility = 1.0;
  10760. _this.alphaIndex = Number.MAX_VALUE;
  10761. _this.infiniteDistance = false;
  10762. _this.isVisible = true;
  10763. _this.isPickable = true;
  10764. _this.showBoundingBox = false;
  10765. _this.showSubMeshesBoundingBox = false;
  10766. _this.isBlocker = false;
  10767. _this.renderingGroupId = 0;
  10768. _this._receiveShadows = false;
  10769. _this.renderOutline = false;
  10770. _this.outlineColor = BABYLON.Color3.Red();
  10771. _this.outlineWidth = 0.02;
  10772. _this.renderOverlay = false;
  10773. _this.overlayColor = BABYLON.Color3.Red();
  10774. _this.overlayAlpha = 0.5;
  10775. _this._hasVertexAlpha = false;
  10776. _this._useVertexColors = true;
  10777. _this._computeBonesUsingShaders = true;
  10778. _this._numBoneInfluencers = 4;
  10779. _this._applyFog = true;
  10780. _this.scalingDeterminant = 1;
  10781. _this.useOctreeForRenderingSelection = true;
  10782. _this.useOctreeForPicking = true;
  10783. _this.useOctreeForCollisions = true;
  10784. _this.layerMask = 0x0FFFFFFF;
  10785. /**
  10786. * True if the mesh must be rendered in any case.
  10787. */
  10788. _this.alwaysSelectAsActiveMesh = false;
  10789. // Collisions
  10790. _this._checkCollisions = false;
  10791. _this._collisionMask = -1;
  10792. _this._collisionGroup = -1;
  10793. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  10794. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  10795. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10796. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10797. _this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10798. // Edges
  10799. _this.edgesWidth = 1;
  10800. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  10801. // Cache
  10802. _this._localWorld = BABYLON.Matrix.Zero();
  10803. _this._worldMatrix = BABYLON.Matrix.Zero();
  10804. _this._absolutePosition = BABYLON.Vector3.Zero();
  10805. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  10806. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  10807. _this._isDirty = false;
  10808. _this._pivotMatrix = BABYLON.Matrix.Identity();
  10809. _this._isDisposed = false;
  10810. _this._renderId = 0;
  10811. _this._intersectionsInProgress = new Array();
  10812. _this._isWorldMatrixFrozen = false;
  10813. _this._unIndexed = false;
  10814. _this._lightSources = new Array();
  10815. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  10816. if (collidedMesh === void 0) { collidedMesh = null; }
  10817. //TODO move this to the collision coordinator!
  10818. if (_this.getScene().workerCollisions)
  10819. newPosition.multiplyInPlace(_this._collider.radius);
  10820. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  10821. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  10822. _this.position.addInPlace(_this._diffPositionForCollisions);
  10823. }
  10824. if (collidedMesh) {
  10825. _this.onCollideObservable.notifyObservers(collidedMesh);
  10826. }
  10827. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  10828. };
  10829. _this.getScene().addMesh(_this);
  10830. _this._resyncLightSources();
  10831. return _this;
  10832. }
  10833. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  10834. get: function () {
  10835. return AbstractMesh._BILLBOARDMODE_NONE;
  10836. },
  10837. enumerable: true,
  10838. configurable: true
  10839. });
  10840. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  10841. get: function () {
  10842. return AbstractMesh._BILLBOARDMODE_X;
  10843. },
  10844. enumerable: true,
  10845. configurable: true
  10846. });
  10847. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  10848. get: function () {
  10849. return AbstractMesh._BILLBOARDMODE_Y;
  10850. },
  10851. enumerable: true,
  10852. configurable: true
  10853. });
  10854. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  10855. get: function () {
  10856. return AbstractMesh._BILLBOARDMODE_Z;
  10857. },
  10858. enumerable: true,
  10859. configurable: true
  10860. });
  10861. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  10862. get: function () {
  10863. return AbstractMesh._BILLBOARDMODE_ALL;
  10864. },
  10865. enumerable: true,
  10866. configurable: true
  10867. });
  10868. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  10869. /**
  10870. * Read-only : the number of facets in the mesh
  10871. */
  10872. get: function () {
  10873. return this._facetNb;
  10874. },
  10875. enumerable: true,
  10876. configurable: true
  10877. });
  10878. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  10879. /**
  10880. * The number (integer) of subdivisions per axis in the partioning space
  10881. */
  10882. get: function () {
  10883. return this._partitioningSubdivisions;
  10884. },
  10885. set: function (nb) {
  10886. this._partitioningSubdivisions = nb;
  10887. },
  10888. enumerable: true,
  10889. configurable: true
  10890. });
  10891. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  10892. /**
  10893. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  10894. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  10895. */
  10896. get: function () {
  10897. return this._partitioningBBoxRatio;
  10898. },
  10899. set: function (ratio) {
  10900. this._partitioningBBoxRatio = ratio;
  10901. },
  10902. enumerable: true,
  10903. configurable: true
  10904. });
  10905. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  10906. /**
  10907. * Read-only boolean : is the feature facetData enabled ?
  10908. */
  10909. get: function () {
  10910. return this._facetDataEnabled;
  10911. },
  10912. enumerable: true,
  10913. configurable: true
  10914. });
  10915. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  10916. set: function (callback) {
  10917. if (this._onCollideObserver) {
  10918. this.onCollideObservable.remove(this._onCollideObserver);
  10919. }
  10920. this._onCollideObserver = this.onCollideObservable.add(callback);
  10921. },
  10922. enumerable: true,
  10923. configurable: true
  10924. });
  10925. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  10926. set: function (callback) {
  10927. if (this._onCollisionPositionChangeObserver) {
  10928. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  10929. }
  10930. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  10931. },
  10932. enumerable: true,
  10933. configurable: true
  10934. });
  10935. Object.defineProperty(AbstractMesh.prototype, "material", {
  10936. get: function () {
  10937. return this._material;
  10938. },
  10939. set: function (value) {
  10940. if (this._material === value) {
  10941. return;
  10942. }
  10943. this._material = value;
  10944. if (!this.subMeshes) {
  10945. return;
  10946. }
  10947. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  10948. var subMesh = _a[_i];
  10949. subMesh.setEffect(null);
  10950. }
  10951. },
  10952. enumerable: true,
  10953. configurable: true
  10954. });
  10955. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  10956. get: function () {
  10957. return this._receiveShadows;
  10958. },
  10959. set: function (value) {
  10960. if (this._receiveShadows === value) {
  10961. return;
  10962. }
  10963. this._receiveShadows = value;
  10964. this._markSubMeshesAsLightDirty();
  10965. },
  10966. enumerable: true,
  10967. configurable: true
  10968. });
  10969. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  10970. get: function () {
  10971. return this._hasVertexAlpha;
  10972. },
  10973. set: function (value) {
  10974. if (this._hasVertexAlpha === value) {
  10975. return;
  10976. }
  10977. this._hasVertexAlpha = value;
  10978. this._markSubMeshesAsAttributesDirty();
  10979. },
  10980. enumerable: true,
  10981. configurable: true
  10982. });
  10983. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  10984. get: function () {
  10985. return this._useVertexColors;
  10986. },
  10987. set: function (value) {
  10988. if (this._useVertexColors === value) {
  10989. return;
  10990. }
  10991. this._useVertexColors = value;
  10992. this._markSubMeshesAsAttributesDirty();
  10993. },
  10994. enumerable: true,
  10995. configurable: true
  10996. });
  10997. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  10998. get: function () {
  10999. return this._computeBonesUsingShaders;
  11000. },
  11001. set: function (value) {
  11002. if (this._computeBonesUsingShaders === value) {
  11003. return;
  11004. }
  11005. this._computeBonesUsingShaders = value;
  11006. this._markSubMeshesAsAttributesDirty();
  11007. },
  11008. enumerable: true,
  11009. configurable: true
  11010. });
  11011. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  11012. get: function () {
  11013. return this._numBoneInfluencers;
  11014. },
  11015. set: function (value) {
  11016. if (this._numBoneInfluencers === value) {
  11017. return;
  11018. }
  11019. this._numBoneInfluencers = value;
  11020. this._markSubMeshesAsAttributesDirty();
  11021. },
  11022. enumerable: true,
  11023. configurable: true
  11024. });
  11025. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  11026. get: function () {
  11027. return this._applyFog;
  11028. },
  11029. set: function (value) {
  11030. if (this._applyFog === value) {
  11031. return;
  11032. }
  11033. this._applyFog = value;
  11034. this._markSubMeshesAsMiscDirty();
  11035. },
  11036. enumerable: true,
  11037. configurable: true
  11038. });
  11039. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  11040. get: function () {
  11041. return this._collisionMask;
  11042. },
  11043. set: function (mask) {
  11044. this._collisionMask = !isNaN(mask) ? mask : -1;
  11045. },
  11046. enumerable: true,
  11047. configurable: true
  11048. });
  11049. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  11050. get: function () {
  11051. return this._collisionGroup;
  11052. },
  11053. set: function (mask) {
  11054. this._collisionGroup = !isNaN(mask) ? mask : -1;
  11055. },
  11056. enumerable: true,
  11057. configurable: true
  11058. });
  11059. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  11060. get: function () {
  11061. return this._skeleton;
  11062. },
  11063. set: function (value) {
  11064. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  11065. this._skeleton._unregisterMeshWithPoseMatrix(this);
  11066. }
  11067. if (value && value.needInitialSkinMatrix) {
  11068. value._registerMeshWithPoseMatrix(this);
  11069. }
  11070. this._skeleton = value;
  11071. if (!this._skeleton) {
  11072. this._bonesTransformMatrices = null;
  11073. }
  11074. this._markSubMeshesAsAttributesDirty();
  11075. },
  11076. enumerable: true,
  11077. configurable: true
  11078. });
  11079. /**
  11080. * Returns the string "AbstractMesh"
  11081. */
  11082. AbstractMesh.prototype.getClassName = function () {
  11083. return "AbstractMesh";
  11084. };
  11085. /**
  11086. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  11087. */
  11088. AbstractMesh.prototype.toString = function (fullDetails) {
  11089. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  11090. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  11091. if (this._skeleton) {
  11092. ret += ", skeleton: " + this._skeleton.name;
  11093. }
  11094. if (fullDetails) {
  11095. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  11096. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  11097. }
  11098. return ret;
  11099. };
  11100. AbstractMesh.prototype._resyncLightSources = function () {
  11101. this._lightSources.length = 0;
  11102. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  11103. var light = _a[_i];
  11104. if (!light.isEnabled()) {
  11105. continue;
  11106. }
  11107. if (light.canAffectMesh(this)) {
  11108. this._lightSources.push(light);
  11109. }
  11110. }
  11111. this._markSubMeshesAsLightDirty();
  11112. };
  11113. AbstractMesh.prototype._resyncLighSource = function (light) {
  11114. var isIn = light.isEnabled() && light.canAffectMesh(this);
  11115. var index = this._lightSources.indexOf(light);
  11116. if (index === -1) {
  11117. if (!isIn) {
  11118. return;
  11119. }
  11120. this._lightSources.push(light);
  11121. }
  11122. else {
  11123. if (isIn) {
  11124. return;
  11125. }
  11126. this._lightSources.splice(index, 1);
  11127. }
  11128. this._markSubMeshesAsLightDirty();
  11129. };
  11130. AbstractMesh.prototype._removeLightSource = function (light) {
  11131. var index = this._lightSources.indexOf(light);
  11132. if (index === -1) {
  11133. return;
  11134. }
  11135. this._lightSources.splice(index, 1);
  11136. };
  11137. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  11138. if (!this.subMeshes) {
  11139. return;
  11140. }
  11141. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  11142. var subMesh = _a[_i];
  11143. if (subMesh._materialDefines) {
  11144. func(subMesh._materialDefines);
  11145. }
  11146. }
  11147. };
  11148. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  11149. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  11150. };
  11151. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  11152. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  11153. };
  11154. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  11155. if (!this.subMeshes) {
  11156. return;
  11157. }
  11158. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  11159. var subMesh = _a[_i];
  11160. var material = subMesh.getMaterial();
  11161. if (material) {
  11162. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  11163. }
  11164. }
  11165. };
  11166. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  11167. /**
  11168. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  11169. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  11170. * Default : (0.0, 0.0, 0.0)
  11171. */
  11172. get: function () {
  11173. return this._rotation;
  11174. },
  11175. set: function (newRotation) {
  11176. this._rotation = newRotation;
  11177. },
  11178. enumerable: true,
  11179. configurable: true
  11180. });
  11181. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  11182. /**
  11183. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  11184. * Default : (1.0, 1.0, 1.0)
  11185. */
  11186. get: function () {
  11187. return this._scaling;
  11188. },
  11189. set: function (newScaling) {
  11190. this._scaling = newScaling;
  11191. if (this.physicsImpostor) {
  11192. this.physicsImpostor.forceUpdate();
  11193. }
  11194. },
  11195. enumerable: true,
  11196. configurable: true
  11197. });
  11198. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  11199. /**
  11200. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  11201. * It's null by default.
  11202. * 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)
  11203. */
  11204. get: function () {
  11205. return this._rotationQuaternion;
  11206. },
  11207. set: function (quaternion) {
  11208. this._rotationQuaternion = quaternion;
  11209. //reset the rotation vector.
  11210. if (quaternion && this.rotation.length()) {
  11211. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  11212. }
  11213. },
  11214. enumerable: true,
  11215. configurable: true
  11216. });
  11217. // Methods
  11218. /**
  11219. * Copies the paramater passed Matrix into the mesh Pose matrix.
  11220. * Returns the AbstractMesh.
  11221. */
  11222. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  11223. this._poseMatrix.copyFrom(matrix);
  11224. return this;
  11225. };
  11226. /**
  11227. * Returns the mesh Pose matrix.
  11228. * Returned object : Matrix
  11229. */
  11230. AbstractMesh.prototype.getPoseMatrix = function () {
  11231. return this._poseMatrix;
  11232. };
  11233. /**
  11234. * Disables the mesh edger rendering mode.
  11235. * Returns the AbstractMesh.
  11236. */
  11237. AbstractMesh.prototype.disableEdgesRendering = function () {
  11238. if (this._edgesRenderer !== undefined) {
  11239. this._edgesRenderer.dispose();
  11240. this._edgesRenderer = undefined;
  11241. }
  11242. return this;
  11243. };
  11244. /**
  11245. * Enables the edge rendering mode on the mesh.
  11246. * This mode makes the mesh edges visible.
  11247. * Returns the AbstractMesh.
  11248. */
  11249. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  11250. if (epsilon === void 0) { epsilon = 0.95; }
  11251. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  11252. this.disableEdgesRendering();
  11253. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  11254. return this;
  11255. };
  11256. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  11257. /**
  11258. * Returns true if the mesh is blocked. Used by the class Mesh.
  11259. * Returns the boolean `false` by default.
  11260. */
  11261. get: function () {
  11262. return false;
  11263. },
  11264. enumerable: true,
  11265. configurable: true
  11266. });
  11267. /**
  11268. * Returns the mesh itself by default, used by the class Mesh.
  11269. * Returned type : AbstractMesh
  11270. */
  11271. AbstractMesh.prototype.getLOD = function (camera) {
  11272. return this;
  11273. };
  11274. /**
  11275. * Returns 0 by default, used by the class Mesh.
  11276. * Returns an integer.
  11277. */
  11278. AbstractMesh.prototype.getTotalVertices = function () {
  11279. return 0;
  11280. };
  11281. /**
  11282. * Returns null by default, used by the class Mesh.
  11283. * Returned type : integer array
  11284. */
  11285. AbstractMesh.prototype.getIndices = function () {
  11286. return null;
  11287. };
  11288. /**
  11289. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  11290. * Returned type : float array or Float32Array
  11291. */
  11292. AbstractMesh.prototype.getVerticesData = function (kind) {
  11293. return null;
  11294. };
  11295. /**
  11296. * Sets the vertex data of the mesh geometry for the requested `kind`.
  11297. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  11298. * The `data` are either a numeric array either a Float32Array.
  11299. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  11300. * 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).
  11301. * Note that a new underlying VertexBuffer object is created each call.
  11302. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  11303. *
  11304. * Possible `kind` values :
  11305. * - BABYLON.VertexBuffer.PositionKind
  11306. * - BABYLON.VertexBuffer.UVKind
  11307. * - BABYLON.VertexBuffer.UV2Kind
  11308. * - BABYLON.VertexBuffer.UV3Kind
  11309. * - BABYLON.VertexBuffer.UV4Kind
  11310. * - BABYLON.VertexBuffer.UV5Kind
  11311. * - BABYLON.VertexBuffer.UV6Kind
  11312. * - BABYLON.VertexBuffer.ColorKind
  11313. * - BABYLON.VertexBuffer.MatricesIndicesKind
  11314. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  11315. * - BABYLON.VertexBuffer.MatricesWeightsKind
  11316. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  11317. *
  11318. * Returns the Mesh.
  11319. */
  11320. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  11321. return null;
  11322. };
  11323. /**
  11324. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  11325. * If the mesh has no geometry, it is simply returned as it is.
  11326. * The `data` are either a numeric array either a Float32Array.
  11327. * No new underlying VertexBuffer object is created.
  11328. * 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.
  11329. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  11330. *
  11331. * Possible `kind` values :
  11332. * - BABYLON.VertexBuffer.PositionKind
  11333. * - BABYLON.VertexBuffer.UVKind
  11334. * - BABYLON.VertexBuffer.UV2Kind
  11335. * - BABYLON.VertexBuffer.UV3Kind
  11336. * - BABYLON.VertexBuffer.UV4Kind
  11337. * - BABYLON.VertexBuffer.UV5Kind
  11338. * - BABYLON.VertexBuffer.UV6Kind
  11339. * - BABYLON.VertexBuffer.ColorKind
  11340. * - BABYLON.VertexBuffer.MatricesIndicesKind
  11341. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  11342. * - BABYLON.VertexBuffer.MatricesWeightsKind
  11343. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  11344. *
  11345. * Returns the Mesh.
  11346. */
  11347. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  11348. return null;
  11349. };
  11350. /**
  11351. * Sets the mesh indices.
  11352. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  11353. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  11354. * This method creates a new index buffer each call.
  11355. * Returns the Mesh.
  11356. */
  11357. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  11358. return null;
  11359. };
  11360. /** Returns false by default, used by the class Mesh.
  11361. * Returns a boolean
  11362. */
  11363. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  11364. return false;
  11365. };
  11366. /**
  11367. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  11368. * Returns a BoundingInfo
  11369. */
  11370. AbstractMesh.prototype.getBoundingInfo = function () {
  11371. if (this._masterMesh) {
  11372. return this._masterMesh.getBoundingInfo();
  11373. }
  11374. if (!this._boundingInfo) {
  11375. this._updateBoundingInfo();
  11376. }
  11377. return this._boundingInfo;
  11378. };
  11379. /**
  11380. * Sets a mesh new object BoundingInfo.
  11381. * Returns the AbstractMesh.
  11382. */
  11383. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  11384. this._boundingInfo = boundingInfo;
  11385. return this;
  11386. };
  11387. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  11388. get: function () {
  11389. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  11390. },
  11391. enumerable: true,
  11392. configurable: true
  11393. });
  11394. AbstractMesh.prototype._preActivate = function () {
  11395. };
  11396. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  11397. };
  11398. AbstractMesh.prototype._activate = function (renderId) {
  11399. this._renderId = renderId;
  11400. };
  11401. /**
  11402. * Returns the last update of the World matrix
  11403. * Returns a Matrix.
  11404. */
  11405. AbstractMesh.prototype.getWorldMatrix = function () {
  11406. if (this._masterMesh) {
  11407. return this._masterMesh.getWorldMatrix();
  11408. }
  11409. if (this._currentRenderId !== this.getScene().getRenderId() || !this.isSynchronized()) {
  11410. this.computeWorldMatrix();
  11411. }
  11412. return this._worldMatrix;
  11413. };
  11414. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  11415. /**
  11416. * Returns directly the last state of the mesh World matrix.
  11417. * A Matrix is returned.
  11418. */
  11419. get: function () {
  11420. return this._worldMatrix;
  11421. },
  11422. enumerable: true,
  11423. configurable: true
  11424. });
  11425. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  11426. /**
  11427. * Returns the current mesh absolute position.
  11428. * Retuns a Vector3.
  11429. */
  11430. get: function () {
  11431. return this._absolutePosition;
  11432. },
  11433. enumerable: true,
  11434. configurable: true
  11435. });
  11436. /**
  11437. * Prevents the World matrix to be computed any longer.
  11438. * Returns the AbstractMesh.
  11439. */
  11440. AbstractMesh.prototype.freezeWorldMatrix = function () {
  11441. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  11442. this.computeWorldMatrix(true);
  11443. this._isWorldMatrixFrozen = true;
  11444. return this;
  11445. };
  11446. /**
  11447. * Allows back the World matrix computation.
  11448. * Returns the AbstractMesh.
  11449. */
  11450. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  11451. this._isWorldMatrixFrozen = false;
  11452. this.computeWorldMatrix(true);
  11453. return this;
  11454. };
  11455. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  11456. /**
  11457. * True if the World matrix has been frozen.
  11458. * Returns a boolean.
  11459. */
  11460. get: function () {
  11461. return this._isWorldMatrixFrozen;
  11462. },
  11463. enumerable: true,
  11464. configurable: true
  11465. });
  11466. /**
  11467. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  11468. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  11469. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  11470. * The passed axis is also normalized.
  11471. * Returns the AbstractMesh.
  11472. */
  11473. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  11474. axis.normalize();
  11475. if (!this.rotationQuaternion) {
  11476. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  11477. this.rotation = BABYLON.Vector3.Zero();
  11478. }
  11479. var rotationQuaternion;
  11480. if (!space || space === BABYLON.Space.LOCAL) {
  11481. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  11482. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  11483. }
  11484. else {
  11485. if (this.parent) {
  11486. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  11487. invertParentWorldMatrix.invert();
  11488. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  11489. }
  11490. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  11491. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  11492. }
  11493. return this;
  11494. };
  11495. /**
  11496. * Translates the mesh along the axis vector for the passed distance in the given space.
  11497. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  11498. * Returns the AbstractMesh.
  11499. */
  11500. AbstractMesh.prototype.translate = function (axis, distance, space) {
  11501. var displacementVector = axis.scale(distance);
  11502. if (!space || space === BABYLON.Space.LOCAL) {
  11503. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  11504. this.setPositionWithLocalVector(tempV3);
  11505. }
  11506. else {
  11507. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  11508. }
  11509. return this;
  11510. };
  11511. /**
  11512. * Adds a rotation step to the mesh current rotation.
  11513. * x, y, z are Euler angles expressed in radians.
  11514. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  11515. * This means this rotation is made in the mesh local space only.
  11516. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  11517. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  11518. * ```javascript
  11519. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  11520. * ```
  11521. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  11522. * 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.
  11523. * Returns the AbstractMesh.
  11524. */
  11525. AbstractMesh.prototype.addRotation = function (x, y, z) {
  11526. var rotationQuaternion;
  11527. if (this.rotationQuaternion) {
  11528. rotationQuaternion = this.rotationQuaternion;
  11529. }
  11530. else {
  11531. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  11532. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  11533. }
  11534. var accumulation = BABYLON.Tmp.Quaternion[0];
  11535. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  11536. rotationQuaternion.multiplyInPlace(accumulation);
  11537. if (!this.rotationQuaternion) {
  11538. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  11539. }
  11540. return this;
  11541. };
  11542. /**
  11543. * Retuns the mesh absolute position in the World.
  11544. * Returns a Vector3.
  11545. */
  11546. AbstractMesh.prototype.getAbsolutePosition = function () {
  11547. this.computeWorldMatrix();
  11548. return this._absolutePosition;
  11549. };
  11550. /**
  11551. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  11552. * Returns the AbstractMesh.
  11553. */
  11554. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  11555. if (!absolutePosition) {
  11556. return;
  11557. }
  11558. var absolutePositionX;
  11559. var absolutePositionY;
  11560. var absolutePositionZ;
  11561. if (absolutePosition.x === undefined) {
  11562. if (arguments.length < 3) {
  11563. return;
  11564. }
  11565. absolutePositionX = arguments[0];
  11566. absolutePositionY = arguments[1];
  11567. absolutePositionZ = arguments[2];
  11568. }
  11569. else {
  11570. absolutePositionX = absolutePosition.x;
  11571. absolutePositionY = absolutePosition.y;
  11572. absolutePositionZ = absolutePosition.z;
  11573. }
  11574. if (this.parent) {
  11575. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  11576. invertParentWorldMatrix.invert();
  11577. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  11578. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  11579. }
  11580. else {
  11581. this.position.x = absolutePositionX;
  11582. this.position.y = absolutePositionY;
  11583. this.position.z = absolutePositionZ;
  11584. }
  11585. return this;
  11586. };
  11587. // ================================== Point of View Movement =================================
  11588. /**
  11589. * Perform relative position change from the point of view of behind the front of the mesh.
  11590. * This is performed taking into account the meshes current rotation, so you do not have to care.
  11591. * Supports definition of mesh facing forward or backward.
  11592. * @param {number} amountRight
  11593. * @param {number} amountUp
  11594. * @param {number} amountForward
  11595. *
  11596. * Returns the AbstractMesh.
  11597. */
  11598. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  11599. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  11600. return this;
  11601. };
  11602. /**
  11603. * Calculate relative position change from the point of view of behind the front of the mesh.
  11604. * This is performed taking into account the meshes current rotation, so you do not have to care.
  11605. * Supports definition of mesh facing forward or backward.
  11606. * @param {number} amountRight
  11607. * @param {number} amountUp
  11608. * @param {number} amountForward
  11609. *
  11610. * Returns a new Vector3.
  11611. */
  11612. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  11613. var rotMatrix = new BABYLON.Matrix();
  11614. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  11615. rotQuaternion.toRotationMatrix(rotMatrix);
  11616. var translationDelta = BABYLON.Vector3.Zero();
  11617. var defForwardMult = this.definedFacingForward ? -1 : 1;
  11618. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  11619. return translationDelta;
  11620. };
  11621. // ================================== Point of View Rotation =================================
  11622. /**
  11623. * Perform relative rotation change from the point of view of behind the front of the mesh.
  11624. * Supports definition of mesh facing forward or backward.
  11625. * @param {number} flipBack
  11626. * @param {number} twirlClockwise
  11627. * @param {number} tiltRight
  11628. *
  11629. * Returns the AbstractMesh.
  11630. */
  11631. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  11632. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  11633. return this;
  11634. };
  11635. /**
  11636. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  11637. * Supports definition of mesh facing forward or backward.
  11638. * @param {number} flipBack
  11639. * @param {number} twirlClockwise
  11640. * @param {number} tiltRight
  11641. *
  11642. * Returns a new Vector3.
  11643. */
  11644. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  11645. var defForwardMult = this.definedFacingForward ? 1 : -1;
  11646. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  11647. };
  11648. /**
  11649. * Sets a new pivot matrix to the mesh.
  11650. * Returns the AbstractMesh.
  11651. */
  11652. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  11653. this._pivotMatrix = matrix;
  11654. this._cache.pivotMatrixUpdated = true;
  11655. return this;
  11656. };
  11657. /**
  11658. * Returns the mesh pivot matrix.
  11659. * Default : Identity.
  11660. * A Matrix is returned.
  11661. */
  11662. AbstractMesh.prototype.getPivotMatrix = function () {
  11663. return this._pivotMatrix;
  11664. };
  11665. AbstractMesh.prototype._isSynchronized = function () {
  11666. if (this._isDirty) {
  11667. return false;
  11668. }
  11669. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  11670. return false;
  11671. if (this._cache.pivotMatrixUpdated) {
  11672. return false;
  11673. }
  11674. if (this.infiniteDistance) {
  11675. return false;
  11676. }
  11677. if (!this._cache.position.equals(this.position))
  11678. return false;
  11679. if (this.rotationQuaternion) {
  11680. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  11681. return false;
  11682. }
  11683. if (!this._cache.rotation.equals(this.rotation))
  11684. return false;
  11685. if (!this._cache.scaling.equals(this.scaling))
  11686. return false;
  11687. return true;
  11688. };
  11689. AbstractMesh.prototype._initCache = function () {
  11690. _super.prototype._initCache.call(this);
  11691. this._cache.localMatrixUpdated = false;
  11692. this._cache.position = BABYLON.Vector3.Zero();
  11693. this._cache.scaling = BABYLON.Vector3.Zero();
  11694. this._cache.rotation = BABYLON.Vector3.Zero();
  11695. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  11696. this._cache.billboardMode = -1;
  11697. };
  11698. AbstractMesh.prototype.markAsDirty = function (property) {
  11699. if (property === "rotation") {
  11700. this.rotationQuaternion = null;
  11701. }
  11702. this._currentRenderId = Number.MAX_VALUE;
  11703. this._isDirty = true;
  11704. return this;
  11705. };
  11706. /**
  11707. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  11708. * Returns the AbstractMesh.
  11709. */
  11710. AbstractMesh.prototype._updateBoundingInfo = function () {
  11711. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  11712. this._boundingInfo.update(this.worldMatrixFromCache);
  11713. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  11714. return this;
  11715. };
  11716. /**
  11717. * Update a mesh's children BoundingInfo objects only.
  11718. * Returns the AbstractMesh.
  11719. */
  11720. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  11721. if (!this.subMeshes) {
  11722. return;
  11723. }
  11724. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  11725. var subMesh = this.subMeshes[subIndex];
  11726. if (!subMesh.IsGlobal) {
  11727. subMesh.updateBoundingInfo(matrix);
  11728. }
  11729. }
  11730. return this;
  11731. };
  11732. /**
  11733. * Computes the mesh World matrix and returns it.
  11734. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  11735. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  11736. * If the parameter `force`is set to `true`, the actual computation is done.
  11737. * Returns the mesh World Matrix.
  11738. */
  11739. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  11740. if (this._isWorldMatrixFrozen) {
  11741. return this._worldMatrix;
  11742. }
  11743. if (!force && this.isSynchronized(true)) {
  11744. this._currentRenderId = this.getScene().getRenderId();
  11745. return this._worldMatrix;
  11746. }
  11747. this._cache.position.copyFrom(this.position);
  11748. this._cache.scaling.copyFrom(this.scaling);
  11749. this._cache.pivotMatrixUpdated = false;
  11750. this._cache.billboardMode = this.billboardMode;
  11751. this._currentRenderId = this.getScene().getRenderId();
  11752. this._isDirty = false;
  11753. // Scaling
  11754. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  11755. // Rotation
  11756. //rotate, if quaternion is set and rotation was used
  11757. if (this.rotationQuaternion) {
  11758. var len = this.rotation.length();
  11759. if (len) {
  11760. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  11761. this.rotation.copyFromFloats(0, 0, 0);
  11762. }
  11763. }
  11764. if (this.rotationQuaternion) {
  11765. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  11766. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  11767. }
  11768. else {
  11769. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  11770. this._cache.rotation.copyFrom(this.rotation);
  11771. }
  11772. // Translation
  11773. if (this.infiniteDistance && !this.parent) {
  11774. var camera = this.getScene().activeCamera;
  11775. if (camera) {
  11776. var cameraWorldMatrix = camera.getWorldMatrix();
  11777. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  11778. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  11779. }
  11780. }
  11781. else {
  11782. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  11783. }
  11784. // Composing transformations
  11785. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  11786. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  11787. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  11788. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  11789. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  11790. // Need to decompose each rotation here
  11791. var currentPosition = BABYLON.Tmp.Vector3[3];
  11792. if (this.parent && this.parent.getWorldMatrix) {
  11793. if (this._meshToBoneReferal) {
  11794. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  11795. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  11796. }
  11797. else {
  11798. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  11799. }
  11800. }
  11801. else {
  11802. currentPosition.copyFrom(this.position);
  11803. }
  11804. currentPosition.subtractInPlace(this.getScene().activeCamera.globalPosition);
  11805. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  11806. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_X) === AbstractMesh.BILLBOARDMODE_X) {
  11807. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  11808. }
  11809. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Y) === AbstractMesh.BILLBOARDMODE_Y) {
  11810. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  11811. }
  11812. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Z) === AbstractMesh.BILLBOARDMODE_Z) {
  11813. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  11814. }
  11815. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  11816. }
  11817. else {
  11818. BABYLON.Tmp.Matrix[1].copyFrom(this.getScene().activeCamera.getViewMatrix());
  11819. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  11820. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  11821. }
  11822. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  11823. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  11824. }
  11825. // Local world
  11826. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  11827. // Parent
  11828. if (this.parent && this.parent.getWorldMatrix) {
  11829. this._markSyncedWithParent();
  11830. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE) {
  11831. if (this._meshToBoneReferal) {
  11832. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  11833. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  11834. }
  11835. else {
  11836. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  11837. }
  11838. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  11839. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  11840. this._worldMatrix.copyFrom(this._localWorld);
  11841. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  11842. }
  11843. else {
  11844. if (this._meshToBoneReferal) {
  11845. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  11846. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  11847. }
  11848. else {
  11849. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  11850. }
  11851. }
  11852. }
  11853. else {
  11854. this._worldMatrix.copyFrom(this._localWorld);
  11855. }
  11856. // Bounding info
  11857. this._updateBoundingInfo();
  11858. // Absolute position
  11859. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  11860. // Callbacks
  11861. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  11862. if (!this._poseMatrix) {
  11863. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  11864. }
  11865. return this._worldMatrix;
  11866. };
  11867. /**
  11868. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  11869. * @param func: callback function to add
  11870. *
  11871. * Returns the AbstractMesh.
  11872. */
  11873. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  11874. this.onAfterWorldMatrixUpdateObservable.add(func);
  11875. return this;
  11876. };
  11877. /**
  11878. * Removes a registered callback function.
  11879. * Returns the AbstractMesh.
  11880. */
  11881. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  11882. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  11883. return this;
  11884. };
  11885. /**
  11886. * Sets the mesh position in its local space.
  11887. * Returns the AbstractMesh.
  11888. */
  11889. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  11890. this.computeWorldMatrix();
  11891. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  11892. return this;
  11893. };
  11894. /**
  11895. * Returns the mesh position in the local space from the current World matrix values.
  11896. * Returns a new Vector3.
  11897. */
  11898. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  11899. this.computeWorldMatrix();
  11900. var invLocalWorldMatrix = this._localWorld.clone();
  11901. invLocalWorldMatrix.invert();
  11902. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  11903. };
  11904. /**
  11905. * Translates the mesh along the passed Vector3 in its local space.
  11906. * Returns the AbstractMesh.
  11907. */
  11908. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  11909. this.computeWorldMatrix(true);
  11910. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  11911. return this;
  11912. };
  11913. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  11914. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  11915. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  11916. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  11917. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  11918. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  11919. /// <returns>Mesh oriented towards targetMesh</returns>
  11920. if (yawCor === void 0) { yawCor = 0; }
  11921. if (pitchCor === void 0) { pitchCor = 0; }
  11922. if (rollCor === void 0) { rollCor = 0; }
  11923. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  11924. var dv = AbstractMesh._lookAtVectorCache;
  11925. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  11926. targetPoint.subtractToRef(pos, dv);
  11927. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  11928. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  11929. var pitch = Math.atan2(dv.y, len);
  11930. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  11931. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  11932. return this;
  11933. };
  11934. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  11935. this._meshToBoneReferal = affectedMesh;
  11936. this.parent = bone;
  11937. if (bone.getWorldMatrix().determinant() < 0) {
  11938. this.scalingDeterminant *= -1;
  11939. }
  11940. return this;
  11941. };
  11942. AbstractMesh.prototype.detachFromBone = function () {
  11943. if (this.parent.getWorldMatrix().determinant() < 0) {
  11944. this.scalingDeterminant *= -1;
  11945. }
  11946. this._meshToBoneReferal = null;
  11947. this.parent = null;
  11948. return this;
  11949. };
  11950. /**
  11951. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  11952. * A mesh is in the frustum if its bounding box intersects the frustum.
  11953. * Boolean returned.
  11954. */
  11955. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  11956. return this._boundingInfo.isInFrustum(frustumPlanes);
  11957. };
  11958. /**
  11959. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  11960. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  11961. * Boolean returned.
  11962. */
  11963. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  11964. return this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  11965. ;
  11966. };
  11967. /**
  11968. * True if the mesh intersects another mesh or a SolidParticle object.
  11969. * 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)
  11970. * Returns a boolean.
  11971. */
  11972. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  11973. if (!this._boundingInfo || !mesh._boundingInfo) {
  11974. return false;
  11975. }
  11976. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  11977. };
  11978. /**
  11979. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  11980. * Returns a boolean.
  11981. */
  11982. AbstractMesh.prototype.intersectsPoint = function (point) {
  11983. if (!this._boundingInfo) {
  11984. return false;
  11985. }
  11986. return this._boundingInfo.intersectsPoint(point);
  11987. };
  11988. AbstractMesh.prototype.getPhysicsImpostor = function () {
  11989. return this.physicsImpostor;
  11990. };
  11991. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  11992. if (!camera) {
  11993. camera = this.getScene().activeCamera;
  11994. }
  11995. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  11996. };
  11997. /**
  11998. * Returns the distance from the mesh to the active camera.
  11999. * Returns a float.
  12000. */
  12001. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  12002. if (!camera) {
  12003. camera = this.getScene().activeCamera;
  12004. }
  12005. return this.absolutePosition.subtract(camera.position).length();
  12006. };
  12007. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  12008. if (!this.physicsImpostor) {
  12009. return;
  12010. }
  12011. this.physicsImpostor.applyImpulse(force, contactPoint);
  12012. return this;
  12013. };
  12014. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  12015. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  12016. return;
  12017. }
  12018. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  12019. mainPivot: pivot1,
  12020. connectedPivot: pivot2,
  12021. nativeParams: options
  12022. });
  12023. return this;
  12024. };
  12025. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  12026. // Collisions
  12027. /**
  12028. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  12029. * Default `false`.
  12030. */
  12031. get: function () {
  12032. return this._checkCollisions;
  12033. },
  12034. set: function (collisionEnabled) {
  12035. this._checkCollisions = collisionEnabled;
  12036. if (this.getScene().workerCollisions) {
  12037. this.getScene().collisionCoordinator.onMeshUpdated(this);
  12038. }
  12039. },
  12040. enumerable: true,
  12041. configurable: true
  12042. });
  12043. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  12044. var globalPosition = this.getAbsolutePosition();
  12045. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  12046. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  12047. if (!this._collider) {
  12048. this._collider = new BABYLON.Collider();
  12049. }
  12050. this._collider.radius = this.ellipsoid;
  12051. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  12052. return this;
  12053. };
  12054. // Submeshes octree
  12055. /**
  12056. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  12057. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  12058. * Returns an Octree of submeshes.
  12059. */
  12060. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  12061. if (maxCapacity === void 0) { maxCapacity = 64; }
  12062. if (maxDepth === void 0) { maxDepth = 2; }
  12063. if (!this._submeshesOctree) {
  12064. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  12065. }
  12066. this.computeWorldMatrix(true);
  12067. // Update octree
  12068. var bbox = this.getBoundingInfo().boundingBox;
  12069. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  12070. return this._submeshesOctree;
  12071. };
  12072. // Collisions
  12073. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  12074. this._generatePointsArray();
  12075. // Transformation
  12076. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  12077. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  12078. subMesh._lastColliderWorldVertices = [];
  12079. subMesh._trianglePlanes = [];
  12080. var start = subMesh.verticesStart;
  12081. var end = (subMesh.verticesStart + subMesh.verticesCount);
  12082. for (var i = start; i < end; i++) {
  12083. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  12084. }
  12085. }
  12086. // Collide
  12087. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  12088. if (collider.collisionFound) {
  12089. collider.collidedMesh = this;
  12090. }
  12091. return this;
  12092. };
  12093. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  12094. var subMeshes;
  12095. var len;
  12096. // Octrees
  12097. if (this._submeshesOctree && this.useOctreeForCollisions) {
  12098. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  12099. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  12100. len = intersections.length;
  12101. subMeshes = intersections.data;
  12102. }
  12103. else {
  12104. subMeshes = this.subMeshes;
  12105. len = subMeshes.length;
  12106. }
  12107. for (var index = 0; index < len; index++) {
  12108. var subMesh = subMeshes[index];
  12109. // Bounding test
  12110. if (len > 1 && !subMesh._checkCollision(collider))
  12111. continue;
  12112. this._collideForSubMesh(subMesh, transformMatrix, collider);
  12113. }
  12114. return this;
  12115. };
  12116. AbstractMesh.prototype._checkCollision = function (collider) {
  12117. // Bounding box test
  12118. if (!this._boundingInfo._checkCollision(collider))
  12119. return this;
  12120. // Transformation matrix
  12121. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  12122. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  12123. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  12124. return this;
  12125. };
  12126. // Picking
  12127. AbstractMesh.prototype._generatePointsArray = function () {
  12128. return false;
  12129. };
  12130. /**
  12131. * Checks if the passed Ray intersects with the mesh.
  12132. * Returns an object PickingInfo.
  12133. */
  12134. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  12135. var pickingInfo = new BABYLON.PickingInfo();
  12136. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  12137. return pickingInfo;
  12138. }
  12139. if (!this._generatePointsArray()) {
  12140. return pickingInfo;
  12141. }
  12142. var intersectInfo = null;
  12143. // Octrees
  12144. var subMeshes;
  12145. var len;
  12146. if (this._submeshesOctree && this.useOctreeForPicking) {
  12147. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  12148. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  12149. len = intersections.length;
  12150. subMeshes = intersections.data;
  12151. }
  12152. else {
  12153. subMeshes = this.subMeshes;
  12154. len = subMeshes.length;
  12155. }
  12156. for (var index = 0; index < len; index++) {
  12157. var subMesh = subMeshes[index];
  12158. // Bounding test
  12159. if (len > 1 && !subMesh.canIntersects(ray))
  12160. continue;
  12161. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  12162. if (currentIntersectInfo) {
  12163. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  12164. intersectInfo = currentIntersectInfo;
  12165. intersectInfo.subMeshId = index;
  12166. if (fastCheck) {
  12167. break;
  12168. }
  12169. }
  12170. }
  12171. }
  12172. if (intersectInfo) {
  12173. // Get picked point
  12174. var world = this.getWorldMatrix();
  12175. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  12176. var direction = ray.direction.clone();
  12177. direction = direction.scale(intersectInfo.distance);
  12178. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  12179. var pickedPoint = worldOrigin.add(worldDirection);
  12180. // Return result
  12181. pickingInfo.hit = true;
  12182. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  12183. pickingInfo.pickedPoint = pickedPoint;
  12184. pickingInfo.pickedMesh = this;
  12185. pickingInfo.bu = intersectInfo.bu;
  12186. pickingInfo.bv = intersectInfo.bv;
  12187. pickingInfo.faceId = intersectInfo.faceId;
  12188. pickingInfo.subMeshId = intersectInfo.subMeshId;
  12189. return pickingInfo;
  12190. }
  12191. return pickingInfo;
  12192. };
  12193. /**
  12194. * Clones the mesh, used by the class Mesh.
  12195. * Just returns `null` for an AbstractMesh.
  12196. */
  12197. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  12198. return null;
  12199. };
  12200. /**
  12201. * Disposes all the mesh submeshes.
  12202. * Returns the AbstractMesh.
  12203. */
  12204. AbstractMesh.prototype.releaseSubMeshes = function () {
  12205. if (this.subMeshes) {
  12206. while (this.subMeshes.length) {
  12207. this.subMeshes[0].dispose();
  12208. }
  12209. }
  12210. else {
  12211. this.subMeshes = new Array();
  12212. }
  12213. return this;
  12214. };
  12215. /**
  12216. * Disposes the AbstractMesh.
  12217. * Some internal references are kept for further use.
  12218. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  12219. * Returns nothing.
  12220. */
  12221. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  12222. var _this = this;
  12223. var index;
  12224. // Action manager
  12225. if (this.actionManager) {
  12226. this.actionManager.dispose();
  12227. this.actionManager = null;
  12228. }
  12229. // Skeleton
  12230. this.skeleton = null;
  12231. // Animations
  12232. this.getScene().stopAnimation(this);
  12233. // Physics
  12234. if (this.physicsImpostor) {
  12235. this.physicsImpostor.dispose();
  12236. }
  12237. // Intersections in progress
  12238. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  12239. var other = this._intersectionsInProgress[index];
  12240. var pos = other._intersectionsInProgress.indexOf(this);
  12241. other._intersectionsInProgress.splice(pos, 1);
  12242. }
  12243. this._intersectionsInProgress = [];
  12244. // Lights
  12245. var lights = this.getScene().lights;
  12246. lights.forEach(function (light) {
  12247. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  12248. if (meshIndex !== -1) {
  12249. light.includedOnlyMeshes.splice(meshIndex, 1);
  12250. }
  12251. meshIndex = light.excludedMeshes.indexOf(_this);
  12252. if (meshIndex !== -1) {
  12253. light.excludedMeshes.splice(meshIndex, 1);
  12254. }
  12255. // Shadow generators
  12256. var generator = light.getShadowGenerator();
  12257. if (generator) {
  12258. meshIndex = generator.getShadowMap().renderList.indexOf(_this);
  12259. if (meshIndex !== -1) {
  12260. generator.getShadowMap().renderList.splice(meshIndex, 1);
  12261. }
  12262. }
  12263. });
  12264. // Edges
  12265. if (this._edgesRenderer) {
  12266. this._edgesRenderer.dispose();
  12267. this._edgesRenderer = null;
  12268. }
  12269. // SubMeshes
  12270. if (this.getClassName() !== "InstancedMesh") {
  12271. this.releaseSubMeshes();
  12272. }
  12273. // Octree
  12274. var sceneOctree = this.getScene().selectionOctree;
  12275. if (sceneOctree) {
  12276. var index = sceneOctree.dynamicContent.indexOf(this);
  12277. if (index !== -1) {
  12278. sceneOctree.dynamicContent.splice(index, 1);
  12279. }
  12280. }
  12281. // Engine
  12282. this.getScene().getEngine().wipeCaches();
  12283. // Remove from scene
  12284. this.getScene().removeMesh(this);
  12285. if (!doNotRecurse) {
  12286. // Particles
  12287. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  12288. if (this.getScene().particleSystems[index].emitter === this) {
  12289. this.getScene().particleSystems[index].dispose();
  12290. index--;
  12291. }
  12292. }
  12293. // Children
  12294. var objects = this.getDescendants(true);
  12295. for (index = 0; index < objects.length; index++) {
  12296. objects[index].dispose();
  12297. }
  12298. }
  12299. else {
  12300. var childMeshes = this.getChildMeshes(true);
  12301. for (index = 0; index < childMeshes.length; index++) {
  12302. var child = childMeshes[index];
  12303. child.parent = null;
  12304. child.computeWorldMatrix(true);
  12305. }
  12306. }
  12307. // facet data
  12308. if (this._facetDataEnabled) {
  12309. this.disableFacetData();
  12310. }
  12311. this.onAfterWorldMatrixUpdateObservable.clear();
  12312. this.onCollideObservable.clear();
  12313. this.onCollisionPositionChangeObservable.clear();
  12314. this._isDisposed = true;
  12315. _super.prototype.dispose.call(this);
  12316. };
  12317. /**
  12318. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  12319. * This Vector3 is expressed in the World space.
  12320. */
  12321. AbstractMesh.prototype.getDirection = function (localAxis) {
  12322. var result = BABYLON.Vector3.Zero();
  12323. this.getDirectionToRef(localAxis, result);
  12324. return result;
  12325. };
  12326. /**
  12327. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  12328. * localAxis is expressed in the mesh local space.
  12329. * result is computed in the Wordl space from the mesh World matrix.
  12330. * Returns the AbstractMesh.
  12331. */
  12332. AbstractMesh.prototype.getDirectionToRef = function (localAxis, result) {
  12333. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  12334. return this;
  12335. };
  12336. AbstractMesh.prototype.setPivotPoint = function (point, space) {
  12337. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  12338. if (this.getScene().getRenderId() == 0) {
  12339. this.computeWorldMatrix(true);
  12340. }
  12341. var wm = this.getWorldMatrix();
  12342. if (space == BABYLON.Space.WORLD) {
  12343. var tmat = BABYLON.Tmp.Matrix[0];
  12344. wm.invertToRef(tmat);
  12345. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  12346. }
  12347. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  12348. this._pivotMatrix.m[12] = -point.x;
  12349. this._pivotMatrix.m[13] = -point.y;
  12350. this._pivotMatrix.m[14] = -point.z;
  12351. this._cache.pivotMatrixUpdated = true;
  12352. return this;
  12353. };
  12354. /**
  12355. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  12356. */
  12357. AbstractMesh.prototype.getPivotPoint = function () {
  12358. var point = BABYLON.Vector3.Zero();
  12359. this.getPivotPointToRef(point);
  12360. return point;
  12361. };
  12362. /**
  12363. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  12364. * Returns the AbstractMesh.
  12365. */
  12366. AbstractMesh.prototype.getPivotPointToRef = function (result) {
  12367. result.x = -this._pivotMatrix.m[12];
  12368. result.y = -this._pivotMatrix.m[13];
  12369. result.z = -this._pivotMatrix.m[14];
  12370. return this;
  12371. };
  12372. /**
  12373. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  12374. */
  12375. AbstractMesh.prototype.getAbsolutePivotPoint = function () {
  12376. var point = BABYLON.Vector3.Zero();
  12377. this.getAbsolutePivotPointToRef(point);
  12378. return point;
  12379. };
  12380. /**
  12381. * Defines the passed mesh as the parent of the current mesh.
  12382. * Returns the AbstractMesh.
  12383. */
  12384. AbstractMesh.prototype.setParent = function (mesh) {
  12385. var child = this;
  12386. var parent = mesh;
  12387. if (mesh == null) {
  12388. var rotation = BABYLON.Tmp.Quaternion[0];
  12389. var position = BABYLON.Tmp.Vector3[0];
  12390. var scale = BABYLON.Tmp.Vector3[1];
  12391. child.getWorldMatrix().decompose(scale, rotation, position);
  12392. if (child.rotationQuaternion) {
  12393. child.rotationQuaternion.copyFrom(rotation);
  12394. }
  12395. else {
  12396. rotation.toEulerAnglesToRef(child.rotation);
  12397. }
  12398. child.position.x = position.x;
  12399. child.position.y = position.y;
  12400. child.position.z = position.z;
  12401. }
  12402. else {
  12403. var rotation = BABYLON.Tmp.Quaternion[0];
  12404. var position = BABYLON.Tmp.Vector3[0];
  12405. var scale = BABYLON.Tmp.Vector3[1];
  12406. var m1 = BABYLON.Tmp.Matrix[0];
  12407. var m2 = BABYLON.Tmp.Matrix[1];
  12408. parent.getWorldMatrix().decompose(scale, rotation, position);
  12409. rotation.toRotationMatrix(m1);
  12410. m2.setTranslation(position);
  12411. m2.multiplyToRef(m1, m1);
  12412. var invParentMatrix = BABYLON.Matrix.Invert(m1);
  12413. var m = child.getWorldMatrix().multiply(invParentMatrix);
  12414. m.decompose(scale, rotation, position);
  12415. if (child.rotationQuaternion) {
  12416. child.rotationQuaternion.copyFrom(rotation);
  12417. }
  12418. else {
  12419. rotation.toEulerAnglesToRef(child.rotation);
  12420. }
  12421. invParentMatrix = BABYLON.Matrix.Invert(parent.getWorldMatrix());
  12422. var m = child.getWorldMatrix().multiply(invParentMatrix);
  12423. m.decompose(scale, rotation, position);
  12424. child.position.x = position.x;
  12425. child.position.y = position.y;
  12426. child.position.z = position.z;
  12427. }
  12428. child.parent = parent;
  12429. return this;
  12430. };
  12431. /**
  12432. * Adds the passed mesh as a child to the current mesh.
  12433. * Returns the AbstractMesh.
  12434. */
  12435. AbstractMesh.prototype.addChild = function (mesh) {
  12436. mesh.setParent(this);
  12437. return this;
  12438. };
  12439. /**
  12440. * Removes the passed mesh from the current mesh children list.
  12441. * Returns the AbstractMesh.
  12442. */
  12443. AbstractMesh.prototype.removeChild = function (mesh) {
  12444. mesh.setParent(null);
  12445. return this;
  12446. };
  12447. /**
  12448. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  12449. * Returns the AbstractMesh.
  12450. */
  12451. AbstractMesh.prototype.getAbsolutePivotPointToRef = function (result) {
  12452. result.x = this._pivotMatrix.m[12];
  12453. result.y = this._pivotMatrix.m[13];
  12454. result.z = this._pivotMatrix.m[14];
  12455. this.getPivotPointToRef(result);
  12456. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  12457. return this;
  12458. };
  12459. // Facet data
  12460. /**
  12461. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  12462. * Returns the AbstractMesh.
  12463. */
  12464. AbstractMesh.prototype._initFacetData = function () {
  12465. if (!this._facetNormals) {
  12466. this._facetNormals = new Array();
  12467. }
  12468. if (!this._facetPositions) {
  12469. this._facetPositions = new Array();
  12470. }
  12471. if (!this._facetPartitioning) {
  12472. this._facetPartitioning = new Array();
  12473. }
  12474. this._facetNb = this.getIndices().length / 3;
  12475. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  12476. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  12477. for (var f = 0; f < this._facetNb; f++) {
  12478. this._facetNormals[f] = BABYLON.Vector3.Zero();
  12479. this._facetPositions[f] = BABYLON.Vector3.Zero();
  12480. }
  12481. this._facetDataEnabled = true;
  12482. return this;
  12483. };
  12484. /**
  12485. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  12486. * This method can be called within the render loop.
  12487. * 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.
  12488. * Returns the AbstractMesh.
  12489. */
  12490. AbstractMesh.prototype.updateFacetData = function () {
  12491. if (!this._facetDataEnabled) {
  12492. this._initFacetData();
  12493. }
  12494. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  12495. var indices = this.getIndices();
  12496. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  12497. var bInfo = this.getBoundingInfo();
  12498. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  12499. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  12500. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  12501. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  12502. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  12503. this._subDiv.max = this._partitioningSubdivisions;
  12504. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  12505. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  12506. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  12507. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  12508. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  12509. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  12510. // set the parameters for ComputeNormals()
  12511. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  12512. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  12513. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  12514. this._facetParameters.bInfo = bInfo;
  12515. this._facetParameters.bbSize = this._bbSize;
  12516. this._facetParameters.subDiv = this._subDiv;
  12517. this._facetParameters.ratio = this.partitioningBBoxRatio;
  12518. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  12519. return this;
  12520. };
  12521. /**
  12522. * Returns the facetLocalNormals array.
  12523. * The normals are expressed in the mesh local space.
  12524. */
  12525. AbstractMesh.prototype.getFacetLocalNormals = function () {
  12526. if (!this._facetNormals) {
  12527. this.updateFacetData();
  12528. }
  12529. return this._facetNormals;
  12530. };
  12531. /**
  12532. * Returns the facetLocalPositions array.
  12533. * The facet positions are expressed in the mesh local space.
  12534. */
  12535. AbstractMesh.prototype.getFacetLocalPositions = function () {
  12536. if (!this._facetPositions) {
  12537. this.updateFacetData();
  12538. }
  12539. return this._facetPositions;
  12540. };
  12541. /**
  12542. * Returns the facetLocalPartioning array.
  12543. */
  12544. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  12545. if (!this._facetPartitioning) {
  12546. this.updateFacetData();
  12547. }
  12548. return this._facetPartitioning;
  12549. };
  12550. /**
  12551. * Returns the i-th facet position in the world system.
  12552. * This method allocates a new Vector3 per call.
  12553. */
  12554. AbstractMesh.prototype.getFacetPosition = function (i) {
  12555. var pos = BABYLON.Vector3.Zero();
  12556. this.getFacetPositionToRef(i, pos);
  12557. return pos;
  12558. };
  12559. /**
  12560. * Sets the reference Vector3 with the i-th facet position in the world system.
  12561. * Returns the AbstractMesh.
  12562. */
  12563. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  12564. var localPos = (this.getFacetLocalPositions())[i];
  12565. var world = this.getWorldMatrix();
  12566. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  12567. return this;
  12568. };
  12569. /**
  12570. * Returns the i-th facet normal in the world system.
  12571. * This method allocates a new Vector3 per call.
  12572. */
  12573. AbstractMesh.prototype.getFacetNormal = function (i) {
  12574. var norm = BABYLON.Vector3.Zero();
  12575. this.getFacetNormalToRef(i, norm);
  12576. return norm;
  12577. };
  12578. /**
  12579. * Sets the reference Vector3 with the i-th facet normal in the world system.
  12580. * Returns the AbstractMesh.
  12581. */
  12582. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  12583. var localNorm = (this.getFacetLocalNormals())[i];
  12584. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  12585. return this;
  12586. };
  12587. /**
  12588. * 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).
  12589. */
  12590. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  12591. var bInfo = this.getBoundingInfo();
  12592. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  12593. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  12594. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  12595. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  12596. return null;
  12597. }
  12598. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  12599. };
  12600. /**
  12601. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  12602. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  12603. * 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.
  12604. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  12605. * 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.
  12606. */
  12607. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  12608. if (checkFace === void 0) { checkFace = false; }
  12609. if (facing === void 0) { facing = true; }
  12610. var world = this.getWorldMatrix();
  12611. var invMat = BABYLON.Tmp.Matrix[5];
  12612. world.invertToRef(invMat);
  12613. var invVect = BABYLON.Tmp.Vector3[8];
  12614. var closest = null;
  12615. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  12616. closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  12617. if (projected) {
  12618. // tranform the local computed projected vector to world coordinates
  12619. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  12620. }
  12621. return closest;
  12622. };
  12623. /**
  12624. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  12625. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  12626. * 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.
  12627. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  12628. * 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.
  12629. */
  12630. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  12631. if (checkFace === void 0) { checkFace = false; }
  12632. if (facing === void 0) { facing = true; }
  12633. var closest = null;
  12634. var tmpx = 0.0;
  12635. var tmpy = 0.0;
  12636. var tmpz = 0.0;
  12637. var d = 0.0; // tmp dot facet normal * facet position
  12638. var t0 = 0.0;
  12639. var projx = 0.0;
  12640. var projy = 0.0;
  12641. var projz = 0.0;
  12642. // Get all the facets in the same partitioning block than (x, y, z)
  12643. var facetPositions = this.getFacetLocalPositions();
  12644. var facetNormals = this.getFacetLocalNormals();
  12645. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  12646. if (!facetsInBlock) {
  12647. return null;
  12648. }
  12649. // Get the closest facet to (x, y, z)
  12650. var shortest = Number.MAX_VALUE; // init distance vars
  12651. var tmpDistance = shortest;
  12652. var fib; // current facet in the block
  12653. var norm; // current facet normal
  12654. var p0; // current facet barycenter position
  12655. // loop on all the facets in the current partitioning block
  12656. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  12657. fib = facetsInBlock[idx];
  12658. norm = facetNormals[fib];
  12659. p0 = facetPositions[fib];
  12660. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  12661. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  12662. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  12663. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  12664. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  12665. projx = x + norm.x * t0;
  12666. projy = y + norm.y * t0;
  12667. projz = z + norm.z * t0;
  12668. tmpx = projx - x;
  12669. tmpy = projy - y;
  12670. tmpz = projz - z;
  12671. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  12672. if (tmpDistance < shortest) {
  12673. shortest = tmpDistance;
  12674. closest = fib;
  12675. if (projected) {
  12676. projected.x = projx;
  12677. projected.y = projy;
  12678. projected.z = projz;
  12679. }
  12680. }
  12681. }
  12682. }
  12683. return closest;
  12684. };
  12685. /**
  12686. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  12687. */
  12688. AbstractMesh.prototype.getFacetDataParameters = function () {
  12689. return this._facetParameters;
  12690. };
  12691. /**
  12692. * Disables the feature FacetData and frees the related memory.
  12693. * Returns the AbstractMesh.
  12694. */
  12695. AbstractMesh.prototype.disableFacetData = function () {
  12696. if (this._facetDataEnabled) {
  12697. this._facetDataEnabled = false;
  12698. this._facetPositions = null;
  12699. this._facetNormals = null;
  12700. this._facetPartitioning = null;
  12701. this._facetParameters = null;
  12702. }
  12703. return this;
  12704. };
  12705. /**
  12706. * Creates new normals data for the mesh.
  12707. * @param updatable.
  12708. */
  12709. AbstractMesh.prototype.createNormals = function (updatable) {
  12710. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  12711. var indices = this.getIndices();
  12712. var normals;
  12713. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  12714. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  12715. }
  12716. else {
  12717. normals = [];
  12718. }
  12719. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  12720. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  12721. };
  12722. return AbstractMesh;
  12723. }(BABYLON.Node));
  12724. // Statics
  12725. AbstractMesh._BILLBOARDMODE_NONE = 0;
  12726. AbstractMesh._BILLBOARDMODE_X = 1;
  12727. AbstractMesh._BILLBOARDMODE_Y = 2;
  12728. AbstractMesh._BILLBOARDMODE_Z = 4;
  12729. AbstractMesh._BILLBOARDMODE_ALL = 7;
  12730. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  12731. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  12732. BABYLON.AbstractMesh = AbstractMesh;
  12733. })(BABYLON || (BABYLON = {}));
  12734. //# sourceMappingURL=babylon.abstractMesh.js.map
  12735. var BABYLON;
  12736. (function (BABYLON) {
  12737. var Light = (function (_super) {
  12738. __extends(Light, _super);
  12739. /**
  12740. * Creates a Light object in the scene.
  12741. * Documentation : http://doc.babylonjs.com/tutorials/lights
  12742. */
  12743. function Light(name, scene) {
  12744. var _this = _super.call(this, name, scene) || this;
  12745. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  12746. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  12747. _this.intensity = 1.0;
  12748. _this.range = Number.MAX_VALUE;
  12749. _this._excludeWithLayerMask = 0;
  12750. _this._includeOnlyWithLayerMask = 0;
  12751. _this._lightmapMode = 0;
  12752. // PBR Properties.
  12753. _this.radius = 0.00001;
  12754. _this._excludedMeshesIds = new Array();
  12755. _this._includedOnlyMeshesIds = new Array();
  12756. _this.getScene().addLight(_this);
  12757. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  12758. _this._buildUniformLayout();
  12759. _this.includedOnlyMeshes = new Array();
  12760. _this.excludedMeshes = new Array();
  12761. _this._resyncMeshes();
  12762. return _this;
  12763. }
  12764. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  12765. /**
  12766. * If every light affecting the material is in this lightmapMode,
  12767. * material.lightmapTexture adds or multiplies
  12768. * (depends on material.useLightmapAsShadowmap)
  12769. * after every other light calculations.
  12770. */
  12771. get: function () {
  12772. return Light._LIGHTMAP_DEFAULT;
  12773. },
  12774. enumerable: true,
  12775. configurable: true
  12776. });
  12777. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  12778. /**
  12779. * material.lightmapTexture as only diffuse lighting from this light
  12780. * adds pnly specular lighting from this light
  12781. * adds dynamic shadows
  12782. */
  12783. get: function () {
  12784. return Light._LIGHTMAP_SPECULAR;
  12785. },
  12786. enumerable: true,
  12787. configurable: true
  12788. });
  12789. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  12790. /**
  12791. * material.lightmapTexture as only lighting
  12792. * no light calculation from this light
  12793. * only adds dynamic shadows from this light
  12794. */
  12795. get: function () {
  12796. return Light._LIGHTMAP_SHADOWSONLY;
  12797. },
  12798. enumerable: true,
  12799. configurable: true
  12800. });
  12801. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  12802. get: function () {
  12803. return this._includedOnlyMeshes;
  12804. },
  12805. set: function (value) {
  12806. this._includedOnlyMeshes = value;
  12807. this._hookArrayForIncludedOnly(value);
  12808. },
  12809. enumerable: true,
  12810. configurable: true
  12811. });
  12812. Object.defineProperty(Light.prototype, "excludedMeshes", {
  12813. get: function () {
  12814. return this._excludedMeshes;
  12815. },
  12816. set: function (value) {
  12817. this._excludedMeshes = value;
  12818. this._hookArrayForExcluded(value);
  12819. },
  12820. enumerable: true,
  12821. configurable: true
  12822. });
  12823. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  12824. get: function () {
  12825. return this._excludeWithLayerMask;
  12826. },
  12827. set: function (value) {
  12828. this._excludeWithLayerMask = value;
  12829. this._resyncMeshes();
  12830. },
  12831. enumerable: true,
  12832. configurable: true
  12833. });
  12834. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  12835. get: function () {
  12836. return this._includeOnlyWithLayerMask;
  12837. },
  12838. set: function (value) {
  12839. this._includeOnlyWithLayerMask = value;
  12840. this._resyncMeshes();
  12841. },
  12842. enumerable: true,
  12843. configurable: true
  12844. });
  12845. Object.defineProperty(Light.prototype, "lightmapMode", {
  12846. get: function () {
  12847. return this._lightmapMode;
  12848. },
  12849. set: function (value) {
  12850. if (this._lightmapMode === value) {
  12851. return;
  12852. }
  12853. this._lightmapMode = value;
  12854. this._markMeshesAsLightDirty();
  12855. },
  12856. enumerable: true,
  12857. configurable: true
  12858. });
  12859. Light.prototype._buildUniformLayout = function () {
  12860. // Overridden
  12861. };
  12862. /**
  12863. * Returns the string "Light".
  12864. */
  12865. Light.prototype.getClassName = function () {
  12866. return "Light";
  12867. };
  12868. /**
  12869. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  12870. */
  12871. Light.prototype.toString = function (fullDetails) {
  12872. var ret = "Name: " + this.name;
  12873. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  12874. if (this.animations) {
  12875. for (var i = 0; i < this.animations.length; i++) {
  12876. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  12877. }
  12878. }
  12879. if (fullDetails) {
  12880. }
  12881. return ret;
  12882. };
  12883. /**
  12884. * Set the enabled state of this node.
  12885. * @param {boolean} value - the new enabled state
  12886. * @see isEnabled
  12887. */
  12888. Light.prototype.setEnabled = function (value) {
  12889. _super.prototype.setEnabled.call(this, value);
  12890. this._resyncMeshes();
  12891. };
  12892. /**
  12893. * Returns the Light associated shadow generator.
  12894. */
  12895. Light.prototype.getShadowGenerator = function () {
  12896. return this._shadowGenerator;
  12897. };
  12898. /**
  12899. * Returns a Vector3, the absolute light position in the World.
  12900. */
  12901. Light.prototype.getAbsolutePosition = function () {
  12902. return BABYLON.Vector3.Zero();
  12903. };
  12904. Light.prototype.transferToEffect = function (effect, lightIndex) {
  12905. };
  12906. Light.prototype._getWorldMatrix = function () {
  12907. return BABYLON.Matrix.Identity();
  12908. };
  12909. /**
  12910. * Boolean : True if the light will affect the passed mesh.
  12911. */
  12912. Light.prototype.canAffectMesh = function (mesh) {
  12913. if (!mesh) {
  12914. return true;
  12915. }
  12916. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  12917. return false;
  12918. }
  12919. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  12920. return false;
  12921. }
  12922. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  12923. return false;
  12924. }
  12925. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  12926. return false;
  12927. }
  12928. return true;
  12929. };
  12930. /**
  12931. * Returns the light World matrix.
  12932. */
  12933. Light.prototype.getWorldMatrix = function () {
  12934. this._currentRenderId = this.getScene().getRenderId();
  12935. var worldMatrix = this._getWorldMatrix();
  12936. if (this.parent && this.parent.getWorldMatrix) {
  12937. if (!this._parentedWorldMatrix) {
  12938. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  12939. }
  12940. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  12941. this._markSyncedWithParent();
  12942. return this._parentedWorldMatrix;
  12943. }
  12944. return worldMatrix;
  12945. };
  12946. /**
  12947. * Disposes the light.
  12948. */
  12949. Light.prototype.dispose = function () {
  12950. if (this._shadowGenerator) {
  12951. this._shadowGenerator.dispose();
  12952. this._shadowGenerator = null;
  12953. }
  12954. // Animations
  12955. this.getScene().stopAnimation(this);
  12956. // Remove from meshes
  12957. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  12958. var mesh = _a[_i];
  12959. mesh._removeLightSource(this);
  12960. }
  12961. this._uniformBuffer.dispose();
  12962. // Remove from scene
  12963. this.getScene().removeLight(this);
  12964. _super.prototype.dispose.call(this);
  12965. };
  12966. /**
  12967. * Returns the light type ID (integer).
  12968. */
  12969. Light.prototype.getTypeID = function () {
  12970. return 0;
  12971. };
  12972. /**
  12973. * Returns a new Light object, named "name", from the current one.
  12974. */
  12975. Light.prototype.clone = function (name) {
  12976. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  12977. };
  12978. /**
  12979. * Serializes the current light into a Serialization object.
  12980. * Returns the serialized object.
  12981. */
  12982. Light.prototype.serialize = function () {
  12983. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  12984. // Type
  12985. serializationObject.type = this.getTypeID();
  12986. // Parent
  12987. if (this.parent) {
  12988. serializationObject.parentId = this.parent.id;
  12989. }
  12990. // Inclusion / exclusions
  12991. if (this.excludedMeshes.length > 0) {
  12992. serializationObject.excludedMeshesIds = [];
  12993. this.excludedMeshes.forEach(function (mesh) {
  12994. serializationObject.excludedMeshesIds.push(mesh.id);
  12995. });
  12996. }
  12997. if (this.includedOnlyMeshes.length > 0) {
  12998. serializationObject.includedOnlyMeshesIds = [];
  12999. this.includedOnlyMeshes.forEach(function (mesh) {
  13000. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  13001. });
  13002. }
  13003. // Animations
  13004. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  13005. serializationObject.ranges = this.serializeAnimationRanges();
  13006. return serializationObject;
  13007. };
  13008. /**
  13009. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  13010. * This new light is named "name" and added to the passed scene.
  13011. */
  13012. Light.GetConstructorFromName = function (type, name, scene) {
  13013. switch (type) {
  13014. case 0:
  13015. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  13016. case 1:
  13017. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  13018. case 2:
  13019. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  13020. case 3:
  13021. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  13022. }
  13023. };
  13024. /**
  13025. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  13026. */
  13027. Light.Parse = function (parsedLight, scene) {
  13028. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  13029. // Inclusion / exclusions
  13030. if (parsedLight.excludedMeshesIds) {
  13031. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  13032. }
  13033. if (parsedLight.includedOnlyMeshesIds) {
  13034. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  13035. }
  13036. // Parent
  13037. if (parsedLight.parentId) {
  13038. light._waitingParentId = parsedLight.parentId;
  13039. }
  13040. // Animations
  13041. if (parsedLight.animations) {
  13042. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  13043. var parsedAnimation = parsedLight.animations[animationIndex];
  13044. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  13045. }
  13046. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  13047. }
  13048. if (parsedLight.autoAnimate) {
  13049. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  13050. }
  13051. return light;
  13052. };
  13053. Light.prototype._hookArrayForExcluded = function (array) {
  13054. var _this = this;
  13055. var oldPush = array.push;
  13056. array.push = function () {
  13057. var items = [];
  13058. for (var _i = 0; _i < arguments.length; _i++) {
  13059. items[_i] = arguments[_i];
  13060. }
  13061. var result = oldPush.apply(array, items);
  13062. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  13063. var item = items_1[_a];
  13064. item._resyncLighSource(_this);
  13065. }
  13066. return result;
  13067. };
  13068. var oldSplice = array.splice;
  13069. array.splice = function (index, deleteCount) {
  13070. var deleted = oldSplice.apply(array, [index, deleteCount]);
  13071. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  13072. var item = deleted_1[_i];
  13073. item._resyncLighSource(_this);
  13074. }
  13075. return deleted;
  13076. };
  13077. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  13078. var item = array_1[_i];
  13079. item._resyncLighSource(this);
  13080. }
  13081. };
  13082. Light.prototype._hookArrayForIncludedOnly = function (array) {
  13083. var _this = this;
  13084. var oldPush = array.push;
  13085. array.push = function () {
  13086. var items = [];
  13087. for (var _i = 0; _i < arguments.length; _i++) {
  13088. items[_i] = arguments[_i];
  13089. }
  13090. var result = oldPush.apply(array, items);
  13091. _this._resyncMeshes();
  13092. return result;
  13093. };
  13094. var oldSplice = array.splice;
  13095. array.splice = function (index, deleteCount) {
  13096. var deleted = oldSplice.apply(array, [index, deleteCount]);
  13097. _this._resyncMeshes();
  13098. return deleted;
  13099. };
  13100. this._resyncMeshes();
  13101. };
  13102. Light.prototype._resyncMeshes = function () {
  13103. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  13104. var mesh = _a[_i];
  13105. mesh._resyncLighSource(this);
  13106. }
  13107. };
  13108. Light.prototype._markMeshesAsLightDirty = function () {
  13109. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  13110. var mesh = _a[_i];
  13111. if (mesh._lightSources.indexOf(this) !== -1) {
  13112. mesh._markSubMeshesAsLightDirty();
  13113. }
  13114. }
  13115. };
  13116. return Light;
  13117. }(BABYLON.Node));
  13118. //lightmapMode Consts
  13119. Light._LIGHTMAP_DEFAULT = 0;
  13120. Light._LIGHTMAP_SPECULAR = 1;
  13121. Light._LIGHTMAP_SHADOWSONLY = 2;
  13122. __decorate([
  13123. BABYLON.serializeAsColor3()
  13124. ], Light.prototype, "diffuse", void 0);
  13125. __decorate([
  13126. BABYLON.serializeAsColor3()
  13127. ], Light.prototype, "specular", void 0);
  13128. __decorate([
  13129. BABYLON.serialize()
  13130. ], Light.prototype, "intensity", void 0);
  13131. __decorate([
  13132. BABYLON.serialize()
  13133. ], Light.prototype, "range", void 0);
  13134. __decorate([
  13135. BABYLON.serialize("excludeWithLayerMask")
  13136. ], Light.prototype, "_excludeWithLayerMask", void 0);
  13137. __decorate([
  13138. BABYLON.serialize("includeOnlyWithLayerMask")
  13139. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  13140. __decorate([
  13141. BABYLON.serialize("lightmapMode")
  13142. ], Light.prototype, "_lightmapMode", void 0);
  13143. __decorate([
  13144. BABYLON.serialize()
  13145. ], Light.prototype, "radius", void 0);
  13146. BABYLON.Light = Light;
  13147. })(BABYLON || (BABYLON = {}));
  13148. //# sourceMappingURL=babylon.light.js.map
  13149. var BABYLON;
  13150. (function (BABYLON) {
  13151. var Camera = (function (_super) {
  13152. __extends(Camera, _super);
  13153. function Camera(name, position, scene) {
  13154. var _this = _super.call(this, name, scene) || this;
  13155. _this.upVector = BABYLON.Vector3.Up();
  13156. _this.orthoLeft = null;
  13157. _this.orthoRight = null;
  13158. _this.orthoBottom = null;
  13159. _this.orthoTop = null;
  13160. _this.fov = 0.8;
  13161. _this.minZ = 1.0;
  13162. _this.maxZ = 10000.0;
  13163. _this.inertia = 0.9;
  13164. _this.mode = Camera.PERSPECTIVE_CAMERA;
  13165. _this.isIntermediate = false;
  13166. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  13167. _this.layerMask = 0x0FFFFFFF;
  13168. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  13169. // Camera rig members
  13170. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  13171. _this._rigCameras = new Array();
  13172. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  13173. // Cache
  13174. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  13175. _this._projectionMatrix = new BABYLON.Matrix();
  13176. _this._doNotComputeProjectionMatrix = false;
  13177. _this._postProcesses = new Array();
  13178. _this._transformMatrix = BABYLON.Matrix.Zero();
  13179. _this._activeMeshes = new BABYLON.SmartArray(256);
  13180. _this._globalPosition = BABYLON.Vector3.Zero();
  13181. _this._refreshFrustumPlanes = true;
  13182. _this.getScene().addCamera(_this);
  13183. if (!_this.getScene().activeCamera) {
  13184. _this.getScene().activeCamera = _this;
  13185. }
  13186. _this.position = position;
  13187. return _this;
  13188. }
  13189. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  13190. get: function () {
  13191. return Camera._PERSPECTIVE_CAMERA;
  13192. },
  13193. enumerable: true,
  13194. configurable: true
  13195. });
  13196. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  13197. get: function () {
  13198. return Camera._ORTHOGRAPHIC_CAMERA;
  13199. },
  13200. enumerable: true,
  13201. configurable: true
  13202. });
  13203. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  13204. get: function () {
  13205. return Camera._FOVMODE_VERTICAL_FIXED;
  13206. },
  13207. enumerable: true,
  13208. configurable: true
  13209. });
  13210. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  13211. get: function () {
  13212. return Camera._FOVMODE_HORIZONTAL_FIXED;
  13213. },
  13214. enumerable: true,
  13215. configurable: true
  13216. });
  13217. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  13218. get: function () {
  13219. return Camera._RIG_MODE_NONE;
  13220. },
  13221. enumerable: true,
  13222. configurable: true
  13223. });
  13224. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  13225. get: function () {
  13226. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  13227. },
  13228. enumerable: true,
  13229. configurable: true
  13230. });
  13231. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  13232. get: function () {
  13233. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  13234. },
  13235. enumerable: true,
  13236. configurable: true
  13237. });
  13238. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  13239. get: function () {
  13240. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  13241. },
  13242. enumerable: true,
  13243. configurable: true
  13244. });
  13245. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  13246. get: function () {
  13247. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  13248. },
  13249. enumerable: true,
  13250. configurable: true
  13251. });
  13252. Object.defineProperty(Camera, "RIG_MODE_VR", {
  13253. get: function () {
  13254. return Camera._RIG_MODE_VR;
  13255. },
  13256. enumerable: true,
  13257. configurable: true
  13258. });
  13259. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  13260. get: function () {
  13261. return Camera._RIG_MODE_WEBVR;
  13262. },
  13263. enumerable: true,
  13264. configurable: true
  13265. });
  13266. Camera.prototype.getClassName = function () {
  13267. return "Camera";
  13268. };
  13269. /**
  13270. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  13271. */
  13272. Camera.prototype.toString = function (fullDetails) {
  13273. var ret = "Name: " + this.name;
  13274. ret += ", type: " + this.getClassName();
  13275. if (this.animations) {
  13276. for (var i = 0; i < this.animations.length; i++) {
  13277. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  13278. }
  13279. }
  13280. if (fullDetails) {
  13281. }
  13282. return ret;
  13283. };
  13284. Object.defineProperty(Camera.prototype, "globalPosition", {
  13285. get: function () {
  13286. return this._globalPosition;
  13287. },
  13288. enumerable: true,
  13289. configurable: true
  13290. });
  13291. Camera.prototype.getActiveMeshes = function () {
  13292. return this._activeMeshes;
  13293. };
  13294. Camera.prototype.isActiveMesh = function (mesh) {
  13295. return (this._activeMeshes.indexOf(mesh) !== -1);
  13296. };
  13297. //Cache
  13298. Camera.prototype._initCache = function () {
  13299. _super.prototype._initCache.call(this);
  13300. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13301. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13302. this._cache.mode = undefined;
  13303. this._cache.minZ = undefined;
  13304. this._cache.maxZ = undefined;
  13305. this._cache.fov = undefined;
  13306. this._cache.fovMode = undefined;
  13307. this._cache.aspectRatio = undefined;
  13308. this._cache.orthoLeft = undefined;
  13309. this._cache.orthoRight = undefined;
  13310. this._cache.orthoBottom = undefined;
  13311. this._cache.orthoTop = undefined;
  13312. this._cache.renderWidth = undefined;
  13313. this._cache.renderHeight = undefined;
  13314. };
  13315. Camera.prototype._updateCache = function (ignoreParentClass) {
  13316. if (!ignoreParentClass) {
  13317. _super.prototype._updateCache.call(this);
  13318. }
  13319. var engine = this.getEngine();
  13320. this._cache.position.copyFrom(this.position);
  13321. this._cache.upVector.copyFrom(this.upVector);
  13322. this._cache.mode = this.mode;
  13323. this._cache.minZ = this.minZ;
  13324. this._cache.maxZ = this.maxZ;
  13325. this._cache.fov = this.fov;
  13326. this._cache.fovMode = this.fovMode;
  13327. this._cache.aspectRatio = engine.getAspectRatio(this);
  13328. this._cache.orthoLeft = this.orthoLeft;
  13329. this._cache.orthoRight = this.orthoRight;
  13330. this._cache.orthoBottom = this.orthoBottom;
  13331. this._cache.orthoTop = this.orthoTop;
  13332. this._cache.renderWidth = engine.getRenderWidth();
  13333. this._cache.renderHeight = engine.getRenderHeight();
  13334. };
  13335. Camera.prototype._updateFromScene = function () {
  13336. this.updateCache();
  13337. this.update();
  13338. };
  13339. // Synchronized
  13340. Camera.prototype._isSynchronized = function () {
  13341. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  13342. };
  13343. Camera.prototype._isSynchronizedViewMatrix = function () {
  13344. if (!_super.prototype._isSynchronized.call(this))
  13345. return false;
  13346. return this._cache.position.equals(this.position)
  13347. && this._cache.upVector.equals(this.upVector)
  13348. && this.isSynchronizedWithParent();
  13349. };
  13350. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  13351. var check = this._cache.mode === this.mode
  13352. && this._cache.minZ === this.minZ
  13353. && this._cache.maxZ === this.maxZ;
  13354. if (!check) {
  13355. return false;
  13356. }
  13357. var engine = this.getEngine();
  13358. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  13359. check = this._cache.fov === this.fov
  13360. && this._cache.fovMode === this.fovMode
  13361. && this._cache.aspectRatio === engine.getAspectRatio(this);
  13362. }
  13363. else {
  13364. check = this._cache.orthoLeft === this.orthoLeft
  13365. && this._cache.orthoRight === this.orthoRight
  13366. && this._cache.orthoBottom === this.orthoBottom
  13367. && this._cache.orthoTop === this.orthoTop
  13368. && this._cache.renderWidth === engine.getRenderWidth()
  13369. && this._cache.renderHeight === engine.getRenderHeight();
  13370. }
  13371. return check;
  13372. };
  13373. // Controls
  13374. Camera.prototype.attachControl = function (element, noPreventDefault) {
  13375. };
  13376. Camera.prototype.detachControl = function (element) {
  13377. };
  13378. Camera.prototype.update = function () {
  13379. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  13380. this._updateRigCameras();
  13381. }
  13382. this._checkInputs();
  13383. };
  13384. Camera.prototype._checkInputs = function () {
  13385. };
  13386. Object.defineProperty(Camera.prototype, "rigCameras", {
  13387. get: function () {
  13388. return this._rigCameras;
  13389. },
  13390. enumerable: true,
  13391. configurable: true
  13392. });
  13393. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  13394. get: function () {
  13395. return this._rigPostProcess;
  13396. },
  13397. enumerable: true,
  13398. configurable: true
  13399. });
  13400. Camera.prototype._cascadePostProcessesToRigCams = function () {
  13401. // invalidate framebuffer
  13402. if (this._postProcesses.length > 0) {
  13403. this._postProcesses[0].markTextureDirty();
  13404. }
  13405. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  13406. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  13407. var cam = this._rigCameras[i];
  13408. var rigPostProcess = cam._rigPostProcess;
  13409. // for VR rig, there does not have to be a post process
  13410. if (rigPostProcess) {
  13411. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  13412. if (isPass) {
  13413. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  13414. cam.isIntermediate = this._postProcesses.length === 0;
  13415. }
  13416. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  13417. rigPostProcess.markTextureDirty();
  13418. }
  13419. else {
  13420. cam._postProcesses = this._postProcesses.slice(0);
  13421. }
  13422. }
  13423. };
  13424. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  13425. if (insertAt === void 0) { insertAt = null; }
  13426. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  13427. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  13428. return 0;
  13429. }
  13430. if (insertAt == null || insertAt < 0) {
  13431. this._postProcesses.push(postProcess);
  13432. }
  13433. else {
  13434. this._postProcesses.splice(insertAt, 0, postProcess);
  13435. }
  13436. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  13437. return this._postProcesses.indexOf(postProcess);
  13438. };
  13439. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  13440. if (atIndices === void 0) { atIndices = null; }
  13441. var result = [];
  13442. var i;
  13443. var index;
  13444. if (!atIndices) {
  13445. var idx = this._postProcesses.indexOf(postProcess);
  13446. if (idx !== -1) {
  13447. this._postProcesses.splice(idx, 1);
  13448. }
  13449. }
  13450. else {
  13451. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  13452. // iterate descending, so can just splice as we go
  13453. for (i = atIndices.length - 1; i >= 0; i--) {
  13454. if (this._postProcesses[atIndices[i]] !== postProcess) {
  13455. result.push(i);
  13456. continue;
  13457. }
  13458. index = atIndices[i];
  13459. this._postProcesses.splice(index, 1);
  13460. }
  13461. }
  13462. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  13463. return result;
  13464. };
  13465. Camera.prototype.getWorldMatrix = function () {
  13466. if (!this._worldMatrix) {
  13467. this._worldMatrix = BABYLON.Matrix.Identity();
  13468. }
  13469. var viewMatrix = this.getViewMatrix();
  13470. viewMatrix.invertToRef(this._worldMatrix);
  13471. return this._worldMatrix;
  13472. };
  13473. Camera.prototype._getViewMatrix = function () {
  13474. return BABYLON.Matrix.Identity();
  13475. };
  13476. Camera.prototype.getViewMatrix = function (force) {
  13477. this._computedViewMatrix = this._computeViewMatrix(force);
  13478. if (!force && this._isSynchronizedViewMatrix()) {
  13479. return this._computedViewMatrix;
  13480. }
  13481. this._refreshFrustumPlanes = true;
  13482. if (!this.parent || !this.parent.getWorldMatrix) {
  13483. this._globalPosition.copyFrom(this.position);
  13484. }
  13485. else {
  13486. if (!this._worldMatrix) {
  13487. this._worldMatrix = BABYLON.Matrix.Identity();
  13488. }
  13489. this._computedViewMatrix.invertToRef(this._worldMatrix);
  13490. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  13491. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  13492. this._computedViewMatrix.invert();
  13493. this._markSyncedWithParent();
  13494. }
  13495. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  13496. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  13497. }
  13498. this._currentRenderId = this.getScene().getRenderId();
  13499. return this._computedViewMatrix;
  13500. };
  13501. Camera.prototype._computeViewMatrix = function (force) {
  13502. if (!force && this._isSynchronizedViewMatrix()) {
  13503. return this._computedViewMatrix;
  13504. }
  13505. this._computedViewMatrix = this._getViewMatrix();
  13506. this._currentRenderId = this.getScene().getRenderId();
  13507. return this._computedViewMatrix;
  13508. };
  13509. Camera.prototype.freezeProjectionMatrix = function (projection) {
  13510. this._doNotComputeProjectionMatrix = true;
  13511. if (projection !== undefined) {
  13512. this._projectionMatrix = projection;
  13513. }
  13514. };
  13515. ;
  13516. Camera.prototype.unfreezeProjectionMatrix = function () {
  13517. this._doNotComputeProjectionMatrix = false;
  13518. };
  13519. ;
  13520. Camera.prototype.getProjectionMatrix = function (force) {
  13521. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  13522. return this._projectionMatrix;
  13523. }
  13524. this._refreshFrustumPlanes = true;
  13525. var engine = this.getEngine();
  13526. var scene = this.getScene();
  13527. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  13528. if (this.minZ <= 0) {
  13529. this.minZ = 0.1;
  13530. }
  13531. if (scene.useRightHandedSystem) {
  13532. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  13533. }
  13534. else {
  13535. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  13536. }
  13537. return this._projectionMatrix;
  13538. }
  13539. var halfWidth = engine.getRenderWidth() / 2.0;
  13540. var halfHeight = engine.getRenderHeight() / 2.0;
  13541. if (scene.useRightHandedSystem) {
  13542. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  13543. }
  13544. else {
  13545. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  13546. }
  13547. return this._projectionMatrix;
  13548. };
  13549. Camera.prototype.getTranformationMatrix = function () {
  13550. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  13551. return this._transformMatrix;
  13552. };
  13553. Camera.prototype.updateFrustumPlanes = function () {
  13554. if (!this._refreshFrustumPlanes) {
  13555. return;
  13556. }
  13557. this.getTranformationMatrix();
  13558. if (!this._frustumPlanes) {
  13559. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  13560. }
  13561. else {
  13562. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  13563. }
  13564. this._refreshFrustumPlanes = false;
  13565. };
  13566. Camera.prototype.isInFrustum = function (target) {
  13567. this.updateFrustumPlanes();
  13568. return target.isInFrustum(this._frustumPlanes);
  13569. };
  13570. Camera.prototype.isCompletelyInFrustum = function (target) {
  13571. this.updateFrustumPlanes();
  13572. return target.isCompletelyInFrustum(this._frustumPlanes);
  13573. };
  13574. Camera.prototype.getForwardRay = function (length, transform, origin) {
  13575. if (length === void 0) { length = 100; }
  13576. if (!transform) {
  13577. transform = this.getWorldMatrix();
  13578. }
  13579. if (!origin) {
  13580. origin = this.position;
  13581. }
  13582. var forward = new BABYLON.Vector3(0, 0, 1);
  13583. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  13584. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  13585. return new BABYLON.Ray(origin, direction, length);
  13586. };
  13587. Camera.prototype.dispose = function () {
  13588. // Animations
  13589. this.getScene().stopAnimation(this);
  13590. // Remove from scene
  13591. this.getScene().removeCamera(this);
  13592. while (this._rigCameras.length > 0) {
  13593. this._rigCameras.pop().dispose();
  13594. }
  13595. // Postprocesses
  13596. var i = this._postProcesses.length;
  13597. while (--i >= 0) {
  13598. this._postProcesses[i].dispose(this);
  13599. }
  13600. _super.prototype.dispose.call(this);
  13601. };
  13602. Object.defineProperty(Camera.prototype, "leftCamera", {
  13603. // ---- Camera rigs section ----
  13604. get: function () {
  13605. if (this._rigCameras.length < 1) {
  13606. return undefined;
  13607. }
  13608. return this._rigCameras[0];
  13609. },
  13610. enumerable: true,
  13611. configurable: true
  13612. });
  13613. Object.defineProperty(Camera.prototype, "rightCamera", {
  13614. get: function () {
  13615. if (this._rigCameras.length < 2) {
  13616. return undefined;
  13617. }
  13618. return this._rigCameras[1];
  13619. },
  13620. enumerable: true,
  13621. configurable: true
  13622. });
  13623. Camera.prototype.getLeftTarget = function () {
  13624. if (this._rigCameras.length < 1) {
  13625. return undefined;
  13626. }
  13627. return this._rigCameras[0].getTarget();
  13628. };
  13629. Camera.prototype.getRightTarget = function () {
  13630. if (this._rigCameras.length < 2) {
  13631. return undefined;
  13632. }
  13633. return this._rigCameras[1].getTarget();
  13634. };
  13635. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  13636. while (this._rigCameras.length > 0) {
  13637. this._rigCameras.pop().dispose();
  13638. }
  13639. this.cameraRigMode = mode;
  13640. this._cameraRigParams = {};
  13641. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  13642. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  13643. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  13644. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  13645. // create the rig cameras, unless none
  13646. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  13647. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  13648. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  13649. }
  13650. switch (this.cameraRigMode) {
  13651. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  13652. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  13653. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  13654. break;
  13655. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  13656. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  13657. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  13658. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  13659. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  13660. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  13661. break;
  13662. case Camera.RIG_MODE_VR:
  13663. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  13664. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  13665. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  13666. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  13667. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  13668. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  13669. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  13670. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  13671. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  13672. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  13673. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  13674. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  13675. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  13676. if (metrics.compensateDistortion) {
  13677. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  13678. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  13679. }
  13680. break;
  13681. case Camera.RIG_MODE_WEBVR:
  13682. if (rigParams.vrDisplay) {
  13683. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  13684. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  13685. //Left eye
  13686. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  13687. this._rigCameras[0].setCameraRigParameter("left", true);
  13688. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  13689. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  13690. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  13691. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  13692. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  13693. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  13694. this._rigCameras[0].parent = this;
  13695. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  13696. //Right eye
  13697. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  13698. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  13699. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  13700. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  13701. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  13702. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  13703. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  13704. this._rigCameras[1].parent = this;
  13705. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  13706. }
  13707. break;
  13708. }
  13709. this._cascadePostProcessesToRigCams();
  13710. this.
  13711. update();
  13712. };
  13713. Camera.prototype._getVRProjectionMatrix = function () {
  13714. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  13715. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  13716. return this._projectionMatrix;
  13717. };
  13718. Camera.prototype._updateCameraRotationMatrix = function () {
  13719. //Here for WebVR
  13720. };
  13721. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  13722. //Here for WebVR
  13723. };
  13724. /**
  13725. * This function MUST be overwritten by the different WebVR cameras available.
  13726. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  13727. */
  13728. Camera.prototype._getWebVRProjectionMatrix = function () {
  13729. return BABYLON.Matrix.Identity();
  13730. };
  13731. /**
  13732. * This function MUST be overwritten by the different WebVR cameras available.
  13733. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  13734. */
  13735. Camera.prototype._getWebVRViewMatrix = function () {
  13736. return BABYLON.Matrix.Identity();
  13737. };
  13738. Camera.prototype.setCameraRigParameter = function (name, value) {
  13739. if (!this._cameraRigParams) {
  13740. this._cameraRigParams = {};
  13741. }
  13742. this._cameraRigParams[name] = value;
  13743. //provisionnally:
  13744. if (name === "interaxialDistance") {
  13745. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  13746. }
  13747. };
  13748. /**
  13749. * needs to be overridden by children so sub has required properties to be copied
  13750. */
  13751. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  13752. return null;
  13753. };
  13754. /**
  13755. * May need to be overridden by children
  13756. */
  13757. Camera.prototype._updateRigCameras = function () {
  13758. for (var i = 0; i < this._rigCameras.length; i++) {
  13759. this._rigCameras[i].minZ = this.minZ;
  13760. this._rigCameras[i].maxZ = this.maxZ;
  13761. this._rigCameras[i].fov = this.fov;
  13762. }
  13763. // only update viewport when ANAGLYPH
  13764. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  13765. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  13766. }
  13767. };
  13768. Camera.prototype._setupInputs = function () {
  13769. };
  13770. Camera.prototype.serialize = function () {
  13771. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  13772. // Type
  13773. serializationObject.type = this.getClassName();
  13774. // Parent
  13775. if (this.parent) {
  13776. serializationObject.parentId = this.parent.id;
  13777. }
  13778. if (this.inputs) {
  13779. this.inputs.serialize(serializationObject);
  13780. }
  13781. // Animations
  13782. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  13783. serializationObject.ranges = this.serializeAnimationRanges();
  13784. return serializationObject;
  13785. };
  13786. Camera.prototype.clone = function (name) {
  13787. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  13788. };
  13789. Camera.prototype.getDirection = function (localAxis) {
  13790. var result = BABYLON.Vector3.Zero();
  13791. this.getDirectionToRef(localAxis, result);
  13792. return result;
  13793. };
  13794. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  13795. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  13796. };
  13797. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  13798. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  13799. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  13800. switch (type) {
  13801. case "ArcRotateCamera":
  13802. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  13803. case "DeviceOrientationCamera":
  13804. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  13805. case "FollowCamera":
  13806. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  13807. case "ArcFollowCamera":
  13808. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  13809. case "GamepadCamera":
  13810. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  13811. case "TouchCamera":
  13812. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  13813. case "VirtualJoysticksCamera":
  13814. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  13815. case "WebVRFreeCamera":
  13816. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  13817. case "WebVRGamepadCamera":
  13818. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  13819. case "VRDeviceOrientationFreeCamera":
  13820. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  13821. case "VRDeviceOrientationGamepadCamera":
  13822. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  13823. case "AnaglyphArcRotateCamera":
  13824. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  13825. case "AnaglyphFreeCamera":
  13826. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  13827. case "AnaglyphGamepadCamera":
  13828. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  13829. case "AnaglyphUniversalCamera":
  13830. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  13831. case "StereoscopicArcRotateCamera":
  13832. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  13833. case "StereoscopicFreeCamera":
  13834. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  13835. case "StereoscopicGamepadCamera":
  13836. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  13837. case "StereoscopicUniversalCamera":
  13838. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  13839. case "FreeCamera":
  13840. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  13841. default:
  13842. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  13843. }
  13844. };
  13845. Camera.Parse = function (parsedCamera, scene) {
  13846. var type = parsedCamera.type;
  13847. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  13848. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  13849. // Parent
  13850. if (parsedCamera.parentId) {
  13851. camera._waitingParentId = parsedCamera.parentId;
  13852. }
  13853. //If camera has an input manager, let it parse inputs settings
  13854. if (camera.inputs) {
  13855. camera.inputs.parse(parsedCamera);
  13856. camera._setupInputs();
  13857. }
  13858. // Target
  13859. if (parsedCamera.target) {
  13860. if (camera.setTarget) {
  13861. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  13862. }
  13863. }
  13864. // Apply 3d rig, when found
  13865. if (parsedCamera.cameraRigMode) {
  13866. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  13867. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  13868. }
  13869. // Animations
  13870. if (parsedCamera.animations) {
  13871. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  13872. var parsedAnimation = parsedCamera.animations[animationIndex];
  13873. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  13874. }
  13875. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  13876. }
  13877. if (parsedCamera.autoAnimate) {
  13878. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  13879. }
  13880. return camera;
  13881. };
  13882. return Camera;
  13883. }(BABYLON.Node));
  13884. // Statics
  13885. Camera._PERSPECTIVE_CAMERA = 0;
  13886. Camera._ORTHOGRAPHIC_CAMERA = 1;
  13887. Camera._FOVMODE_VERTICAL_FIXED = 0;
  13888. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  13889. Camera._RIG_MODE_NONE = 0;
  13890. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  13891. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  13892. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  13893. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  13894. Camera._RIG_MODE_VR = 20;
  13895. Camera._RIG_MODE_WEBVR = 21;
  13896. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  13897. __decorate([
  13898. BABYLON.serializeAsVector3()
  13899. ], Camera.prototype, "position", void 0);
  13900. __decorate([
  13901. BABYLON.serializeAsVector3()
  13902. ], Camera.prototype, "upVector", void 0);
  13903. __decorate([
  13904. BABYLON.serialize()
  13905. ], Camera.prototype, "orthoLeft", void 0);
  13906. __decorate([
  13907. BABYLON.serialize()
  13908. ], Camera.prototype, "orthoRight", void 0);
  13909. __decorate([
  13910. BABYLON.serialize()
  13911. ], Camera.prototype, "orthoBottom", void 0);
  13912. __decorate([
  13913. BABYLON.serialize()
  13914. ], Camera.prototype, "orthoTop", void 0);
  13915. __decorate([
  13916. BABYLON.serialize()
  13917. ], Camera.prototype, "fov", void 0);
  13918. __decorate([
  13919. BABYLON.serialize()
  13920. ], Camera.prototype, "minZ", void 0);
  13921. __decorate([
  13922. BABYLON.serialize()
  13923. ], Camera.prototype, "maxZ", void 0);
  13924. __decorate([
  13925. BABYLON.serialize()
  13926. ], Camera.prototype, "inertia", void 0);
  13927. __decorate([
  13928. BABYLON.serialize()
  13929. ], Camera.prototype, "mode", void 0);
  13930. __decorate([
  13931. BABYLON.serialize()
  13932. ], Camera.prototype, "layerMask", void 0);
  13933. __decorate([
  13934. BABYLON.serialize()
  13935. ], Camera.prototype, "fovMode", void 0);
  13936. __decorate([
  13937. BABYLON.serialize()
  13938. ], Camera.prototype, "cameraRigMode", void 0);
  13939. __decorate([
  13940. BABYLON.serialize()
  13941. ], Camera.prototype, "interaxialDistance", void 0);
  13942. __decorate([
  13943. BABYLON.serialize()
  13944. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  13945. BABYLON.Camera = Camera;
  13946. })(BABYLON || (BABYLON = {}));
  13947. //# sourceMappingURL=babylon.camera.js.map
  13948. var BABYLON;
  13949. (function (BABYLON) {
  13950. var RenderingManager = (function () {
  13951. function RenderingManager(scene) {
  13952. this._renderingGroups = new Array();
  13953. this._autoClearDepthStencil = {};
  13954. this._customOpaqueSortCompareFn = {};
  13955. this._customAlphaTestSortCompareFn = {};
  13956. this._customTransparentSortCompareFn = {};
  13957. this._renderinGroupInfo = null;
  13958. this._scene = scene;
  13959. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  13960. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  13961. }
  13962. }
  13963. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  13964. if (depth === void 0) { depth = true; }
  13965. if (stencil === void 0) { stencil = true; }
  13966. if (this._depthStencilBufferAlreadyCleaned) {
  13967. return;
  13968. }
  13969. this._scene.getEngine().clear(null, false, depth, stencil);
  13970. this._depthStencilBufferAlreadyCleaned = true;
  13971. };
  13972. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  13973. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  13974. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  13975. var info = null;
  13976. if (observable) {
  13977. if (!this._renderinGroupInfo) {
  13978. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  13979. }
  13980. info = this._renderinGroupInfo;
  13981. info.scene = this._scene;
  13982. info.camera = this._scene.activeCamera;
  13983. }
  13984. // Dispatch sprites
  13985. if (renderSprites) {
  13986. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  13987. var manager = this._scene.spriteManagers[index];
  13988. this.dispatchSprites(manager);
  13989. }
  13990. }
  13991. // Render
  13992. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  13993. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  13994. var renderingGroup = this._renderingGroups[index];
  13995. if (!renderingGroup && !observable)
  13996. continue;
  13997. this._currentIndex = index;
  13998. var renderingGroupMask = 0;
  13999. // Fire PRECLEAR stage
  14000. if (observable) {
  14001. renderingGroupMask = Math.pow(2, index);
  14002. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  14003. info.renderingGroupId = index;
  14004. observable.notifyObservers(info, renderingGroupMask);
  14005. }
  14006. // Clear depth/stencil if needed
  14007. if (RenderingManager.AUTOCLEAR) {
  14008. var autoClear = this._autoClearDepthStencil[index];
  14009. if (autoClear && autoClear.autoClear) {
  14010. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  14011. }
  14012. }
  14013. if (observable) {
  14014. // Fire PREOPAQUE stage
  14015. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  14016. observable.notifyObservers(info, renderingGroupMask);
  14017. // Fire PRETRANSPARENT stage
  14018. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  14019. observable.notifyObservers(info, renderingGroupMask);
  14020. }
  14021. if (renderingGroup)
  14022. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  14023. // Fire POSTTRANSPARENT stage
  14024. if (observable) {
  14025. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  14026. observable.notifyObservers(info, renderingGroupMask);
  14027. }
  14028. }
  14029. };
  14030. RenderingManager.prototype.reset = function () {
  14031. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  14032. var renderingGroup = this._renderingGroups[index];
  14033. if (renderingGroup) {
  14034. renderingGroup.prepare();
  14035. }
  14036. }
  14037. };
  14038. RenderingManager.prototype.dispose = function () {
  14039. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  14040. var renderingGroup = this._renderingGroups[index];
  14041. if (renderingGroup) {
  14042. renderingGroup.dispose();
  14043. }
  14044. }
  14045. this._renderingGroups.length = 0;
  14046. };
  14047. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  14048. if (!this._renderingGroups[renderingGroupId]) {
  14049. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  14050. }
  14051. };
  14052. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  14053. var renderingGroupId = spriteManager.renderingGroupId || 0;
  14054. this._prepareRenderingGroup(renderingGroupId);
  14055. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  14056. };
  14057. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  14058. var renderingGroupId = particleSystem.renderingGroupId || 0;
  14059. this._prepareRenderingGroup(renderingGroupId);
  14060. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  14061. };
  14062. RenderingManager.prototype.dispatch = function (subMesh) {
  14063. var mesh = subMesh.getMesh();
  14064. var renderingGroupId = mesh.renderingGroupId || 0;
  14065. this._prepareRenderingGroup(renderingGroupId);
  14066. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  14067. };
  14068. /**
  14069. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  14070. * This allowed control for front to back rendering or reversly depending of the special needs.
  14071. *
  14072. * @param renderingGroupId The rendering group id corresponding to its index
  14073. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  14074. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  14075. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  14076. */
  14077. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  14078. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  14079. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  14080. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  14081. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  14082. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  14083. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  14084. if (this._renderingGroups[renderingGroupId]) {
  14085. var group = this._renderingGroups[renderingGroupId];
  14086. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  14087. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  14088. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  14089. }
  14090. };
  14091. /**
  14092. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  14093. *
  14094. * @param renderingGroupId The rendering group id corresponding to its index
  14095. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  14096. * @param depth Automatically clears depth between groups if true and autoClear is true.
  14097. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  14098. */
  14099. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  14100. if (depth === void 0) { depth = true; }
  14101. if (stencil === void 0) { stencil = true; }
  14102. this._autoClearDepthStencil[renderingGroupId] = {
  14103. autoClear: autoClearDepthStencil,
  14104. depth: depth,
  14105. stencil: stencil
  14106. };
  14107. };
  14108. return RenderingManager;
  14109. }());
  14110. /**
  14111. * The max id used for rendering groups (not included)
  14112. */
  14113. RenderingManager.MAX_RENDERINGGROUPS = 4;
  14114. /**
  14115. * The min id used for rendering groups (included)
  14116. */
  14117. RenderingManager.MIN_RENDERINGGROUPS = 0;
  14118. /**
  14119. * Used to globally prevent autoclearing scenes.
  14120. */
  14121. RenderingManager.AUTOCLEAR = true;
  14122. BABYLON.RenderingManager = RenderingManager;
  14123. })(BABYLON || (BABYLON = {}));
  14124. //# sourceMappingURL=babylon.renderingManager.js.map
  14125. var BABYLON;
  14126. (function (BABYLON) {
  14127. var RenderingGroup = (function () {
  14128. /**
  14129. * Creates a new rendering group.
  14130. * @param index The rendering group index
  14131. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  14132. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  14133. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  14134. */
  14135. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  14136. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  14137. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  14138. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  14139. this.index = index;
  14140. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  14141. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  14142. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  14143. this._particleSystems = new BABYLON.SmartArray(256);
  14144. this._spriteManagers = new BABYLON.SmartArray(256);
  14145. this._scene = scene;
  14146. this.opaqueSortCompareFn = opaqueSortCompareFn;
  14147. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  14148. this.transparentSortCompareFn = transparentSortCompareFn;
  14149. }
  14150. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  14151. /**
  14152. * Set the opaque sort comparison function.
  14153. * If null the sub meshes will be render in the order they were created
  14154. */
  14155. set: function (value) {
  14156. this._opaqueSortCompareFn = value;
  14157. if (value) {
  14158. this._renderOpaque = this.renderOpaqueSorted;
  14159. }
  14160. else {
  14161. this._renderOpaque = RenderingGroup.renderUnsorted;
  14162. }
  14163. },
  14164. enumerable: true,
  14165. configurable: true
  14166. });
  14167. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  14168. /**
  14169. * Set the alpha test sort comparison function.
  14170. * If null the sub meshes will be render in the order they were created
  14171. */
  14172. set: function (value) {
  14173. this._alphaTestSortCompareFn = value;
  14174. if (value) {
  14175. this._renderAlphaTest = this.renderAlphaTestSorted;
  14176. }
  14177. else {
  14178. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  14179. }
  14180. },
  14181. enumerable: true,
  14182. configurable: true
  14183. });
  14184. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  14185. /**
  14186. * Set the transparent sort comparison function.
  14187. * If null the sub meshes will be render in the order they were created
  14188. */
  14189. set: function (value) {
  14190. if (value) {
  14191. this._transparentSortCompareFn = value;
  14192. }
  14193. else {
  14194. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  14195. }
  14196. this._renderTransparent = this.renderTransparentSorted;
  14197. },
  14198. enumerable: true,
  14199. configurable: true
  14200. });
  14201. /**
  14202. * Render all the sub meshes contained in the group.
  14203. * @param customRenderFunction Used to override the default render behaviour of the group.
  14204. * @returns true if rendered some submeshes.
  14205. */
  14206. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  14207. if (customRenderFunction) {
  14208. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  14209. return;
  14210. }
  14211. var engine = this._scene.getEngine();
  14212. // Opaque
  14213. if (this._opaqueSubMeshes.length !== 0) {
  14214. this._renderOpaque(this._opaqueSubMeshes);
  14215. }
  14216. // Alpha test
  14217. if (this._alphaTestSubMeshes.length !== 0) {
  14218. engine.setAlphaTesting(true);
  14219. this._renderAlphaTest(this._alphaTestSubMeshes);
  14220. engine.setAlphaTesting(false);
  14221. }
  14222. var stencilState = engine.getStencilBuffer();
  14223. engine.setStencilBuffer(false);
  14224. // Sprites
  14225. if (renderSprites) {
  14226. this._renderSprites();
  14227. }
  14228. // Particles
  14229. if (renderParticles) {
  14230. this._renderParticles(activeMeshes);
  14231. }
  14232. if (this.onBeforeTransparentRendering) {
  14233. this.onBeforeTransparentRendering();
  14234. }
  14235. // Transparent
  14236. if (this._transparentSubMeshes.length !== 0) {
  14237. this._renderTransparent(this._transparentSubMeshes);
  14238. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  14239. }
  14240. engine.setStencilBuffer(stencilState);
  14241. };
  14242. /**
  14243. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  14244. * @param subMeshes The submeshes to render
  14245. */
  14246. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  14247. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera.globalPosition, false);
  14248. };
  14249. /**
  14250. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  14251. * @param subMeshes The submeshes to render
  14252. */
  14253. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  14254. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera.globalPosition, false);
  14255. };
  14256. /**
  14257. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  14258. * @param subMeshes The submeshes to render
  14259. */
  14260. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  14261. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera.globalPosition, true);
  14262. };
  14263. /**
  14264. * Renders the submeshes in a specified order.
  14265. * @param subMeshes The submeshes to sort before render
  14266. * @param sortCompareFn The comparison function use to sort
  14267. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  14268. * @param transparent Specifies to activate blending if true
  14269. */
  14270. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, cameraPosition, transparent) {
  14271. var subIndex = 0;
  14272. var subMesh;
  14273. for (; subIndex < subMeshes.length; subIndex++) {
  14274. subMesh = subMeshes.data[subIndex];
  14275. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  14276. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  14277. }
  14278. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  14279. sortedArray.sort(sortCompareFn);
  14280. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  14281. subMesh = sortedArray[subIndex];
  14282. subMesh.render(transparent);
  14283. }
  14284. };
  14285. /**
  14286. * Renders the submeshes in the order they were dispatched (no sort applied).
  14287. * @param subMeshes The submeshes to render
  14288. */
  14289. RenderingGroup.renderUnsorted = function (subMeshes) {
  14290. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  14291. var submesh = subMeshes.data[subIndex];
  14292. submesh.render(false);
  14293. }
  14294. };
  14295. /**
  14296. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  14297. * are rendered back to front if in the same alpha index.
  14298. *
  14299. * @param a The first submesh
  14300. * @param b The second submesh
  14301. * @returns The result of the comparison
  14302. */
  14303. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  14304. // Alpha index first
  14305. if (a._alphaIndex > b._alphaIndex) {
  14306. return 1;
  14307. }
  14308. if (a._alphaIndex < b._alphaIndex) {
  14309. return -1;
  14310. }
  14311. // Then distance to camera
  14312. return RenderingGroup.backToFrontSortCompare(a, b);
  14313. };
  14314. /**
  14315. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  14316. * are rendered back to front.
  14317. *
  14318. * @param a The first submesh
  14319. * @param b The second submesh
  14320. * @returns The result of the comparison
  14321. */
  14322. RenderingGroup.backToFrontSortCompare = function (a, b) {
  14323. // Then distance to camera
  14324. if (a._distanceToCamera < b._distanceToCamera) {
  14325. return 1;
  14326. }
  14327. if (a._distanceToCamera > b._distanceToCamera) {
  14328. return -1;
  14329. }
  14330. return 0;
  14331. };
  14332. /**
  14333. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  14334. * are rendered front to back (prevent overdraw).
  14335. *
  14336. * @param a The first submesh
  14337. * @param b The second submesh
  14338. * @returns The result of the comparison
  14339. */
  14340. RenderingGroup.frontToBackSortCompare = function (a, b) {
  14341. // Then distance to camera
  14342. if (a._distanceToCamera < b._distanceToCamera) {
  14343. return -1;
  14344. }
  14345. if (a._distanceToCamera > b._distanceToCamera) {
  14346. return 1;
  14347. }
  14348. return 0;
  14349. };
  14350. /**
  14351. * Resets the different lists of submeshes to prepare a new frame.
  14352. */
  14353. RenderingGroup.prototype.prepare = function () {
  14354. this._opaqueSubMeshes.reset();
  14355. this._transparentSubMeshes.reset();
  14356. this._alphaTestSubMeshes.reset();
  14357. this._particleSystems.reset();
  14358. this._spriteManagers.reset();
  14359. };
  14360. RenderingGroup.prototype.dispose = function () {
  14361. this._opaqueSubMeshes.dispose();
  14362. this._transparentSubMeshes.dispose();
  14363. this._alphaTestSubMeshes.dispose();
  14364. this._particleSystems.dispose();
  14365. this._spriteManagers.dispose();
  14366. };
  14367. /**
  14368. * Inserts the submesh in its correct queue depending on its material.
  14369. * @param subMesh The submesh to dispatch
  14370. */
  14371. RenderingGroup.prototype.dispatch = function (subMesh) {
  14372. var material = subMesh.getMaterial();
  14373. var mesh = subMesh.getMesh();
  14374. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  14375. this._transparentSubMeshes.push(subMesh);
  14376. }
  14377. else if (material.needAlphaTesting()) {
  14378. this._alphaTestSubMeshes.push(subMesh);
  14379. }
  14380. else {
  14381. this._opaqueSubMeshes.push(subMesh); // Opaque
  14382. }
  14383. };
  14384. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  14385. this._spriteManagers.push(spriteManager);
  14386. };
  14387. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  14388. this._particleSystems.push(particleSystem);
  14389. };
  14390. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  14391. if (this._particleSystems.length === 0) {
  14392. return;
  14393. }
  14394. // Particles
  14395. var activeCamera = this._scene.activeCamera;
  14396. this._scene._particlesDuration.beginMonitoring();
  14397. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  14398. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  14399. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  14400. continue;
  14401. }
  14402. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  14403. this._scene._activeParticles.addCount(particleSystem.render(), false);
  14404. }
  14405. }
  14406. this._scene._particlesDuration.endMonitoring(false);
  14407. };
  14408. RenderingGroup.prototype._renderSprites = function () {
  14409. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  14410. return;
  14411. }
  14412. // Sprites
  14413. var activeCamera = this._scene.activeCamera;
  14414. this._scene._spritesDuration.beginMonitoring();
  14415. for (var id = 0; id < this._spriteManagers.length; id++) {
  14416. var spriteManager = this._spriteManagers.data[id];
  14417. if (((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  14418. spriteManager.render();
  14419. }
  14420. }
  14421. this._scene._spritesDuration.endMonitoring(false);
  14422. };
  14423. return RenderingGroup;
  14424. }());
  14425. BABYLON.RenderingGroup = RenderingGroup;
  14426. })(BABYLON || (BABYLON = {}));
  14427. //# sourceMappingURL=babylon.renderingGroup.js.map
  14428. var BABYLON;
  14429. (function (BABYLON) {
  14430. var ClickInfo = (function () {
  14431. function ClickInfo() {
  14432. this._singleClick = false;
  14433. this._doubleClick = false;
  14434. this._hasSwiped = false;
  14435. this._ignore = false;
  14436. }
  14437. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  14438. get: function () {
  14439. return this._singleClick;
  14440. },
  14441. set: function (b) {
  14442. this._singleClick = b;
  14443. },
  14444. enumerable: true,
  14445. configurable: true
  14446. });
  14447. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  14448. get: function () {
  14449. return this._doubleClick;
  14450. },
  14451. set: function (b) {
  14452. this._doubleClick = b;
  14453. },
  14454. enumerable: true,
  14455. configurable: true
  14456. });
  14457. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  14458. get: function () {
  14459. return this._hasSwiped;
  14460. },
  14461. set: function (b) {
  14462. this._hasSwiped = b;
  14463. },
  14464. enumerable: true,
  14465. configurable: true
  14466. });
  14467. Object.defineProperty(ClickInfo.prototype, "ignore", {
  14468. get: function () {
  14469. return this._ignore;
  14470. },
  14471. set: function (b) {
  14472. this._ignore = b;
  14473. },
  14474. enumerable: true,
  14475. configurable: true
  14476. });
  14477. return ClickInfo;
  14478. }());
  14479. var PointerEventTypes = (function () {
  14480. function PointerEventTypes() {
  14481. }
  14482. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  14483. get: function () {
  14484. return PointerEventTypes._POINTERDOWN;
  14485. },
  14486. enumerable: true,
  14487. configurable: true
  14488. });
  14489. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  14490. get: function () {
  14491. return PointerEventTypes._POINTERUP;
  14492. },
  14493. enumerable: true,
  14494. configurable: true
  14495. });
  14496. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  14497. get: function () {
  14498. return PointerEventTypes._POINTERMOVE;
  14499. },
  14500. enumerable: true,
  14501. configurable: true
  14502. });
  14503. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  14504. get: function () {
  14505. return PointerEventTypes._POINTERWHEEL;
  14506. },
  14507. enumerable: true,
  14508. configurable: true
  14509. });
  14510. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  14511. get: function () {
  14512. return PointerEventTypes._POINTERPICK;
  14513. },
  14514. enumerable: true,
  14515. configurable: true
  14516. });
  14517. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  14518. get: function () {
  14519. return PointerEventTypes._POINTERTAP;
  14520. },
  14521. enumerable: true,
  14522. configurable: true
  14523. });
  14524. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  14525. get: function () {
  14526. return PointerEventTypes._POINTERDOUBLETAP;
  14527. },
  14528. enumerable: true,
  14529. configurable: true
  14530. });
  14531. return PointerEventTypes;
  14532. }());
  14533. PointerEventTypes._POINTERDOWN = 0x01;
  14534. PointerEventTypes._POINTERUP = 0x02;
  14535. PointerEventTypes._POINTERMOVE = 0x04;
  14536. PointerEventTypes._POINTERWHEEL = 0x08;
  14537. PointerEventTypes._POINTERPICK = 0x10;
  14538. PointerEventTypes._POINTERTAP = 0x20;
  14539. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  14540. BABYLON.PointerEventTypes = PointerEventTypes;
  14541. var PointerInfoBase = (function () {
  14542. function PointerInfoBase(type, event) {
  14543. this.type = type;
  14544. this.event = event;
  14545. }
  14546. return PointerInfoBase;
  14547. }());
  14548. BABYLON.PointerInfoBase = PointerInfoBase;
  14549. /**
  14550. * This class is used to store pointer related info for the onPrePointerObservable event.
  14551. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  14552. */
  14553. var PointerInfoPre = (function (_super) {
  14554. __extends(PointerInfoPre, _super);
  14555. function PointerInfoPre(type, event, localX, localY) {
  14556. var _this = _super.call(this, type, event) || this;
  14557. _this.skipOnPointerObservable = false;
  14558. _this.localPosition = new BABYLON.Vector2(localX, localY);
  14559. return _this;
  14560. }
  14561. return PointerInfoPre;
  14562. }(PointerInfoBase));
  14563. BABYLON.PointerInfoPre = PointerInfoPre;
  14564. /**
  14565. * This type contains all the data related to a pointer event in Babylon.js.
  14566. * 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.
  14567. */
  14568. var PointerInfo = (function (_super) {
  14569. __extends(PointerInfo, _super);
  14570. function PointerInfo(type, event, pickInfo) {
  14571. var _this = _super.call(this, type, event) || this;
  14572. _this.pickInfo = pickInfo;
  14573. return _this;
  14574. }
  14575. return PointerInfo;
  14576. }(PointerInfoBase));
  14577. BABYLON.PointerInfo = PointerInfo;
  14578. /**
  14579. * This class is used by the onRenderingGroupObservable
  14580. */
  14581. var RenderingGroupInfo = (function () {
  14582. function RenderingGroupInfo() {
  14583. }
  14584. return RenderingGroupInfo;
  14585. }());
  14586. /**
  14587. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  14588. * This stage will be fired no matter what
  14589. */
  14590. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  14591. /**
  14592. * Called before opaque object are rendered.
  14593. * This stage will be fired only if there's 3D Opaque content to render
  14594. */
  14595. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  14596. /**
  14597. * Called after the opaque objects are rendered and before the transparent ones
  14598. * This stage will be fired only if there's 3D transparent content to render
  14599. */
  14600. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  14601. /**
  14602. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  14603. * This stage will be fired no matter what
  14604. */
  14605. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  14606. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  14607. /**
  14608. * Represents a scene to be rendered by the engine.
  14609. * @see http://doc.babylonjs.com/page.php?p=21911
  14610. */
  14611. var Scene = (function () {
  14612. /**
  14613. * @constructor
  14614. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  14615. */
  14616. function Scene(engine) {
  14617. // Members
  14618. this.autoClear = true;
  14619. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  14620. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  14621. this.forceWireframe = false;
  14622. this._forcePointsCloud = false;
  14623. this.forceShowBoundingBoxes = false;
  14624. this.animationsEnabled = true;
  14625. this.constantlyUpdateMeshUnderPointer = false;
  14626. this.useRightHandedSystem = false;
  14627. this.hoverCursor = "pointer";
  14628. // Metadata
  14629. this.metadata = null;
  14630. // Events
  14631. /**
  14632. * An event triggered when the scene is disposed.
  14633. * @type {BABYLON.Observable}
  14634. */
  14635. this.onDisposeObservable = new BABYLON.Observable();
  14636. /**
  14637. * An event triggered before rendering the scene
  14638. * @type {BABYLON.Observable}
  14639. */
  14640. this.onBeforeRenderObservable = new BABYLON.Observable();
  14641. /**
  14642. * An event triggered after rendering the scene
  14643. * @type {BABYLON.Observable}
  14644. */
  14645. this.onAfterRenderObservable = new BABYLON.Observable();
  14646. /**
  14647. * An event triggered when the scene is ready
  14648. * @type {BABYLON.Observable}
  14649. */
  14650. this.onReadyObservable = new BABYLON.Observable();
  14651. /**
  14652. * An event triggered before rendering a camera
  14653. * @type {BABYLON.Observable}
  14654. */
  14655. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  14656. /**
  14657. * An event triggered after rendering a camera
  14658. * @type {BABYLON.Observable}
  14659. */
  14660. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  14661. /**
  14662. * An event triggered when a camera is created
  14663. * @type {BABYLON.Observable}
  14664. */
  14665. this.onNewCameraAddedObservable = new BABYLON.Observable();
  14666. /**
  14667. * An event triggered when a camera is removed
  14668. * @type {BABYLON.Observable}
  14669. */
  14670. this.onCameraRemovedObservable = new BABYLON.Observable();
  14671. /**
  14672. * An event triggered when a light is created
  14673. * @type {BABYLON.Observable}
  14674. */
  14675. this.onNewLightAddedObservable = new BABYLON.Observable();
  14676. /**
  14677. * An event triggered when a light is removed
  14678. * @type {BABYLON.Observable}
  14679. */
  14680. this.onLightRemovedObservable = new BABYLON.Observable();
  14681. /**
  14682. * An event triggered when a geometry is created
  14683. * @type {BABYLON.Observable}
  14684. */
  14685. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  14686. /**
  14687. * An event triggered when a geometry is removed
  14688. * @type {BABYLON.Observable}
  14689. */
  14690. this.onGeometryRemovedObservable = new BABYLON.Observable();
  14691. /**
  14692. * An event triggered when a mesh is created
  14693. * @type {BABYLON.Observable}
  14694. */
  14695. this.onNewMeshAddedObservable = new BABYLON.Observable();
  14696. /**
  14697. * An event triggered when a mesh is removed
  14698. * @type {BABYLON.Observable}
  14699. */
  14700. this.onMeshRemovedObservable = new BABYLON.Observable();
  14701. /**
  14702. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  14703. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  14704. * 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)
  14705. */
  14706. this.onRenderingGroupObservable = new BABYLON.Observable();
  14707. // Animations
  14708. this.animations = [];
  14709. /**
  14710. * 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).
  14711. * You have the possibility to skip the 3D Engine process and the call to onPointerObservable by setting PointerInfoBase.skipOnPointerObservable to true
  14712. */
  14713. this.onPrePointerObservable = new BABYLON.Observable();
  14714. /**
  14715. * Observable event triggered each time an input event is received from the rendering canvas
  14716. */
  14717. this.onPointerObservable = new BABYLON.Observable();
  14718. this._meshPickProceed = false;
  14719. this._previousHasSwiped = false;
  14720. this._currentPickResult = null;
  14721. this._previousPickResult = null;
  14722. this._isButtonPressed = false;
  14723. this._doubleClickOccured = false;
  14724. 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
  14725. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  14726. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  14727. this._startingPointerTime = 0;
  14728. this._previousStartingPointerTime = 0;
  14729. // Fog
  14730. /**
  14731. * is fog enabled on this scene.
  14732. * @type {boolean}
  14733. */
  14734. this._fogEnabled = true;
  14735. this._fogMode = Scene.FOGMODE_NONE;
  14736. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  14737. this.fogDensity = 0.1;
  14738. this.fogStart = 0;
  14739. this.fogEnd = 1000.0;
  14740. // Lights
  14741. /**
  14742. * is shadow enabled on this scene.
  14743. * @type {boolean}
  14744. */
  14745. this._shadowsEnabled = true;
  14746. /**
  14747. * is light enabled on this scene.
  14748. * @type {boolean}
  14749. */
  14750. this._lightsEnabled = true;
  14751. /**
  14752. * All of the lights added to this scene.
  14753. * @see BABYLON.Light
  14754. * @type {BABYLON.Light[]}
  14755. */
  14756. this.lights = new Array();
  14757. // Cameras
  14758. /**
  14759. * All of the cameras added to this scene.
  14760. * @see BABYLON.Camera
  14761. * @type {BABYLON.Camera[]}
  14762. */
  14763. this.cameras = new Array();
  14764. this.activeCameras = new Array();
  14765. // Meshes
  14766. /**
  14767. * All of the (abstract) meshes added to this scene.
  14768. * @see BABYLON.AbstractMesh
  14769. * @type {BABYLON.AbstractMesh[]}
  14770. */
  14771. this.meshes = new Array();
  14772. // Geometries
  14773. this._geometries = new Array();
  14774. this.materials = new Array();
  14775. this.multiMaterials = new Array();
  14776. // Textures
  14777. this._texturesEnabled = true;
  14778. this.textures = new Array();
  14779. // Particles
  14780. this.particlesEnabled = true;
  14781. this.particleSystems = new Array();
  14782. // Sprites
  14783. this.spritesEnabled = true;
  14784. this.spriteManagers = new Array();
  14785. // Layers
  14786. this.layers = new Array();
  14787. this.highlightLayers = new Array();
  14788. // Skeletons
  14789. this._skeletonsEnabled = true;
  14790. this.skeletons = new Array();
  14791. // Morph targets
  14792. this.morphTargetManagers = new Array();
  14793. // Lens flares
  14794. this.lensFlaresEnabled = true;
  14795. this.lensFlareSystems = new Array();
  14796. // Collisions
  14797. this.collisionsEnabled = true;
  14798. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  14799. // Postprocesses
  14800. this.postProcessesEnabled = true;
  14801. // Customs render targets
  14802. this.renderTargetsEnabled = true;
  14803. this.dumpNextRenderTargets = false;
  14804. this.customRenderTargets = new Array();
  14805. // Imported meshes
  14806. this.importedMeshesFiles = new Array();
  14807. // Probes
  14808. this.probesEnabled = true;
  14809. this.reflectionProbes = new Array();
  14810. this._actionManagers = new Array();
  14811. this._meshesForIntersections = new BABYLON.SmartArray(256);
  14812. // Procedural textures
  14813. this.proceduralTexturesEnabled = true;
  14814. this._proceduralTextures = new Array();
  14815. this.soundTracks = new Array();
  14816. this._audioEnabled = true;
  14817. this._headphone = false;
  14818. // Performance counters
  14819. this._totalMeshesCounter = new BABYLON.PerfCounter();
  14820. this._totalLightsCounter = new BABYLON.PerfCounter();
  14821. this._totalMaterialsCounter = new BABYLON.PerfCounter();
  14822. this._totalTexturesCounter = new BABYLON.PerfCounter();
  14823. this._totalVertices = new BABYLON.PerfCounter();
  14824. this._activeIndices = new BABYLON.PerfCounter();
  14825. this._activeParticles = new BABYLON.PerfCounter();
  14826. this._lastFrameDuration = new BABYLON.PerfCounter();
  14827. this._evaluateActiveMeshesDuration = new BABYLON.PerfCounter();
  14828. this._renderTargetsDuration = new BABYLON.PerfCounter();
  14829. this._particlesDuration = new BABYLON.PerfCounter();
  14830. this._renderDuration = new BABYLON.PerfCounter();
  14831. this._spritesDuration = new BABYLON.PerfCounter();
  14832. this._activeBones = new BABYLON.PerfCounter();
  14833. this._animationTime = 0;
  14834. this.animationTimeScale = 1;
  14835. this._renderId = 0;
  14836. this._executeWhenReadyTimeoutId = -1;
  14837. this._intermediateRendering = false;
  14838. this._viewUpdateFlag = -1;
  14839. this._projectionUpdateFlag = -1;
  14840. this._toBeDisposed = new BABYLON.SmartArray(256);
  14841. this._pendingData = []; //ANY
  14842. this._activeMeshes = new BABYLON.SmartArray(256);
  14843. this._processedMaterials = new BABYLON.SmartArray(256);
  14844. this._renderTargets = new BABYLON.SmartArray(256);
  14845. this._activeParticleSystems = new BABYLON.SmartArray(256);
  14846. this._activeSkeletons = new BABYLON.SmartArray(32);
  14847. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  14848. this._activeAnimatables = new Array();
  14849. this._transformMatrix = BABYLON.Matrix.Zero();
  14850. this._edgesRenderers = new BABYLON.SmartArray(16);
  14851. this._uniqueIdCounter = 0;
  14852. this.offscreenRenderTarget = null;
  14853. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  14854. this._engine.scenes.push(this);
  14855. this._uid = null;
  14856. this._renderingManager = new BABYLON.RenderingManager(this);
  14857. this.postProcessManager = new BABYLON.PostProcessManager(this);
  14858. if (BABYLON.OutlineRenderer) {
  14859. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  14860. }
  14861. this.attachControl();
  14862. if (BABYLON.SoundTrack) {
  14863. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  14864. }
  14865. //simplification queue
  14866. if (BABYLON.SimplificationQueue) {
  14867. this.simplificationQueue = new BABYLON.SimplificationQueue();
  14868. }
  14869. //collision coordinator initialization. For now legacy per default.
  14870. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  14871. // Uniform Buffer
  14872. this._createUbo();
  14873. }
  14874. Object.defineProperty(Scene, "FOGMODE_NONE", {
  14875. get: function () {
  14876. return Scene._FOGMODE_NONE;
  14877. },
  14878. enumerable: true,
  14879. configurable: true
  14880. });
  14881. Object.defineProperty(Scene, "FOGMODE_EXP", {
  14882. get: function () {
  14883. return Scene._FOGMODE_EXP;
  14884. },
  14885. enumerable: true,
  14886. configurable: true
  14887. });
  14888. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  14889. get: function () {
  14890. return Scene._FOGMODE_EXP2;
  14891. },
  14892. enumerable: true,
  14893. configurable: true
  14894. });
  14895. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  14896. get: function () {
  14897. return Scene._FOGMODE_LINEAR;
  14898. },
  14899. enumerable: true,
  14900. configurable: true
  14901. });
  14902. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  14903. get: function () {
  14904. return this._forcePointsCloud;
  14905. },
  14906. set: function (value) {
  14907. if (this._forcePointsCloud === value) {
  14908. return;
  14909. }
  14910. this._forcePointsCloud = value;
  14911. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  14912. },
  14913. enumerable: true,
  14914. configurable: true
  14915. });
  14916. Object.defineProperty(Scene.prototype, "onDispose", {
  14917. set: function (callback) {
  14918. if (this._onDisposeObserver) {
  14919. this.onDisposeObservable.remove(this._onDisposeObserver);
  14920. }
  14921. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  14922. },
  14923. enumerable: true,
  14924. configurable: true
  14925. });
  14926. Object.defineProperty(Scene.prototype, "beforeRender", {
  14927. set: function (callback) {
  14928. if (this._onBeforeRenderObserver) {
  14929. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  14930. }
  14931. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  14932. },
  14933. enumerable: true,
  14934. configurable: true
  14935. });
  14936. Object.defineProperty(Scene.prototype, "afterRender", {
  14937. set: function (callback) {
  14938. if (this._onAfterRenderObserver) {
  14939. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  14940. }
  14941. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  14942. },
  14943. enumerable: true,
  14944. configurable: true
  14945. });
  14946. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  14947. set: function (callback) {
  14948. if (this._onBeforeCameraRenderObserver) {
  14949. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  14950. }
  14951. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  14952. },
  14953. enumerable: true,
  14954. configurable: true
  14955. });
  14956. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  14957. set: function (callback) {
  14958. if (this._onAfterCameraRenderObserver) {
  14959. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  14960. }
  14961. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  14962. },
  14963. enumerable: true,
  14964. configurable: true
  14965. });
  14966. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  14967. get: function () {
  14968. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  14969. },
  14970. enumerable: true,
  14971. configurable: true
  14972. });
  14973. Object.defineProperty(Scene.prototype, "fogEnabled", {
  14974. get: function () {
  14975. return this._fogEnabled;
  14976. },
  14977. set: function (value) {
  14978. if (this._fogEnabled === value) {
  14979. return;
  14980. }
  14981. this._fogEnabled = value;
  14982. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  14983. },
  14984. enumerable: true,
  14985. configurable: true
  14986. });
  14987. Object.defineProperty(Scene.prototype, "fogMode", {
  14988. get: function () {
  14989. return this._fogMode;
  14990. },
  14991. set: function (value) {
  14992. if (this._fogMode === value) {
  14993. return;
  14994. }
  14995. this._fogMode = value;
  14996. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  14997. },
  14998. enumerable: true,
  14999. configurable: true
  15000. });
  15001. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  15002. get: function () {
  15003. return this._shadowsEnabled;
  15004. },
  15005. set: function (value) {
  15006. if (this._shadowsEnabled === value) {
  15007. return;
  15008. }
  15009. this._shadowsEnabled = value;
  15010. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  15011. },
  15012. enumerable: true,
  15013. configurable: true
  15014. });
  15015. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  15016. get: function () {
  15017. return this._lightsEnabled;
  15018. },
  15019. set: function (value) {
  15020. if (this._lightsEnabled === value) {
  15021. return;
  15022. }
  15023. this._lightsEnabled = value;
  15024. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  15025. },
  15026. enumerable: true,
  15027. configurable: true
  15028. });
  15029. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  15030. get: function () {
  15031. if (!this._defaultMaterial) {
  15032. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  15033. }
  15034. return this._defaultMaterial;
  15035. },
  15036. set: function (value) {
  15037. this._defaultMaterial = value;
  15038. },
  15039. enumerable: true,
  15040. configurable: true
  15041. });
  15042. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  15043. get: function () {
  15044. return this._texturesEnabled;
  15045. },
  15046. set: function (value) {
  15047. if (this._texturesEnabled === value) {
  15048. return;
  15049. }
  15050. this._texturesEnabled = value;
  15051. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  15052. },
  15053. enumerable: true,
  15054. configurable: true
  15055. });
  15056. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  15057. get: function () {
  15058. return this._skeletonsEnabled;
  15059. },
  15060. set: function (value) {
  15061. if (this._skeletonsEnabled === value) {
  15062. return;
  15063. }
  15064. this._skeletonsEnabled = value;
  15065. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  15066. },
  15067. enumerable: true,
  15068. configurable: true
  15069. });
  15070. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  15071. get: function () {
  15072. if (!this._postProcessRenderPipelineManager) {
  15073. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  15074. }
  15075. return this._postProcessRenderPipelineManager;
  15076. },
  15077. enumerable: true,
  15078. configurable: true
  15079. });
  15080. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  15081. get: function () {
  15082. return this._frustumPlanes;
  15083. },
  15084. enumerable: true,
  15085. configurable: true
  15086. });
  15087. Object.defineProperty(Scene.prototype, "debugLayer", {
  15088. // Properties
  15089. get: function () {
  15090. if (!this._debugLayer) {
  15091. this._debugLayer = new BABYLON.DebugLayer(this);
  15092. }
  15093. return this._debugLayer;
  15094. },
  15095. enumerable: true,
  15096. configurable: true
  15097. });
  15098. Object.defineProperty(Scene.prototype, "workerCollisions", {
  15099. get: function () {
  15100. return this._workerCollisions;
  15101. },
  15102. set: function (enabled) {
  15103. if (!BABYLON.CollisionCoordinatorLegacy) {
  15104. return;
  15105. }
  15106. enabled = (enabled && !!Worker);
  15107. this._workerCollisions = enabled;
  15108. if (this.collisionCoordinator) {
  15109. this.collisionCoordinator.destroy();
  15110. }
  15111. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  15112. this.collisionCoordinator.init(this);
  15113. },
  15114. enumerable: true,
  15115. configurable: true
  15116. });
  15117. Object.defineProperty(Scene.prototype, "selectionOctree", {
  15118. get: function () {
  15119. return this._selectionOctree;
  15120. },
  15121. enumerable: true,
  15122. configurable: true
  15123. });
  15124. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  15125. /**
  15126. * The mesh that is currently under the pointer.
  15127. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  15128. */
  15129. get: function () {
  15130. return this._pointerOverMesh;
  15131. },
  15132. enumerable: true,
  15133. configurable: true
  15134. });
  15135. Object.defineProperty(Scene.prototype, "pointerX", {
  15136. /**
  15137. * Current on-screen X position of the pointer
  15138. * @return {number} X position of the pointer
  15139. */
  15140. get: function () {
  15141. return this._pointerX;
  15142. },
  15143. enumerable: true,
  15144. configurable: true
  15145. });
  15146. Object.defineProperty(Scene.prototype, "pointerY", {
  15147. /**
  15148. * Current on-screen Y position of the pointer
  15149. * @return {number} Y position of the pointer
  15150. */
  15151. get: function () {
  15152. return this._pointerY;
  15153. },
  15154. enumerable: true,
  15155. configurable: true
  15156. });
  15157. Scene.prototype.getCachedMaterial = function () {
  15158. return this._cachedMaterial;
  15159. };
  15160. Scene.prototype.getCachedEffect = function () {
  15161. return this._cachedEffect;
  15162. };
  15163. Scene.prototype.getCachedVisibility = function () {
  15164. return this._cachedVisibility;
  15165. };
  15166. Scene.prototype.isCachedMaterialValid = function (material, effect, visibility) {
  15167. if (visibility === void 0) { visibility = 0; }
  15168. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  15169. };
  15170. Scene.prototype.getBoundingBoxRenderer = function () {
  15171. if (!this._boundingBoxRenderer) {
  15172. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  15173. }
  15174. return this._boundingBoxRenderer;
  15175. };
  15176. Scene.prototype.getOutlineRenderer = function () {
  15177. return this._outlineRenderer;
  15178. };
  15179. Scene.prototype.getEngine = function () {
  15180. return this._engine;
  15181. };
  15182. Scene.prototype.getTotalVertices = function () {
  15183. return this._totalVertices.current;
  15184. };
  15185. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  15186. get: function () {
  15187. return this._totalVertices;
  15188. },
  15189. enumerable: true,
  15190. configurable: true
  15191. });
  15192. Scene.prototype.getActiveIndices = function () {
  15193. return this._activeIndices.current;
  15194. };
  15195. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  15196. get: function () {
  15197. return this._activeIndices;
  15198. },
  15199. enumerable: true,
  15200. configurable: true
  15201. });
  15202. Scene.prototype.getActiveParticles = function () {
  15203. return this._activeParticles.current;
  15204. };
  15205. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  15206. get: function () {
  15207. return this._activeParticles;
  15208. },
  15209. enumerable: true,
  15210. configurable: true
  15211. });
  15212. Scene.prototype.getActiveBones = function () {
  15213. return this._activeBones.current;
  15214. };
  15215. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  15216. get: function () {
  15217. return this._activeBones;
  15218. },
  15219. enumerable: true,
  15220. configurable: true
  15221. });
  15222. // Stats
  15223. Scene.prototype.getLastFrameDuration = function () {
  15224. return this._lastFrameDuration.current;
  15225. };
  15226. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  15227. get: function () {
  15228. return this._lastFrameDuration;
  15229. },
  15230. enumerable: true,
  15231. configurable: true
  15232. });
  15233. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  15234. return this._evaluateActiveMeshesDuration.current;
  15235. };
  15236. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  15237. get: function () {
  15238. return this._evaluateActiveMeshesDuration;
  15239. },
  15240. enumerable: true,
  15241. configurable: true
  15242. });
  15243. Scene.prototype.getActiveMeshes = function () {
  15244. return this._activeMeshes;
  15245. };
  15246. Scene.prototype.getRenderTargetsDuration = function () {
  15247. return this._renderTargetsDuration.current;
  15248. };
  15249. Scene.prototype.getRenderDuration = function () {
  15250. return this._renderDuration.current;
  15251. };
  15252. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  15253. get: function () {
  15254. return this._renderDuration;
  15255. },
  15256. enumerable: true,
  15257. configurable: true
  15258. });
  15259. Scene.prototype.getParticlesDuration = function () {
  15260. return this._particlesDuration.current;
  15261. };
  15262. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  15263. get: function () {
  15264. return this._particlesDuration;
  15265. },
  15266. enumerable: true,
  15267. configurable: true
  15268. });
  15269. Scene.prototype.getSpritesDuration = function () {
  15270. return this._spritesDuration.current;
  15271. };
  15272. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  15273. get: function () {
  15274. return this._spritesDuration;
  15275. },
  15276. enumerable: true,
  15277. configurable: true
  15278. });
  15279. Scene.prototype.getAnimationRatio = function () {
  15280. return this._animationRatio;
  15281. };
  15282. Scene.prototype.getRenderId = function () {
  15283. return this._renderId;
  15284. };
  15285. Scene.prototype.incrementRenderId = function () {
  15286. this._renderId++;
  15287. };
  15288. Scene.prototype._updatePointerPosition = function (evt) {
  15289. var canvasRect = this._engine.getRenderingCanvasClientRect();
  15290. this._pointerX = evt.clientX - canvasRect.left;
  15291. this._pointerY = evt.clientY - canvasRect.top;
  15292. this._unTranslatedPointerX = this._pointerX;
  15293. this._unTranslatedPointerY = this._pointerY;
  15294. if (this.cameraToUseForPointers) {
  15295. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  15296. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  15297. }
  15298. };
  15299. Scene.prototype._createUbo = function () {
  15300. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, null, true);
  15301. this._sceneUbo.addUniform("viewProjection", 16);
  15302. this._sceneUbo.addUniform("view", 16);
  15303. };
  15304. // Pointers handling
  15305. /**
  15306. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  15307. * @param attachUp defines if you want to attach events to pointerup
  15308. * @param attachDown defines if you want to attach events to pointerdown
  15309. * @param attachMove defines if you want to attach events to pointermove
  15310. */
  15311. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  15312. var _this = this;
  15313. if (attachUp === void 0) { attachUp = true; }
  15314. if (attachDown === void 0) { attachDown = true; }
  15315. if (attachMove === void 0) { attachMove = true; }
  15316. this._initActionManager = function (act, clickInfo) {
  15317. if (!_this._meshPickProceed) {
  15318. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  15319. _this._currentPickResult = pickResult;
  15320. if (pickResult) {
  15321. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  15322. }
  15323. _this._meshPickProceed = true;
  15324. }
  15325. return act;
  15326. };
  15327. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  15328. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  15329. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  15330. btn !== _this._previousButtonPressed) {
  15331. _this._doubleClickOccured = false;
  15332. clickInfo.singleClick = true;
  15333. clickInfo.ignore = false;
  15334. cb(clickInfo, _this._currentPickResult);
  15335. }
  15336. };
  15337. this._initClickEvent = function (obs1, obs2, evt, cb) {
  15338. var clickInfo = new ClickInfo();
  15339. _this._currentPickResult = null;
  15340. var act;
  15341. var checkPicking = obs1.hasSpecificMask(PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(PointerEventTypes.POINTERPICK)
  15342. || obs1.hasSpecificMask(PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERTAP)
  15343. || obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  15344. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  15345. act = _this._initActionManager(act, clickInfo);
  15346. if (act)
  15347. checkPicking = act.hasPickTriggers;
  15348. }
  15349. if (checkPicking) {
  15350. var btn = evt.button;
  15351. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  15352. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  15353. if (!clickInfo.hasSwiped) {
  15354. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  15355. if (!checkSingleClickImmediately) {
  15356. checkSingleClickImmediately = !obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) &&
  15357. !obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  15358. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  15359. act = _this._initActionManager(act, clickInfo);
  15360. if (act)
  15361. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  15362. }
  15363. }
  15364. if (checkSingleClickImmediately) {
  15365. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  15366. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  15367. btn !== _this._previousButtonPressed) {
  15368. clickInfo.singleClick = true;
  15369. cb(clickInfo, _this._currentPickResult);
  15370. }
  15371. }
  15372. else {
  15373. // wait that no double click has been raised during the double click delay
  15374. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  15375. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  15376. }
  15377. var checkDoubleClick = obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) ||
  15378. obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  15379. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  15380. act = _this._initActionManager(act, clickInfo);
  15381. if (act)
  15382. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  15383. }
  15384. if (checkDoubleClick) {
  15385. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  15386. if (btn === _this._previousButtonPressed &&
  15387. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  15388. !_this._doubleClickOccured) {
  15389. // pointer has not moved for 2 clicks, it's a double click
  15390. if (!clickInfo.hasSwiped &&
  15391. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  15392. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  15393. _this._previousStartingPointerTime = 0;
  15394. _this._doubleClickOccured = true;
  15395. clickInfo.doubleClick = true;
  15396. clickInfo.ignore = false;
  15397. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout)
  15398. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  15399. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  15400. cb(clickInfo, _this._currentPickResult);
  15401. }
  15402. else {
  15403. _this._doubleClickOccured = false;
  15404. _this._previousStartingPointerTime = _this._startingPointerTime;
  15405. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  15406. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  15407. _this._previousButtonPressed = btn;
  15408. _this._previousHasSwiped = clickInfo.hasSwiped;
  15409. if (Scene.ExclusiveDoubleClickMode) {
  15410. if (_this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout) {
  15411. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  15412. }
  15413. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  15414. cb(clickInfo, _this._previousPickResult);
  15415. }
  15416. else {
  15417. cb(clickInfo, _this._currentPickResult);
  15418. }
  15419. }
  15420. }
  15421. else {
  15422. _this._doubleClickOccured = false;
  15423. _this._previousStartingPointerTime = _this._startingPointerTime;
  15424. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  15425. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  15426. _this._previousButtonPressed = btn;
  15427. _this._previousHasSwiped = clickInfo.hasSwiped;
  15428. }
  15429. }
  15430. }
  15431. }
  15432. clickInfo.ignore = true;
  15433. cb(clickInfo, _this._currentPickResult);
  15434. };
  15435. var spritePredicate = function (sprite) {
  15436. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  15437. };
  15438. this._onPointerMove = function (evt) {
  15439. _this._updatePointerPosition(evt);
  15440. // PreObservable support
  15441. if (_this.onPrePointerObservable.hasObservers()) {
  15442. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  15443. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  15444. _this.onPrePointerObservable.notifyObservers(pi, type);
  15445. if (pi.skipOnPointerObservable) {
  15446. return;
  15447. }
  15448. }
  15449. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  15450. return;
  15451. }
  15452. var canvas = _this._engine.getRenderingCanvas();
  15453. if (!_this.pointerMovePredicate) {
  15454. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && (_this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  15455. }
  15456. // Meshes
  15457. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  15458. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  15459. _this.setPointerOverSprite(null);
  15460. _this.setPointerOverMesh(pickResult.pickedMesh);
  15461. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  15462. if (_this._pointerOverMesh.actionManager.hoverCursor) {
  15463. canvas.style.cursor = _this._pointerOverMesh.actionManager.hoverCursor;
  15464. }
  15465. else {
  15466. canvas.style.cursor = _this.hoverCursor;
  15467. }
  15468. }
  15469. else {
  15470. canvas.style.cursor = "";
  15471. }
  15472. }
  15473. else {
  15474. _this.setPointerOverMesh(null);
  15475. // Sprites
  15476. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  15477. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  15478. _this.setPointerOverSprite(pickResult.pickedSprite);
  15479. if (_this._pointerOverSprite.actionManager && _this._pointerOverSprite.actionManager.hoverCursor) {
  15480. canvas.style.cursor = _this._pointerOverSprite.actionManager.hoverCursor;
  15481. }
  15482. else {
  15483. canvas.style.cursor = _this.hoverCursor;
  15484. }
  15485. }
  15486. else {
  15487. _this.setPointerOverSprite(null);
  15488. // Restore pointer
  15489. canvas.style.cursor = "";
  15490. }
  15491. }
  15492. if (_this.onPointerMove) {
  15493. _this.onPointerMove(evt, pickResult);
  15494. }
  15495. if (_this.onPointerObservable.hasObservers()) {
  15496. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  15497. var pi = new PointerInfo(type, evt, pickResult);
  15498. _this.onPointerObservable.notifyObservers(pi, type);
  15499. }
  15500. };
  15501. this._onPointerDown = function (evt) {
  15502. _this._isButtonPressed = true;
  15503. _this._pickedDownMesh = null;
  15504. _this._meshPickProceed = false;
  15505. _this._updatePointerPosition(evt);
  15506. // PreObservable support
  15507. if (_this.onPrePointerObservable.hasObservers()) {
  15508. var type = PointerEventTypes.POINTERDOWN;
  15509. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  15510. _this.onPrePointerObservable.notifyObservers(pi, type);
  15511. if (pi.skipOnPointerObservable) {
  15512. return;
  15513. }
  15514. }
  15515. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  15516. return;
  15517. }
  15518. _this._startingPointerPosition.x = _this._pointerX;
  15519. _this._startingPointerPosition.y = _this._pointerY;
  15520. _this._startingPointerTime = new Date().getTime();
  15521. if (!_this.pointerDownPredicate) {
  15522. _this.pointerDownPredicate = function (mesh) {
  15523. return mesh.isPickable && mesh.isVisible && mesh.isReady();
  15524. };
  15525. }
  15526. // Meshes
  15527. _this._pickedDownMesh = null;
  15528. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  15529. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  15530. _this._pickedDownMesh = pickResult.pickedMesh;
  15531. var actionManager = pickResult.pickedMesh.actionManager;
  15532. if (actionManager) {
  15533. if (actionManager.hasPickTriggers) {
  15534. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15535. switch (evt.button) {
  15536. case 0:
  15537. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15538. break;
  15539. case 1:
  15540. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15541. break;
  15542. case 2:
  15543. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15544. break;
  15545. }
  15546. }
  15547. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  15548. window.setTimeout((function () {
  15549. var _this = this;
  15550. 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);
  15551. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  15552. if (this._isButtonPressed &&
  15553. ((new Date().getTime() - this._startingPointerTime) > Scene.LongPressDelay) &&
  15554. (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold &&
  15555. Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold)) {
  15556. this._startingPointerTime = 0;
  15557. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15558. }
  15559. }
  15560. }).bind(_this), Scene.LongPressDelay);
  15561. }
  15562. }
  15563. }
  15564. if (_this.onPointerDown) {
  15565. _this.onPointerDown(evt, pickResult);
  15566. }
  15567. if (_this.onPointerObservable.hasObservers()) {
  15568. var type = PointerEventTypes.POINTERDOWN;
  15569. var pi = new PointerInfo(type, evt, pickResult);
  15570. _this.onPointerObservable.notifyObservers(pi, type);
  15571. }
  15572. // Sprites
  15573. _this._pickedDownSprite = null;
  15574. if (_this.spriteManagers.length > 0) {
  15575. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  15576. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  15577. if (pickResult.pickedSprite.actionManager) {
  15578. _this._pickedDownSprite = pickResult.pickedSprite;
  15579. switch (evt.button) {
  15580. case 0:
  15581. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  15582. break;
  15583. case 1:
  15584. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  15585. break;
  15586. case 2:
  15587. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  15588. break;
  15589. }
  15590. if (pickResult.pickedSprite.actionManager) {
  15591. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  15592. }
  15593. }
  15594. }
  15595. }
  15596. };
  15597. this._onPointerUp = function (evt) {
  15598. _this._isButtonPressed = false;
  15599. _this._pickedUpMesh = null;
  15600. _this._meshPickProceed = false;
  15601. _this._updatePointerPosition(evt);
  15602. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, (function (clickInfo, pickResult) {
  15603. // PreObservable support
  15604. if (this.onPrePointerObservable.hasObservers()) {
  15605. if (!clickInfo.ignore) {
  15606. if (!clickInfo.hasSwiped) {
  15607. if (clickInfo.singleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  15608. var type = PointerEventTypes.POINTERTAP;
  15609. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  15610. this.onPrePointerObservable.notifyObservers(pi, type);
  15611. if (pi.skipOnPointerObservable) {
  15612. return;
  15613. }
  15614. }
  15615. if (clickInfo.doubleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  15616. var type = PointerEventTypes.POINTERDOUBLETAP;
  15617. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  15618. this.onPrePointerObservable.notifyObservers(pi, type);
  15619. if (pi.skipOnPointerObservable) {
  15620. return;
  15621. }
  15622. }
  15623. }
  15624. }
  15625. else {
  15626. var type = PointerEventTypes.POINTERUP;
  15627. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  15628. this.onPrePointerObservable.notifyObservers(pi, type);
  15629. if (pi.skipOnPointerObservable) {
  15630. return;
  15631. }
  15632. }
  15633. }
  15634. if (!this.cameraToUseForPointers && !this.activeCamera) {
  15635. return;
  15636. }
  15637. if (!this.pointerUpPredicate) {
  15638. this.pointerUpPredicate = function (mesh) {
  15639. return mesh.isPickable && mesh.isVisible && mesh.isReady();
  15640. };
  15641. }
  15642. // Meshes
  15643. if (!this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || this.onPointerObservable.hasObservers())) {
  15644. this._initActionManager(null, clickInfo);
  15645. }
  15646. if (!pickResult) {
  15647. pickResult = this._currentPickResult;
  15648. }
  15649. if (pickResult && pickResult && pickResult.pickedMesh) {
  15650. this._pickedUpMesh = pickResult.pickedMesh;
  15651. if (this._pickedDownMesh === this._pickedUpMesh) {
  15652. if (this.onPointerPick) {
  15653. this.onPointerPick(evt, pickResult);
  15654. }
  15655. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  15656. var type = PointerEventTypes.POINTERPICK;
  15657. var pi = new PointerInfo(type, evt, pickResult);
  15658. this.onPointerObservable.notifyObservers(pi, type);
  15659. }
  15660. }
  15661. if (pickResult.pickedMesh.actionManager) {
  15662. if (clickInfo.ignore) {
  15663. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15664. }
  15665. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  15666. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15667. }
  15668. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  15669. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15670. }
  15671. }
  15672. }
  15673. if (this._pickedDownMesh &&
  15674. this._pickedDownMesh.actionManager &&
  15675. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  15676. this._pickedDownMesh !== this._pickedUpMesh) {
  15677. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  15678. }
  15679. if (this.onPointerUp) {
  15680. this.onPointerUp(evt, pickResult);
  15681. }
  15682. if (this.onPointerObservable.hasObservers()) {
  15683. if (!clickInfo.ignore) {
  15684. if (!clickInfo.hasSwiped) {
  15685. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  15686. var type = PointerEventTypes.POINTERTAP;
  15687. var pi = new PointerInfo(type, evt, pickResult);
  15688. this.onPointerObservable.notifyObservers(pi, type);
  15689. }
  15690. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  15691. var type = PointerEventTypes.POINTERDOUBLETAP;
  15692. var pi = new PointerInfo(type, evt, pickResult);
  15693. this.onPointerObservable.notifyObservers(pi, type);
  15694. }
  15695. }
  15696. }
  15697. else {
  15698. var type = PointerEventTypes.POINTERUP;
  15699. var pi = new PointerInfo(type, evt, pickResult);
  15700. this.onPointerObservable.notifyObservers(pi, type);
  15701. }
  15702. }
  15703. // Sprites
  15704. if (this.spriteManagers.length > 0) {
  15705. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, spritePredicate, false, this.cameraToUseForPointers);
  15706. if (pickResult.hit && pickResult.pickedSprite) {
  15707. if (pickResult.pickedSprite.actionManager) {
  15708. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  15709. if (pickResult.pickedSprite.actionManager) {
  15710. if (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold && Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold) {
  15711. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  15712. }
  15713. }
  15714. }
  15715. }
  15716. if (this._pickedDownSprite && this._pickedDownSprite.actionManager && this._pickedDownSprite !== pickResult.pickedSprite) {
  15717. this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pickedDownSprite, this, evt));
  15718. }
  15719. }
  15720. this._previousPickResult = this._currentPickResult;
  15721. }).bind(_this));
  15722. };
  15723. this._onKeyDown = function (evt) {
  15724. if (_this.actionManager) {
  15725. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  15726. }
  15727. };
  15728. this._onKeyUp = function (evt) {
  15729. if (_this.actionManager) {
  15730. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  15731. }
  15732. };
  15733. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  15734. var canvas = this._engine.getRenderingCanvas();
  15735. if (attachMove) {
  15736. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  15737. // Wheel
  15738. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  15739. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  15740. }
  15741. if (attachDown) {
  15742. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  15743. }
  15744. if (attachUp) {
  15745. canvas.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  15746. }
  15747. canvas.tabIndex = 1;
  15748. canvas.addEventListener("keydown", this._onKeyDown, false);
  15749. canvas.addEventListener("keyup", this._onKeyUp, false);
  15750. };
  15751. Scene.prototype.detachControl = function () {
  15752. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  15753. var canvas = this._engine.getRenderingCanvas();
  15754. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  15755. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  15756. canvas.removeEventListener(eventPrefix + "up", this._onPointerUp);
  15757. // Wheel
  15758. canvas.removeEventListener('mousewheel', this._onPointerMove);
  15759. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  15760. canvas.removeEventListener("keydown", this._onKeyDown);
  15761. canvas.removeEventListener("keyup", this._onKeyUp);
  15762. };
  15763. // Ready
  15764. Scene.prototype.isReady = function () {
  15765. if (this._pendingData.length > 0) {
  15766. return false;
  15767. }
  15768. var index;
  15769. // Geometries
  15770. for (index = 0; index < this._geometries.length; index++) {
  15771. var geometry = this._geometries[index];
  15772. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  15773. return false;
  15774. }
  15775. }
  15776. // Meshes
  15777. for (index = 0; index < this.meshes.length; index++) {
  15778. var mesh = this.meshes[index];
  15779. if (!mesh.isEnabled()) {
  15780. continue;
  15781. }
  15782. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  15783. continue;
  15784. }
  15785. if (!mesh.isReady()) {
  15786. return false;
  15787. }
  15788. var mat = mesh.material;
  15789. if (mat) {
  15790. if (!mat.isReady(mesh)) {
  15791. return false;
  15792. }
  15793. }
  15794. }
  15795. return true;
  15796. };
  15797. Scene.prototype.resetCachedMaterial = function () {
  15798. this._cachedMaterial = null;
  15799. this._cachedEffect = null;
  15800. this._cachedVisibility = null;
  15801. };
  15802. Scene.prototype.registerBeforeRender = function (func) {
  15803. this.onBeforeRenderObservable.add(func);
  15804. };
  15805. Scene.prototype.unregisterBeforeRender = function (func) {
  15806. this.onBeforeRenderObservable.removeCallback(func);
  15807. };
  15808. Scene.prototype.registerAfterRender = function (func) {
  15809. this.onAfterRenderObservable.add(func);
  15810. };
  15811. Scene.prototype.unregisterAfterRender = function (func) {
  15812. this.onAfterRenderObservable.removeCallback(func);
  15813. };
  15814. Scene.prototype._addPendingData = function (data) {
  15815. this._pendingData.push(data);
  15816. };
  15817. Scene.prototype._removePendingData = function (data) {
  15818. var index = this._pendingData.indexOf(data);
  15819. if (index !== -1) {
  15820. this._pendingData.splice(index, 1);
  15821. }
  15822. };
  15823. Scene.prototype.getWaitingItemsCount = function () {
  15824. return this._pendingData.length;
  15825. };
  15826. /**
  15827. * Registers a function to be executed when the scene is ready.
  15828. * @param {Function} func - the function to be executed.
  15829. */
  15830. Scene.prototype.executeWhenReady = function (func) {
  15831. var _this = this;
  15832. this.onReadyObservable.add(func);
  15833. if (this._executeWhenReadyTimeoutId !== -1) {
  15834. return;
  15835. }
  15836. this._executeWhenReadyTimeoutId = setTimeout(function () {
  15837. _this._checkIsReady();
  15838. }, 150);
  15839. };
  15840. Scene.prototype._checkIsReady = function () {
  15841. var _this = this;
  15842. if (this.isReady()) {
  15843. this.onReadyObservable.notifyObservers(this);
  15844. this.onReadyObservable.clear();
  15845. this._executeWhenReadyTimeoutId = -1;
  15846. return;
  15847. }
  15848. this._executeWhenReadyTimeoutId = setTimeout(function () {
  15849. _this._checkIsReady();
  15850. }, 150);
  15851. };
  15852. // Animations
  15853. /**
  15854. * Will start the animation sequence of a given target
  15855. * @param target - the target
  15856. * @param {number} from - from which frame should animation start
  15857. * @param {number} to - till which frame should animation run.
  15858. * @param {boolean} [loop] - should the animation loop
  15859. * @param {number} [speedRatio] - the speed in which to run the animation
  15860. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  15861. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  15862. * @return {BABYLON.Animatable} the animatable object created for this animation
  15863. * @see BABYLON.Animatable
  15864. * @see http://doc.babylonjs.com/page.php?p=22081
  15865. */
  15866. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  15867. if (speedRatio === void 0) { speedRatio = 1.0; }
  15868. this.stopAnimation(target);
  15869. if (!animatable) {
  15870. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  15871. }
  15872. // Local animations
  15873. if (target.animations) {
  15874. animatable.appendAnimations(target, target.animations);
  15875. }
  15876. // Children animations
  15877. if (target.getAnimatables) {
  15878. var animatables = target.getAnimatables();
  15879. for (var index = 0; index < animatables.length; index++) {
  15880. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  15881. }
  15882. }
  15883. animatable.reset();
  15884. return animatable;
  15885. };
  15886. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  15887. if (speedRatio === undefined) {
  15888. speedRatio = 1.0;
  15889. }
  15890. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  15891. return animatable;
  15892. };
  15893. Scene.prototype.getAnimatableByTarget = function (target) {
  15894. for (var index = 0; index < this._activeAnimatables.length; index++) {
  15895. if (this._activeAnimatables[index].target === target) {
  15896. return this._activeAnimatables[index];
  15897. }
  15898. }
  15899. return null;
  15900. };
  15901. Object.defineProperty(Scene.prototype, "Animatables", {
  15902. get: function () {
  15903. return this._activeAnimatables;
  15904. },
  15905. enumerable: true,
  15906. configurable: true
  15907. });
  15908. /**
  15909. * Will stop the animation of the given target
  15910. * @param target - the target
  15911. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  15912. * @see beginAnimation
  15913. */
  15914. Scene.prototype.stopAnimation = function (target, animationName) {
  15915. var animatable = this.getAnimatableByTarget(target);
  15916. if (animatable) {
  15917. animatable.stop(animationName);
  15918. }
  15919. };
  15920. Scene.prototype._animate = function () {
  15921. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  15922. return;
  15923. }
  15924. // Getting time
  15925. var now = BABYLON.Tools.Now;
  15926. if (!this._animationTimeLast) {
  15927. if (this._pendingData.length > 0) {
  15928. return;
  15929. }
  15930. this._animationTimeLast = now;
  15931. }
  15932. var deltaTime = (now - this._animationTimeLast) * this.animationTimeScale;
  15933. this._animationTime += deltaTime;
  15934. this._animationTimeLast = now;
  15935. for (var index = 0; index < this._activeAnimatables.length; index++) {
  15936. this._activeAnimatables[index]._animate(this._animationTime);
  15937. }
  15938. };
  15939. // Matrix
  15940. Scene.prototype.getViewMatrix = function () {
  15941. return this._viewMatrix;
  15942. };
  15943. Scene.prototype.getProjectionMatrix = function () {
  15944. return this._projectionMatrix;
  15945. };
  15946. Scene.prototype.getTransformMatrix = function () {
  15947. return this._transformMatrix;
  15948. };
  15949. Scene.prototype.setTransformMatrix = function (view, projection) {
  15950. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  15951. return;
  15952. }
  15953. this._viewUpdateFlag = view.updateFlag;
  15954. this._projectionUpdateFlag = projection.updateFlag;
  15955. this._viewMatrix = view;
  15956. this._projectionMatrix = projection;
  15957. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  15958. // Update frustum
  15959. if (!this._frustumPlanes) {
  15960. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  15961. }
  15962. else {
  15963. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  15964. }
  15965. if (this._sceneUbo.useUbo) {
  15966. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  15967. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  15968. this._sceneUbo.update();
  15969. }
  15970. };
  15971. Scene.prototype.getSceneUniformBuffer = function () {
  15972. return this._sceneUbo;
  15973. };
  15974. // Methods
  15975. Scene.prototype.getUniqueId = function () {
  15976. var result = this._uniqueIdCounter;
  15977. this._uniqueIdCounter++;
  15978. return result;
  15979. };
  15980. Scene.prototype.addMesh = function (newMesh) {
  15981. newMesh.uniqueId = this.getUniqueId();
  15982. var position = this.meshes.push(newMesh);
  15983. //notify the collision coordinator
  15984. if (this.collisionCoordinator) {
  15985. this.collisionCoordinator.onMeshAdded(newMesh);
  15986. }
  15987. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  15988. };
  15989. Scene.prototype.removeMesh = function (toRemove) {
  15990. var index = this.meshes.indexOf(toRemove);
  15991. if (index !== -1) {
  15992. // Remove from the scene if mesh found
  15993. this.meshes.splice(index, 1);
  15994. }
  15995. //notify the collision coordinator
  15996. if (this.collisionCoordinator) {
  15997. this.collisionCoordinator.onMeshRemoved(toRemove);
  15998. }
  15999. this.onMeshRemovedObservable.notifyObservers(toRemove);
  16000. return index;
  16001. };
  16002. Scene.prototype.removeSkeleton = function (toRemove) {
  16003. var index = this.skeletons.indexOf(toRemove);
  16004. if (index !== -1) {
  16005. // Remove from the scene if found
  16006. this.skeletons.splice(index, 1);
  16007. }
  16008. return index;
  16009. };
  16010. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  16011. var index = this.morphTargetManagers.indexOf(toRemove);
  16012. if (index !== -1) {
  16013. // Remove from the scene if found
  16014. this.morphTargetManagers.splice(index, 1);
  16015. }
  16016. return index;
  16017. };
  16018. Scene.prototype.removeLight = function (toRemove) {
  16019. var index = this.lights.indexOf(toRemove);
  16020. if (index !== -1) {
  16021. // Remove from the scene if mesh found
  16022. this.lights.splice(index, 1);
  16023. }
  16024. this.onLightRemovedObservable.notifyObservers(toRemove);
  16025. return index;
  16026. };
  16027. Scene.prototype.removeCamera = function (toRemove) {
  16028. var index = this.cameras.indexOf(toRemove);
  16029. if (index !== -1) {
  16030. // Remove from the scene if mesh found
  16031. this.cameras.splice(index, 1);
  16032. }
  16033. // Remove from activeCameras
  16034. var index2 = this.activeCameras.indexOf(toRemove);
  16035. if (index2 !== -1) {
  16036. // Remove from the scene if mesh found
  16037. this.activeCameras.splice(index2, 1);
  16038. }
  16039. // Reset the activeCamera
  16040. if (this.activeCamera === toRemove) {
  16041. if (this.cameras.length > 0) {
  16042. this.activeCamera = this.cameras[0];
  16043. }
  16044. else {
  16045. this.activeCamera = null;
  16046. }
  16047. }
  16048. this.onCameraRemovedObservable.notifyObservers(toRemove);
  16049. return index;
  16050. };
  16051. Scene.prototype.addLight = function (newLight) {
  16052. newLight.uniqueId = this.getUniqueId();
  16053. var position = this.lights.push(newLight);
  16054. this.onNewLightAddedObservable.notifyObservers(newLight);
  16055. };
  16056. Scene.prototype.addCamera = function (newCamera) {
  16057. newCamera.uniqueId = this.getUniqueId();
  16058. var position = this.cameras.push(newCamera);
  16059. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  16060. };
  16061. /**
  16062. * Switch active camera
  16063. * @param {Camera} newCamera - new active camera
  16064. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  16065. */
  16066. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  16067. if (attachControl === void 0) { attachControl = true; }
  16068. var canvas = this._engine.getRenderingCanvas();
  16069. this.activeCamera.detachControl(canvas);
  16070. this.activeCamera = newCamera;
  16071. if (attachControl) {
  16072. newCamera.attachControl(canvas);
  16073. }
  16074. };
  16075. /**
  16076. * sets the active camera of the scene using its ID
  16077. * @param {string} id - the camera's ID
  16078. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  16079. * @see activeCamera
  16080. */
  16081. Scene.prototype.setActiveCameraByID = function (id) {
  16082. var camera = this.getCameraByID(id);
  16083. if (camera) {
  16084. this.activeCamera = camera;
  16085. return camera;
  16086. }
  16087. return null;
  16088. };
  16089. /**
  16090. * sets the active camera of the scene using its name
  16091. * @param {string} name - the camera's name
  16092. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  16093. * @see activeCamera
  16094. */
  16095. Scene.prototype.setActiveCameraByName = function (name) {
  16096. var camera = this.getCameraByName(name);
  16097. if (camera) {
  16098. this.activeCamera = camera;
  16099. return camera;
  16100. }
  16101. return null;
  16102. };
  16103. /**
  16104. * get a material using its id
  16105. * @param {string} the material's ID
  16106. * @return {BABYLON.Material|null} the material or null if none found.
  16107. */
  16108. Scene.prototype.getMaterialByID = function (id) {
  16109. for (var index = 0; index < this.materials.length; index++) {
  16110. if (this.materials[index].id === id) {
  16111. return this.materials[index];
  16112. }
  16113. }
  16114. return null;
  16115. };
  16116. /**
  16117. * get a material using its name
  16118. * @param {string} the material's name
  16119. * @return {BABYLON.Material|null} the material or null if none found.
  16120. */
  16121. Scene.prototype.getMaterialByName = function (name) {
  16122. for (var index = 0; index < this.materials.length; index++) {
  16123. if (this.materials[index].name === name) {
  16124. return this.materials[index];
  16125. }
  16126. }
  16127. return null;
  16128. };
  16129. Scene.prototype.getLensFlareSystemByName = function (name) {
  16130. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  16131. if (this.lensFlareSystems[index].name === name) {
  16132. return this.lensFlareSystems[index];
  16133. }
  16134. }
  16135. return null;
  16136. };
  16137. Scene.prototype.getLensFlareSystemByID = function (id) {
  16138. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  16139. if (this.lensFlareSystems[index].id === id) {
  16140. return this.lensFlareSystems[index];
  16141. }
  16142. }
  16143. return null;
  16144. };
  16145. Scene.prototype.getCameraByID = function (id) {
  16146. for (var index = 0; index < this.cameras.length; index++) {
  16147. if (this.cameras[index].id === id) {
  16148. return this.cameras[index];
  16149. }
  16150. }
  16151. return null;
  16152. };
  16153. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  16154. for (var index = 0; index < this.cameras.length; index++) {
  16155. if (this.cameras[index].uniqueId === uniqueId) {
  16156. return this.cameras[index];
  16157. }
  16158. }
  16159. return null;
  16160. };
  16161. /**
  16162. * get a camera using its name
  16163. * @param {string} the camera's name
  16164. * @return {BABYLON.Camera|null} the camera or null if none found.
  16165. */
  16166. Scene.prototype.getCameraByName = function (name) {
  16167. for (var index = 0; index < this.cameras.length; index++) {
  16168. if (this.cameras[index].name === name) {
  16169. return this.cameras[index];
  16170. }
  16171. }
  16172. return null;
  16173. };
  16174. /**
  16175. * get a bone using its id
  16176. * @param {string} the bone's id
  16177. * @return {BABYLON.Bone|null} the bone or null if not found
  16178. */
  16179. Scene.prototype.getBoneByID = function (id) {
  16180. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  16181. var skeleton = this.skeletons[skeletonIndex];
  16182. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  16183. if (skeleton.bones[boneIndex].id === id) {
  16184. return skeleton.bones[boneIndex];
  16185. }
  16186. }
  16187. }
  16188. return null;
  16189. };
  16190. /**
  16191. * get a bone using its id
  16192. * @param {string} the bone's name
  16193. * @return {BABYLON.Bone|null} the bone or null if not found
  16194. */
  16195. Scene.prototype.getBoneByName = function (name) {
  16196. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  16197. var skeleton = this.skeletons[skeletonIndex];
  16198. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  16199. if (skeleton.bones[boneIndex].name === name) {
  16200. return skeleton.bones[boneIndex];
  16201. }
  16202. }
  16203. }
  16204. return null;
  16205. };
  16206. /**
  16207. * get a light node using its name
  16208. * @param {string} the light's name
  16209. * @return {BABYLON.Light|null} the light or null if none found.
  16210. */
  16211. Scene.prototype.getLightByName = function (name) {
  16212. for (var index = 0; index < this.lights.length; index++) {
  16213. if (this.lights[index].name === name) {
  16214. return this.lights[index];
  16215. }
  16216. }
  16217. return null;
  16218. };
  16219. /**
  16220. * get a light node using its ID
  16221. * @param {string} the light's id
  16222. * @return {BABYLON.Light|null} the light or null if none found.
  16223. */
  16224. Scene.prototype.getLightByID = function (id) {
  16225. for (var index = 0; index < this.lights.length; index++) {
  16226. if (this.lights[index].id === id) {
  16227. return this.lights[index];
  16228. }
  16229. }
  16230. return null;
  16231. };
  16232. /**
  16233. * get a light node using its scene-generated unique ID
  16234. * @param {number} the light's unique id
  16235. * @return {BABYLON.Light|null} the light or null if none found.
  16236. */
  16237. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  16238. for (var index = 0; index < this.lights.length; index++) {
  16239. if (this.lights[index].uniqueId === uniqueId) {
  16240. return this.lights[index];
  16241. }
  16242. }
  16243. return null;
  16244. };
  16245. /**
  16246. * get a particle system by id
  16247. * @param id {number} the particle system id
  16248. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  16249. */
  16250. Scene.prototype.getParticleSystemByID = function (id) {
  16251. for (var index = 0; index < this.particleSystems.length; index++) {
  16252. if (this.particleSystems[index].id === id) {
  16253. return this.particleSystems[index];
  16254. }
  16255. }
  16256. return null;
  16257. };
  16258. /**
  16259. * get a geometry using its ID
  16260. * @param {string} the geometry's id
  16261. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  16262. */
  16263. Scene.prototype.getGeometryByID = function (id) {
  16264. for (var index = 0; index < this._geometries.length; index++) {
  16265. if (this._geometries[index].id === id) {
  16266. return this._geometries[index];
  16267. }
  16268. }
  16269. return null;
  16270. };
  16271. /**
  16272. * add a new geometry to this scene.
  16273. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  16274. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  16275. * @return {boolean} was the geometry added or not
  16276. */
  16277. Scene.prototype.pushGeometry = function (geometry, force) {
  16278. if (!force && this.getGeometryByID(geometry.id)) {
  16279. return false;
  16280. }
  16281. this._geometries.push(geometry);
  16282. //notify the collision coordinator
  16283. if (this.collisionCoordinator) {
  16284. this.collisionCoordinator.onGeometryAdded(geometry);
  16285. }
  16286. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  16287. return true;
  16288. };
  16289. /**
  16290. * Removes an existing geometry
  16291. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  16292. * @return {boolean} was the geometry removed or not
  16293. */
  16294. Scene.prototype.removeGeometry = function (geometry) {
  16295. var index = this._geometries.indexOf(geometry);
  16296. if (index > -1) {
  16297. this._geometries.splice(index, 1);
  16298. //notify the collision coordinator
  16299. if (this.collisionCoordinator) {
  16300. this.collisionCoordinator.onGeometryDeleted(geometry);
  16301. }
  16302. this.onGeometryRemovedObservable.notifyObservers(geometry);
  16303. return true;
  16304. }
  16305. return false;
  16306. };
  16307. Scene.prototype.getGeometries = function () {
  16308. return this._geometries;
  16309. };
  16310. /**
  16311. * Get the first added mesh found of a given ID
  16312. * @param {string} id - the id to search for
  16313. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  16314. */
  16315. Scene.prototype.getMeshByID = function (id) {
  16316. for (var index = 0; index < this.meshes.length; index++) {
  16317. if (this.meshes[index].id === id) {
  16318. return this.meshes[index];
  16319. }
  16320. }
  16321. return null;
  16322. };
  16323. Scene.prototype.getMeshesByID = function (id) {
  16324. return this.meshes.filter(function (m) {
  16325. return m.id === id;
  16326. });
  16327. };
  16328. /**
  16329. * Get a mesh with its auto-generated unique id
  16330. * @param {number} uniqueId - the unique id to search for
  16331. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  16332. */
  16333. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  16334. for (var index = 0; index < this.meshes.length; index++) {
  16335. if (this.meshes[index].uniqueId === uniqueId) {
  16336. return this.meshes[index];
  16337. }
  16338. }
  16339. return null;
  16340. };
  16341. /**
  16342. * Get a the last added mesh found of a given ID
  16343. * @param {string} id - the id to search for
  16344. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  16345. */
  16346. Scene.prototype.getLastMeshByID = function (id) {
  16347. for (var index = this.meshes.length - 1; index >= 0; index--) {
  16348. if (this.meshes[index].id === id) {
  16349. return this.meshes[index];
  16350. }
  16351. }
  16352. return null;
  16353. };
  16354. /**
  16355. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  16356. * @param {string} id - the id to search for
  16357. * @return {BABYLON.Node|null} the node found or null if not found at all.
  16358. */
  16359. Scene.prototype.getLastEntryByID = function (id) {
  16360. var index;
  16361. for (index = this.meshes.length - 1; index >= 0; index--) {
  16362. if (this.meshes[index].id === id) {
  16363. return this.meshes[index];
  16364. }
  16365. }
  16366. for (index = this.cameras.length - 1; index >= 0; index--) {
  16367. if (this.cameras[index].id === id) {
  16368. return this.cameras[index];
  16369. }
  16370. }
  16371. for (index = this.lights.length - 1; index >= 0; index--) {
  16372. if (this.lights[index].id === id) {
  16373. return this.lights[index];
  16374. }
  16375. }
  16376. return null;
  16377. };
  16378. Scene.prototype.getNodeByID = function (id) {
  16379. var mesh = this.getMeshByID(id);
  16380. if (mesh) {
  16381. return mesh;
  16382. }
  16383. var light = this.getLightByID(id);
  16384. if (light) {
  16385. return light;
  16386. }
  16387. var camera = this.getCameraByID(id);
  16388. if (camera) {
  16389. return camera;
  16390. }
  16391. var bone = this.getBoneByID(id);
  16392. return bone;
  16393. };
  16394. Scene.prototype.getNodeByName = function (name) {
  16395. var mesh = this.getMeshByName(name);
  16396. if (mesh) {
  16397. return mesh;
  16398. }
  16399. var light = this.getLightByName(name);
  16400. if (light) {
  16401. return light;
  16402. }
  16403. var camera = this.getCameraByName(name);
  16404. if (camera) {
  16405. return camera;
  16406. }
  16407. var bone = this.getBoneByName(name);
  16408. return bone;
  16409. };
  16410. Scene.prototype.getMeshByName = function (name) {
  16411. for (var index = 0; index < this.meshes.length; index++) {
  16412. if (this.meshes[index].name === name) {
  16413. return this.meshes[index];
  16414. }
  16415. }
  16416. return null;
  16417. };
  16418. Scene.prototype.getSoundByName = function (name) {
  16419. var index;
  16420. if (BABYLON.AudioEngine) {
  16421. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  16422. if (this.mainSoundTrack.soundCollection[index].name === name) {
  16423. return this.mainSoundTrack.soundCollection[index];
  16424. }
  16425. }
  16426. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  16427. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  16428. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  16429. return this.soundTracks[sdIndex].soundCollection[index];
  16430. }
  16431. }
  16432. }
  16433. }
  16434. return null;
  16435. };
  16436. Scene.prototype.getLastSkeletonByID = function (id) {
  16437. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  16438. if (this.skeletons[index].id === id) {
  16439. return this.skeletons[index];
  16440. }
  16441. }
  16442. return null;
  16443. };
  16444. Scene.prototype.getSkeletonById = function (id) {
  16445. for (var index = 0; index < this.skeletons.length; index++) {
  16446. if (this.skeletons[index].id === id) {
  16447. return this.skeletons[index];
  16448. }
  16449. }
  16450. return null;
  16451. };
  16452. Scene.prototype.getSkeletonByName = function (name) {
  16453. for (var index = 0; index < this.skeletons.length; index++) {
  16454. if (this.skeletons[index].name === name) {
  16455. return this.skeletons[index];
  16456. }
  16457. }
  16458. return null;
  16459. };
  16460. Scene.prototype.getMorphTargetManagerById = function (id) {
  16461. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  16462. if (this.morphTargetManagers[index].uniqueId === id) {
  16463. return this.morphTargetManagers[index];
  16464. }
  16465. }
  16466. return null;
  16467. };
  16468. Scene.prototype.isActiveMesh = function (mesh) {
  16469. return (this._activeMeshes.indexOf(mesh) !== -1);
  16470. };
  16471. /**
  16472. * Return a the first highlight layer of the scene with a given name.
  16473. * @param name The name of the highlight layer to look for.
  16474. * @return The highlight layer if found otherwise null.
  16475. */
  16476. Scene.prototype.getHighlightLayerByName = function (name) {
  16477. for (var index = 0; index < this.highlightLayers.length; index++) {
  16478. if (this.highlightLayers[index].name === name) {
  16479. return this.highlightLayers[index];
  16480. }
  16481. }
  16482. return null;
  16483. };
  16484. Object.defineProperty(Scene.prototype, "uid", {
  16485. /**
  16486. * Return a unique id as a string which can serve as an identifier for the scene
  16487. */
  16488. get: function () {
  16489. if (!this._uid) {
  16490. this._uid = BABYLON.Tools.RandomId();
  16491. }
  16492. return this._uid;
  16493. },
  16494. enumerable: true,
  16495. configurable: true
  16496. });
  16497. /**
  16498. * Add an externaly attached data from its key.
  16499. * This method call will fail and return false, if such key already exists.
  16500. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16501. * @param key the unique key that identifies the data
  16502. * @param data the data object to associate to the key for this Engine instance
  16503. * @return true if no such key were already present and the data was added successfully, false otherwise
  16504. */
  16505. Scene.prototype.addExternalData = function (key, data) {
  16506. if (!this._externalData) {
  16507. this._externalData = new BABYLON.StringDictionary();
  16508. }
  16509. return this._externalData.add(key, data);
  16510. };
  16511. /**
  16512. * Get an externaly attached data from its key
  16513. * @param key the unique key that identifies the data
  16514. * @return the associated data, if present (can be null), or undefined if not present
  16515. */
  16516. Scene.prototype.getExternalData = function (key) {
  16517. if (!this._externalData) {
  16518. return null;
  16519. }
  16520. return this._externalData.get(key);
  16521. };
  16522. /**
  16523. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16524. * @param key the unique key that identifies the data
  16525. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16526. * @return the associated data, can be null if the factory returned null.
  16527. */
  16528. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16529. if (!this._externalData) {
  16530. this._externalData = new BABYLON.StringDictionary();
  16531. }
  16532. return this._externalData.getOrAddWithFactory(key, factory);
  16533. };
  16534. /**
  16535. * Remove an externaly attached data from the Engine instance
  16536. * @param key the unique key that identifies the data
  16537. * @return true if the data was successfully removed, false if it doesn't exist
  16538. */
  16539. Scene.prototype.removeExternalData = function (key) {
  16540. return this._externalData.remove(key);
  16541. };
  16542. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  16543. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  16544. var material = subMesh.getMaterial();
  16545. if (mesh.showSubMeshesBoundingBox) {
  16546. this.getBoundingBoxRenderer().renderList.push(subMesh.getBoundingInfo().boundingBox);
  16547. }
  16548. if (material) {
  16549. // Render targets
  16550. if (material.getRenderTargetTextures) {
  16551. if (this._processedMaterials.indexOf(material) === -1) {
  16552. this._processedMaterials.push(material);
  16553. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  16554. }
  16555. }
  16556. // Dispatch
  16557. this._activeIndices.addCount(subMesh.indexCount, false);
  16558. this._renderingManager.dispatch(subMesh);
  16559. }
  16560. }
  16561. };
  16562. Scene.prototype._isInIntermediateRendering = function () {
  16563. return this._intermediateRendering;
  16564. };
  16565. Scene.prototype._evaluateActiveMeshes = function () {
  16566. this.activeCamera._activeMeshes.reset();
  16567. this._activeMeshes.reset();
  16568. this._renderingManager.reset();
  16569. this._processedMaterials.reset();
  16570. this._activeParticleSystems.reset();
  16571. this._activeSkeletons.reset();
  16572. this._softwareSkinnedMeshes.reset();
  16573. if (this._boundingBoxRenderer) {
  16574. this._boundingBoxRenderer.reset();
  16575. }
  16576. this._edgesRenderers.reset();
  16577. // Meshes
  16578. var meshes;
  16579. var len;
  16580. if (this._selectionOctree) {
  16581. var selection = this._selectionOctree.select(this._frustumPlanes);
  16582. meshes = selection.data;
  16583. len = selection.length;
  16584. }
  16585. else {
  16586. len = this.meshes.length;
  16587. meshes = this.meshes;
  16588. }
  16589. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  16590. var mesh = meshes[meshIndex];
  16591. if (mesh.isBlocked) {
  16592. continue;
  16593. }
  16594. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  16595. if (!mesh.isReady() || !mesh.isEnabled()) {
  16596. continue;
  16597. }
  16598. mesh.computeWorldMatrix();
  16599. // Intersections
  16600. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  16601. this._meshesForIntersections.pushNoDuplicate(mesh);
  16602. }
  16603. // Switch to current LOD
  16604. var meshLOD = mesh.getLOD(this.activeCamera);
  16605. if (!meshLOD) {
  16606. continue;
  16607. }
  16608. mesh._preActivate();
  16609. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  16610. this._activeMeshes.push(mesh);
  16611. this.activeCamera._activeMeshes.push(mesh);
  16612. mesh._activate(this._renderId);
  16613. this._activeMesh(mesh, meshLOD);
  16614. }
  16615. }
  16616. // Particle systems
  16617. this._particlesDuration.beginMonitoring();
  16618. var beforeParticlesDate = BABYLON.Tools.Now;
  16619. if (this.particlesEnabled) {
  16620. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  16621. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  16622. var particleSystem = this.particleSystems[particleIndex];
  16623. if (!particleSystem.isStarted()) {
  16624. continue;
  16625. }
  16626. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  16627. this._activeParticleSystems.push(particleSystem);
  16628. particleSystem.animate();
  16629. this._renderingManager.dispatchParticles(particleSystem);
  16630. }
  16631. }
  16632. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  16633. }
  16634. this._particlesDuration.endMonitoring(false);
  16635. };
  16636. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  16637. if (mesh.skeleton && this.skeletonsEnabled) {
  16638. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  16639. mesh.skeleton.prepare();
  16640. }
  16641. if (!mesh.computeBonesUsingShaders) {
  16642. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  16643. }
  16644. }
  16645. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  16646. this.getBoundingBoxRenderer().renderList.push(sourceMesh.getBoundingInfo().boundingBox);
  16647. }
  16648. if (sourceMesh._edgesRenderer) {
  16649. this._edgesRenderers.push(sourceMesh._edgesRenderer);
  16650. }
  16651. if (mesh && mesh.subMeshes) {
  16652. // Submeshes Octrees
  16653. var len;
  16654. var subMeshes;
  16655. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  16656. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  16657. len = intersections.length;
  16658. subMeshes = intersections.data;
  16659. }
  16660. else {
  16661. subMeshes = mesh.subMeshes;
  16662. len = subMeshes.length;
  16663. }
  16664. for (var subIndex = 0; subIndex < len; subIndex++) {
  16665. var subMesh = subMeshes[subIndex];
  16666. this._evaluateSubMesh(subMesh, mesh);
  16667. }
  16668. }
  16669. };
  16670. Scene.prototype.updateTransformMatrix = function (force) {
  16671. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  16672. };
  16673. Scene.prototype._renderForCamera = function (camera) {
  16674. var engine = this._engine;
  16675. var startTime = BABYLON.Tools.Now;
  16676. this.activeCamera = camera;
  16677. if (!this.activeCamera)
  16678. throw new Error("Active camera not set");
  16679. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  16680. // Viewport
  16681. engine.setViewport(this.activeCamera.viewport);
  16682. // Camera
  16683. this.resetCachedMaterial();
  16684. this._renderId++;
  16685. this.updateTransformMatrix();
  16686. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  16687. // Meshes
  16688. this._evaluateActiveMeshesDuration.beginMonitoring();
  16689. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  16690. this._evaluateActiveMeshes();
  16691. this._evaluateActiveMeshesDuration.endMonitoring(false);
  16692. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  16693. // Software skinning
  16694. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  16695. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  16696. mesh.applySkeleton(mesh.skeleton);
  16697. }
  16698. // Render targets
  16699. this._renderTargetsDuration.beginMonitoring();
  16700. var needsRestoreFrameBuffer = false;
  16701. var beforeRenderTargetDate = BABYLON.Tools.Now;
  16702. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  16703. this._intermediateRendering = true;
  16704. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  16705. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  16706. var renderTarget = this._renderTargets.data[renderIndex];
  16707. if (renderTarget._shouldRender()) {
  16708. this._renderId++;
  16709. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  16710. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  16711. }
  16712. }
  16713. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  16714. this._intermediateRendering = false;
  16715. this._renderId++;
  16716. needsRestoreFrameBuffer = true; // Restore back buffer
  16717. }
  16718. // Render HighlightLayer Texture
  16719. var stencilState = this._engine.getStencilBuffer();
  16720. var renderhighlights = false;
  16721. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  16722. this._intermediateRendering = true;
  16723. for (var i = 0; i < this.highlightLayers.length; i++) {
  16724. var highlightLayer = this.highlightLayers[i];
  16725. if (highlightLayer.shouldRender() &&
  16726. (!highlightLayer.camera ||
  16727. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  16728. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  16729. renderhighlights = true;
  16730. var renderTarget = highlightLayer._mainTexture;
  16731. if (renderTarget._shouldRender()) {
  16732. this._renderId++;
  16733. renderTarget.render(false, false);
  16734. needsRestoreFrameBuffer = true;
  16735. }
  16736. }
  16737. }
  16738. this._intermediateRendering = false;
  16739. this._renderId++;
  16740. }
  16741. if (needsRestoreFrameBuffer) {
  16742. if (this.offscreenRenderTarget) {
  16743. engine.bindFramebuffer(this.offscreenRenderTarget._texture);
  16744. }
  16745. else {
  16746. engine.restoreDefaultFramebuffer(); // Restore back buffer
  16747. }
  16748. }
  16749. this._renderTargetsDuration.endMonitoring(false);
  16750. // Prepare Frame
  16751. this.postProcessManager._prepareFrame();
  16752. this._renderDuration.beginMonitoring();
  16753. // Backgrounds
  16754. var layerIndex;
  16755. var layer;
  16756. if (this.layers.length) {
  16757. engine.setDepthBuffer(false);
  16758. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  16759. layer = this.layers[layerIndex];
  16760. if (layer.isBackground) {
  16761. layer.render();
  16762. }
  16763. }
  16764. engine.setDepthBuffer(true);
  16765. }
  16766. // Render
  16767. BABYLON.Tools.StartPerformanceCounter("Main render");
  16768. // Activate HighlightLayer stencil
  16769. if (renderhighlights) {
  16770. this._engine.setStencilBuffer(true);
  16771. }
  16772. this._renderingManager.render(null, null, true, true);
  16773. // Restore HighlightLayer stencil
  16774. if (renderhighlights) {
  16775. this._engine.setStencilBuffer(stencilState);
  16776. }
  16777. BABYLON.Tools.EndPerformanceCounter("Main render");
  16778. // Bounding boxes
  16779. if (this._boundingBoxRenderer) {
  16780. this._boundingBoxRenderer.render();
  16781. }
  16782. // Edges
  16783. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  16784. this._edgesRenderers.data[edgesRendererIndex].render();
  16785. }
  16786. // Lens flares
  16787. if (this.lensFlaresEnabled) {
  16788. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  16789. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  16790. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  16791. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  16792. lensFlareSystem.render();
  16793. }
  16794. }
  16795. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  16796. }
  16797. // Foregrounds
  16798. if (this.layers.length) {
  16799. engine.setDepthBuffer(false);
  16800. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  16801. layer = this.layers[layerIndex];
  16802. if (!layer.isBackground) {
  16803. layer.render();
  16804. }
  16805. }
  16806. engine.setDepthBuffer(true);
  16807. }
  16808. // Highlight Layer
  16809. if (renderhighlights) {
  16810. engine.setDepthBuffer(false);
  16811. for (var i = 0; i < this.highlightLayers.length; i++) {
  16812. if (this.highlightLayers[i].shouldRender()) {
  16813. this.highlightLayers[i].render();
  16814. }
  16815. }
  16816. engine.setDepthBuffer(true);
  16817. }
  16818. this._renderDuration.endMonitoring(false);
  16819. // Finalize frame
  16820. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  16821. // Update camera
  16822. this.activeCamera._updateFromScene();
  16823. // Reset some special arrays
  16824. this._renderTargets.reset();
  16825. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  16826. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  16827. };
  16828. Scene.prototype._processSubCameras = function (camera) {
  16829. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  16830. this._renderForCamera(camera);
  16831. return;
  16832. }
  16833. // rig cameras
  16834. for (var index = 0; index < camera._rigCameras.length; index++) {
  16835. this._renderForCamera(camera._rigCameras[index]);
  16836. }
  16837. this.activeCamera = camera;
  16838. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  16839. // Update camera
  16840. this.activeCamera._updateFromScene();
  16841. };
  16842. Scene.prototype._checkIntersections = function () {
  16843. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  16844. var sourceMesh = this._meshesForIntersections.data[index];
  16845. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  16846. var action = sourceMesh.actionManager.actions[actionIndex];
  16847. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  16848. var parameters = action.getTriggerParameter();
  16849. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  16850. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  16851. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  16852. if (areIntersecting && currentIntersectionInProgress === -1) {
  16853. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  16854. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  16855. sourceMesh._intersectionsInProgress.push(otherMesh);
  16856. }
  16857. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  16858. sourceMesh._intersectionsInProgress.push(otherMesh);
  16859. }
  16860. }
  16861. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  16862. //They intersected, and now they don't.
  16863. //is this trigger an exit trigger? execute an event.
  16864. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  16865. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  16866. }
  16867. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  16868. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  16869. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  16870. }
  16871. }
  16872. }
  16873. }
  16874. }
  16875. };
  16876. Scene.prototype.render = function () {
  16877. if (this.isDisposed) {
  16878. return;
  16879. }
  16880. this._lastFrameDuration.beginMonitoring();
  16881. this._particlesDuration.fetchNewFrame();
  16882. this._spritesDuration.fetchNewFrame();
  16883. this._activeParticles.fetchNewFrame();
  16884. this._renderDuration.fetchNewFrame();
  16885. this._renderTargetsDuration.fetchNewFrame();
  16886. this._evaluateActiveMeshesDuration.fetchNewFrame();
  16887. this._totalVertices.fetchNewFrame();
  16888. this._activeIndices.fetchNewFrame();
  16889. this._activeBones.fetchNewFrame();
  16890. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  16891. this._meshesForIntersections.reset();
  16892. this.resetCachedMaterial();
  16893. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  16894. // Actions
  16895. if (this.actionManager) {
  16896. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  16897. }
  16898. //Simplification Queue
  16899. if (this.simplificationQueue && !this.simplificationQueue.running) {
  16900. this.simplificationQueue.executeNext();
  16901. }
  16902. // Animations
  16903. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  16904. this._animationRatio = deltaTime * (60.0 / 1000.0);
  16905. this._animate();
  16906. // Physics
  16907. if (this._physicsEngine) {
  16908. BABYLON.Tools.StartPerformanceCounter("Physics");
  16909. this._physicsEngine._step(deltaTime / 1000.0);
  16910. BABYLON.Tools.EndPerformanceCounter("Physics");
  16911. }
  16912. // Before render
  16913. this.onBeforeRenderObservable.notifyObservers(this);
  16914. // Customs render targets
  16915. this._renderTargetsDuration.beginMonitoring();
  16916. var beforeRenderTargetDate = BABYLON.Tools.Now;
  16917. var engine = this.getEngine();
  16918. var currentActiveCamera = this.activeCamera;
  16919. if (this.renderTargetsEnabled) {
  16920. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  16921. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  16922. var renderTarget = this.customRenderTargets[customIndex];
  16923. if (renderTarget._shouldRender()) {
  16924. this._renderId++;
  16925. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  16926. if (!this.activeCamera)
  16927. throw new Error("Active camera not set");
  16928. // Viewport
  16929. engine.setViewport(this.activeCamera.viewport);
  16930. // Camera
  16931. this.updateTransformMatrix();
  16932. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  16933. }
  16934. }
  16935. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  16936. this._renderId++;
  16937. }
  16938. if (this.offscreenRenderTarget) {
  16939. engine.bindFramebuffer(this.offscreenRenderTarget._texture);
  16940. }
  16941. else {
  16942. // Restore back buffer
  16943. if (this.customRenderTargets.length > 0) {
  16944. engine.restoreDefaultFramebuffer();
  16945. }
  16946. }
  16947. this._renderTargetsDuration.endMonitoring();
  16948. this.activeCamera = currentActiveCamera;
  16949. // Procedural textures
  16950. if (this.proceduralTexturesEnabled) {
  16951. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  16952. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  16953. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  16954. if (proceduralTexture._shouldRender()) {
  16955. proceduralTexture.render();
  16956. }
  16957. }
  16958. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  16959. }
  16960. // Clear
  16961. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true, true);
  16962. // Shadows
  16963. if (this.shadowsEnabled) {
  16964. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  16965. var light = this.lights[lightIndex];
  16966. var shadowGenerator = light.getShadowGenerator();
  16967. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  16968. this._renderTargets.push(shadowGenerator.getShadowMap());
  16969. }
  16970. }
  16971. }
  16972. // Depth renderer
  16973. if (this._depthRenderer) {
  16974. this._renderTargets.push(this._depthRenderer.getDepthMap());
  16975. }
  16976. // RenderPipeline
  16977. if (this._postProcessRenderPipelineManager) {
  16978. this._postProcessRenderPipelineManager.update();
  16979. }
  16980. // Multi-cameras?
  16981. if (this.activeCameras.length > 0) {
  16982. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  16983. if (cameraIndex > 0) {
  16984. this._engine.clear(null, false, true, true);
  16985. }
  16986. this._processSubCameras(this.activeCameras[cameraIndex]);
  16987. }
  16988. }
  16989. else {
  16990. if (!this.activeCamera) {
  16991. throw new Error("No camera defined");
  16992. }
  16993. this._processSubCameras(this.activeCamera);
  16994. }
  16995. // Intersection checks
  16996. this._checkIntersections();
  16997. // Update the audio listener attached to the camera
  16998. if (BABYLON.AudioEngine) {
  16999. this._updateAudioParameters();
  17000. }
  17001. // After render
  17002. if (this.afterRender) {
  17003. this.afterRender();
  17004. }
  17005. this.onAfterRenderObservable.notifyObservers(this);
  17006. // Cleaning
  17007. for (var index = 0; index < this._toBeDisposed.length; index++) {
  17008. this._toBeDisposed.data[index].dispose();
  17009. this._toBeDisposed[index] = null;
  17010. }
  17011. this._toBeDisposed.reset();
  17012. if (this.dumpNextRenderTargets) {
  17013. this.dumpNextRenderTargets = false;
  17014. }
  17015. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  17016. this._lastFrameDuration.endMonitoring();
  17017. this._totalMeshesCounter.addCount(this.meshes.length, true);
  17018. this._totalLightsCounter.addCount(this.lights.length, true);
  17019. this._totalMaterialsCounter.addCount(this.materials.length, true);
  17020. this._totalTexturesCounter.addCount(this.textures.length, true);
  17021. this._activeBones.addCount(0, true);
  17022. this._activeIndices.addCount(0, true);
  17023. this._activeParticles.addCount(0, true);
  17024. };
  17025. Scene.prototype._updateAudioParameters = function () {
  17026. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  17027. return;
  17028. }
  17029. var listeningCamera;
  17030. var audioEngine = BABYLON.Engine.audioEngine;
  17031. if (this.activeCameras.length > 0) {
  17032. listeningCamera = this.activeCameras[0];
  17033. }
  17034. else {
  17035. listeningCamera = this.activeCamera;
  17036. }
  17037. if (listeningCamera && audioEngine.canUseWebAudio) {
  17038. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  17039. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  17040. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  17041. cameraDirection.normalize();
  17042. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  17043. var i;
  17044. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  17045. var sound = this.mainSoundTrack.soundCollection[i];
  17046. if (sound.useCustomAttenuation) {
  17047. sound.updateDistanceFromListener();
  17048. }
  17049. }
  17050. for (i = 0; i < this.soundTracks.length; i++) {
  17051. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  17052. sound = this.soundTracks[i].soundCollection[j];
  17053. if (sound.useCustomAttenuation) {
  17054. sound.updateDistanceFromListener();
  17055. }
  17056. }
  17057. }
  17058. }
  17059. };
  17060. Object.defineProperty(Scene.prototype, "audioEnabled", {
  17061. // Audio
  17062. get: function () {
  17063. return this._audioEnabled;
  17064. },
  17065. set: function (value) {
  17066. this._audioEnabled = value;
  17067. if (BABYLON.AudioEngine) {
  17068. if (this._audioEnabled) {
  17069. this._enableAudio();
  17070. }
  17071. else {
  17072. this._disableAudio();
  17073. }
  17074. }
  17075. },
  17076. enumerable: true,
  17077. configurable: true
  17078. });
  17079. Scene.prototype._disableAudio = function () {
  17080. var i;
  17081. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  17082. this.mainSoundTrack.soundCollection[i].pause();
  17083. }
  17084. for (i = 0; i < this.soundTracks.length; i++) {
  17085. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  17086. this.soundTracks[i].soundCollection[j].pause();
  17087. }
  17088. }
  17089. };
  17090. Scene.prototype._enableAudio = function () {
  17091. var i;
  17092. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  17093. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  17094. this.mainSoundTrack.soundCollection[i].play();
  17095. }
  17096. }
  17097. for (i = 0; i < this.soundTracks.length; i++) {
  17098. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  17099. if (this.soundTracks[i].soundCollection[j].isPaused) {
  17100. this.soundTracks[i].soundCollection[j].play();
  17101. }
  17102. }
  17103. }
  17104. };
  17105. Object.defineProperty(Scene.prototype, "headphone", {
  17106. get: function () {
  17107. return this._headphone;
  17108. },
  17109. set: function (value) {
  17110. this._headphone = value;
  17111. if (BABYLON.AudioEngine) {
  17112. if (this._headphone) {
  17113. this._switchAudioModeForHeadphones();
  17114. }
  17115. else {
  17116. this._switchAudioModeForNormalSpeakers();
  17117. }
  17118. }
  17119. },
  17120. enumerable: true,
  17121. configurable: true
  17122. });
  17123. Scene.prototype._switchAudioModeForHeadphones = function () {
  17124. this.mainSoundTrack.switchPanningModelToHRTF();
  17125. for (var i = 0; i < this.soundTracks.length; i++) {
  17126. this.soundTracks[i].switchPanningModelToHRTF();
  17127. }
  17128. };
  17129. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  17130. this.mainSoundTrack.switchPanningModelToEqualPower();
  17131. for (var i = 0; i < this.soundTracks.length; i++) {
  17132. this.soundTracks[i].switchPanningModelToEqualPower();
  17133. }
  17134. };
  17135. Scene.prototype.enableDepthRenderer = function () {
  17136. if (this._depthRenderer) {
  17137. return this._depthRenderer;
  17138. }
  17139. this._depthRenderer = new BABYLON.DepthRenderer(this);
  17140. return this._depthRenderer;
  17141. };
  17142. Scene.prototype.disableDepthRenderer = function () {
  17143. if (!this._depthRenderer) {
  17144. return;
  17145. }
  17146. this._depthRenderer.dispose();
  17147. this._depthRenderer = null;
  17148. };
  17149. Scene.prototype.freezeMaterials = function () {
  17150. for (var i = 0; i < this.materials.length; i++) {
  17151. this.materials[i].freeze();
  17152. }
  17153. };
  17154. Scene.prototype.unfreezeMaterials = function () {
  17155. for (var i = 0; i < this.materials.length; i++) {
  17156. this.materials[i].unfreeze();
  17157. }
  17158. };
  17159. Scene.prototype.dispose = function () {
  17160. this.beforeRender = null;
  17161. this.afterRender = null;
  17162. this.skeletons = [];
  17163. this.morphTargetManagers = [];
  17164. this.importedMeshesFiles = new Array();
  17165. if (this._depthRenderer) {
  17166. this._depthRenderer.dispose();
  17167. }
  17168. // Smart arrays
  17169. if (this.activeCamera) {
  17170. this.activeCamera._activeMeshes.dispose();
  17171. this.activeCamera = null;
  17172. }
  17173. this._activeMeshes.dispose();
  17174. this._renderingManager.dispose();
  17175. this._processedMaterials.dispose();
  17176. this._activeParticleSystems.dispose();
  17177. this._activeSkeletons.dispose();
  17178. this._softwareSkinnedMeshes.dispose();
  17179. if (this._boundingBoxRenderer) {
  17180. this._boundingBoxRenderer.dispose();
  17181. }
  17182. this._edgesRenderers.dispose();
  17183. this._meshesForIntersections.dispose();
  17184. this._toBeDisposed.dispose();
  17185. // Debug layer
  17186. if (this._debugLayer) {
  17187. this._debugLayer.hide();
  17188. }
  17189. // Events
  17190. this.onDisposeObservable.notifyObservers(this);
  17191. this.onDisposeObservable.clear();
  17192. this.onBeforeRenderObservable.clear();
  17193. this.onAfterRenderObservable.clear();
  17194. this.detachControl();
  17195. // Release sounds & sounds tracks
  17196. if (BABYLON.AudioEngine) {
  17197. this.disposeSounds();
  17198. }
  17199. // Detach cameras
  17200. var canvas = this._engine.getRenderingCanvas();
  17201. var index;
  17202. for (index = 0; index < this.cameras.length; index++) {
  17203. this.cameras[index].detachControl(canvas);
  17204. }
  17205. // Release lights
  17206. while (this.lights.length) {
  17207. this.lights[0].dispose();
  17208. }
  17209. // Release meshes
  17210. while (this.meshes.length) {
  17211. this.meshes[0].dispose(true);
  17212. }
  17213. // Release cameras
  17214. while (this.cameras.length) {
  17215. this.cameras[0].dispose();
  17216. }
  17217. // Release materials
  17218. while (this.materials.length) {
  17219. this.materials[0].dispose();
  17220. }
  17221. // Release particles
  17222. while (this.particleSystems.length) {
  17223. this.particleSystems[0].dispose();
  17224. }
  17225. // Release sprites
  17226. while (this.spriteManagers.length) {
  17227. this.spriteManagers[0].dispose();
  17228. }
  17229. // Release layers
  17230. while (this.layers.length) {
  17231. this.layers[0].dispose();
  17232. }
  17233. while (this.highlightLayers.length) {
  17234. this.highlightLayers[0].dispose();
  17235. }
  17236. // Release textures
  17237. while (this.textures.length) {
  17238. this.textures[0].dispose();
  17239. }
  17240. // Release UBO
  17241. this._sceneUbo.dispose();
  17242. // Post-processes
  17243. this.postProcessManager.dispose();
  17244. // Physics
  17245. if (this._physicsEngine) {
  17246. this.disablePhysicsEngine();
  17247. }
  17248. // Remove from engine
  17249. index = this._engine.scenes.indexOf(this);
  17250. if (index > -1) {
  17251. this._engine.scenes.splice(index, 1);
  17252. }
  17253. this._engine.wipeCaches();
  17254. this._engine = null;
  17255. };
  17256. Object.defineProperty(Scene.prototype, "isDisposed", {
  17257. get: function () {
  17258. return !this._engine;
  17259. },
  17260. enumerable: true,
  17261. configurable: true
  17262. });
  17263. // Release sounds & sounds tracks
  17264. Scene.prototype.disposeSounds = function () {
  17265. this.mainSoundTrack.dispose();
  17266. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  17267. this.soundTracks[scIndex].dispose();
  17268. }
  17269. };
  17270. // Octrees
  17271. Scene.prototype.getWorldExtends = function () {
  17272. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  17273. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  17274. for (var index = 0; index < this.meshes.length; index++) {
  17275. var mesh = this.meshes[index];
  17276. mesh.computeWorldMatrix(true);
  17277. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  17278. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  17279. BABYLON.Tools.CheckExtends(minBox, min, max);
  17280. BABYLON.Tools.CheckExtends(maxBox, min, max);
  17281. }
  17282. return {
  17283. min: min,
  17284. max: max
  17285. };
  17286. };
  17287. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  17288. if (maxCapacity === void 0) { maxCapacity = 64; }
  17289. if (maxDepth === void 0) { maxDepth = 2; }
  17290. if (!this._selectionOctree) {
  17291. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  17292. }
  17293. var worldExtends = this.getWorldExtends();
  17294. // Update octree
  17295. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  17296. return this._selectionOctree;
  17297. };
  17298. // Picking
  17299. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  17300. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  17301. var engine = this._engine;
  17302. if (!camera) {
  17303. if (!this.activeCamera)
  17304. throw new Error("Active camera not set");
  17305. camera = this.activeCamera;
  17306. }
  17307. var cameraViewport = camera.viewport;
  17308. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  17309. // Moving coordinates to local viewport world
  17310. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  17311. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  17312. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  17313. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  17314. };
  17315. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  17316. if (!BABYLON.PickingInfo) {
  17317. return null;
  17318. }
  17319. var engine = this._engine;
  17320. if (!camera) {
  17321. if (!this.activeCamera)
  17322. throw new Error("Active camera not set");
  17323. camera = this.activeCamera;
  17324. }
  17325. var cameraViewport = camera.viewport;
  17326. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  17327. var identity = BABYLON.Matrix.Identity();
  17328. // Moving coordinates to local viewport world
  17329. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  17330. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  17331. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  17332. };
  17333. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  17334. if (!BABYLON.PickingInfo) {
  17335. return null;
  17336. }
  17337. var pickingInfo = null;
  17338. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  17339. var mesh = this.meshes[meshIndex];
  17340. if (predicate) {
  17341. if (!predicate(mesh)) {
  17342. continue;
  17343. }
  17344. }
  17345. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  17346. continue;
  17347. }
  17348. var world = mesh.getWorldMatrix();
  17349. var ray = rayFunction(world);
  17350. var result = mesh.intersects(ray, fastCheck);
  17351. if (!result || !result.hit)
  17352. continue;
  17353. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  17354. continue;
  17355. pickingInfo = result;
  17356. if (fastCheck) {
  17357. break;
  17358. }
  17359. }
  17360. return pickingInfo || new BABYLON.PickingInfo();
  17361. };
  17362. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  17363. if (!BABYLON.PickingInfo) {
  17364. return null;
  17365. }
  17366. var pickingInfos = new Array();
  17367. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  17368. var mesh = this.meshes[meshIndex];
  17369. if (predicate) {
  17370. if (!predicate(mesh)) {
  17371. continue;
  17372. }
  17373. }
  17374. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  17375. continue;
  17376. }
  17377. var world = mesh.getWorldMatrix();
  17378. var ray = rayFunction(world);
  17379. var result = mesh.intersects(ray, false);
  17380. if (!result || !result.hit)
  17381. continue;
  17382. pickingInfos.push(result);
  17383. }
  17384. return pickingInfos;
  17385. };
  17386. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  17387. if (!BABYLON.PickingInfo) {
  17388. return null;
  17389. }
  17390. var pickingInfo = null;
  17391. camera = camera || this.activeCamera;
  17392. if (this.spriteManagers.length > 0) {
  17393. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  17394. var spriteManager = this.spriteManagers[spriteIndex];
  17395. if (!spriteManager.isPickable) {
  17396. continue;
  17397. }
  17398. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  17399. if (!result || !result.hit)
  17400. continue;
  17401. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  17402. continue;
  17403. pickingInfo = result;
  17404. if (fastCheck) {
  17405. break;
  17406. }
  17407. }
  17408. }
  17409. return pickingInfo || new BABYLON.PickingInfo();
  17410. };
  17411. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  17412. /// <param name="x">X position on screen</param>
  17413. /// <param name="y">Y position on screen</param>
  17414. /// <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>
  17415. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  17416. /// <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>
  17417. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  17418. var _this = this;
  17419. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  17420. };
  17421. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  17422. /// <param name="x">X position on screen</param>
  17423. /// <param name="y">Y position on screen</param>
  17424. /// <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>
  17425. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  17426. /// <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>
  17427. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  17428. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  17429. };
  17430. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  17431. var _this = this;
  17432. return this._internalPick(function (world) {
  17433. if (!_this._pickWithRayInverseMatrix) {
  17434. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  17435. }
  17436. world.invertToRef(_this._pickWithRayInverseMatrix);
  17437. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  17438. }, predicate, fastCheck);
  17439. };
  17440. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  17441. /// <param name="x">X position on screen</param>
  17442. /// <param name="y">Y position on screen</param>
  17443. /// <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>
  17444. /// <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>
  17445. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  17446. var _this = this;
  17447. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate);
  17448. };
  17449. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  17450. /// <param name="ray">Ray to use</param>
  17451. /// <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>
  17452. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  17453. var _this = this;
  17454. return this._internalMultiPick(function (world) {
  17455. if (!_this._pickWithRayInverseMatrix) {
  17456. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  17457. }
  17458. world.invertToRef(_this._pickWithRayInverseMatrix);
  17459. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  17460. }, predicate);
  17461. };
  17462. Scene.prototype.setPointerOverMesh = function (mesh) {
  17463. if (this._pointerOverMesh === mesh) {
  17464. return;
  17465. }
  17466. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  17467. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  17468. }
  17469. this._pointerOverMesh = mesh;
  17470. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  17471. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  17472. }
  17473. };
  17474. Scene.prototype.getPointerOverMesh = function () {
  17475. return this._pointerOverMesh;
  17476. };
  17477. Scene.prototype.setPointerOverSprite = function (sprite) {
  17478. if (this._pointerOverSprite === sprite) {
  17479. return;
  17480. }
  17481. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  17482. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  17483. }
  17484. this._pointerOverSprite = sprite;
  17485. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  17486. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  17487. }
  17488. };
  17489. Scene.prototype.getPointerOverSprite = function () {
  17490. return this._pointerOverSprite;
  17491. };
  17492. // Physics
  17493. Scene.prototype.getPhysicsEngine = function () {
  17494. return this._physicsEngine;
  17495. };
  17496. /**
  17497. * Enables physics to the current scene
  17498. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  17499. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  17500. * @return {boolean} was the physics engine initialized
  17501. */
  17502. Scene.prototype.enablePhysics = function (gravity, plugin) {
  17503. if (this._physicsEngine) {
  17504. return true;
  17505. }
  17506. try {
  17507. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  17508. return true;
  17509. }
  17510. catch (e) {
  17511. BABYLON.Tools.Error(e.message);
  17512. return false;
  17513. }
  17514. };
  17515. Scene.prototype.disablePhysicsEngine = function () {
  17516. if (!this._physicsEngine) {
  17517. return;
  17518. }
  17519. this._physicsEngine.dispose();
  17520. this._physicsEngine = undefined;
  17521. };
  17522. Scene.prototype.isPhysicsEnabled = function () {
  17523. return this._physicsEngine !== undefined;
  17524. };
  17525. Scene.prototype.deleteCompoundImpostor = function (compound) {
  17526. var mesh = compound.parts[0].mesh;
  17527. mesh.physicsImpostor.dispose();
  17528. mesh.physicsImpostor = null;
  17529. };
  17530. // Misc.
  17531. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera) {
  17532. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  17533. // Light
  17534. if (this.lights.length === 0) {
  17535. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  17536. }
  17537. // Camera
  17538. if (!this.activeCamera) {
  17539. var worldExtends = this.getWorldExtends();
  17540. var worldSize = worldExtends.max.subtract(worldExtends.min);
  17541. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  17542. var camera;
  17543. var radius = worldSize.length() * 1.5;
  17544. if (createArcRotateCamera) {
  17545. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", 4.712, 1.571, radius, worldCenter, this);
  17546. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  17547. arcRotateCamera.wheelPrecision = 100 / radius;
  17548. camera = arcRotateCamera;
  17549. }
  17550. else {
  17551. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, this.useRightHandedSystem ? -radius : radius), this);
  17552. freeCamera.setTarget(worldCenter);
  17553. camera = freeCamera;
  17554. }
  17555. camera.minZ = radius * 0.01;
  17556. camera.maxZ = radius * 100;
  17557. camera.speed = radius * 0.2;
  17558. this.activeCamera = camera;
  17559. }
  17560. };
  17561. // Tags
  17562. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  17563. if (tagsQuery === undefined) {
  17564. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  17565. return list;
  17566. }
  17567. var listByTags = [];
  17568. forEach = forEach || (function (item) { return; });
  17569. for (var i in list) {
  17570. var item = list[i];
  17571. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  17572. listByTags.push(item);
  17573. forEach(item);
  17574. }
  17575. }
  17576. return listByTags;
  17577. };
  17578. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  17579. return this._getByTags(this.meshes, tagsQuery, forEach);
  17580. };
  17581. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  17582. return this._getByTags(this.cameras, tagsQuery, forEach);
  17583. };
  17584. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  17585. return this._getByTags(this.lights, tagsQuery, forEach);
  17586. };
  17587. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  17588. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  17589. };
  17590. /**
  17591. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  17592. * This allowed control for front to back rendering or reversly depending of the special needs.
  17593. *
  17594. * @param renderingGroupId The rendering group id corresponding to its index
  17595. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  17596. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  17597. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  17598. */
  17599. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  17600. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  17601. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  17602. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  17603. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  17604. };
  17605. /**
  17606. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  17607. *
  17608. * @param renderingGroupId The rendering group id corresponding to its index
  17609. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  17610. * @param depth Automatically clears depth between groups if true and autoClear is true.
  17611. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  17612. */
  17613. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  17614. if (depth === void 0) { depth = true; }
  17615. if (stencil === void 0) { stencil = true; }
  17616. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  17617. };
  17618. /**
  17619. * Will flag all materials as dirty to trigger new shader compilation
  17620. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  17621. */
  17622. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  17623. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  17624. var material = _a[_i];
  17625. if (predicate && !predicate(material)) {
  17626. continue;
  17627. }
  17628. material.markAsDirty(flag);
  17629. }
  17630. };
  17631. return Scene;
  17632. }());
  17633. // Statics
  17634. Scene._FOGMODE_NONE = 0;
  17635. Scene._FOGMODE_EXP = 1;
  17636. Scene._FOGMODE_EXP2 = 2;
  17637. Scene._FOGMODE_LINEAR = 3;
  17638. Scene.MinDeltaTime = 1.0;
  17639. Scene.MaxDeltaTime = 1000.0;
  17640. Scene.DragMovementThreshold = 10; // in pixels
  17641. Scene.LongPressDelay = 500; // in milliseconds
  17642. Scene.DoubleClickDelay = 300; // in milliseconds
  17643. Scene.ExclusiveDoubleClickMode = false; // If you need to check double click without raising a single click at first click, enable this flag
  17644. BABYLON.Scene = Scene;
  17645. })(BABYLON || (BABYLON = {}));
  17646. //# sourceMappingURL=babylon.scene.js.map
  17647. var BABYLON;
  17648. (function (BABYLON) {
  17649. var Buffer = (function () {
  17650. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  17651. if (engine instanceof BABYLON.Mesh) {
  17652. this._engine = engine.getScene().getEngine();
  17653. }
  17654. else {
  17655. this._engine = engine;
  17656. }
  17657. this._updatable = updatable;
  17658. this._data = data;
  17659. this._strideSize = stride;
  17660. if (!postponeInternalCreation) {
  17661. this.create();
  17662. }
  17663. this._instanced = instanced;
  17664. }
  17665. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  17666. // a lot of these parameters are ignored as they are overriden by the buffer
  17667. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  17668. };
  17669. // Properties
  17670. Buffer.prototype.isUpdatable = function () {
  17671. return this._updatable;
  17672. };
  17673. Buffer.prototype.getData = function () {
  17674. return this._data;
  17675. };
  17676. Buffer.prototype.getBuffer = function () {
  17677. return this._buffer;
  17678. };
  17679. Buffer.prototype.getStrideSize = function () {
  17680. return this._strideSize;
  17681. };
  17682. Buffer.prototype.getIsInstanced = function () {
  17683. return this._instanced;
  17684. };
  17685. // Methods
  17686. Buffer.prototype.create = function (data) {
  17687. if (!data && this._buffer) {
  17688. return; // nothing to do
  17689. }
  17690. data = data || this._data;
  17691. if (!this._buffer) {
  17692. if (this._updatable) {
  17693. this._buffer = this._engine.createDynamicVertexBuffer(data);
  17694. this._data = data;
  17695. }
  17696. else {
  17697. this._buffer = this._engine.createVertexBuffer(data);
  17698. }
  17699. }
  17700. else if (this._updatable) {
  17701. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  17702. this._data = data;
  17703. }
  17704. };
  17705. Buffer.prototype.update = function (data) {
  17706. this.create(data);
  17707. };
  17708. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  17709. if (!this._buffer) {
  17710. return;
  17711. }
  17712. if (this._updatable) {
  17713. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  17714. this._data = null;
  17715. }
  17716. };
  17717. Buffer.prototype.dispose = function () {
  17718. if (!this._buffer) {
  17719. return;
  17720. }
  17721. if (this._engine._releaseBuffer(this._buffer)) {
  17722. this._buffer = null;
  17723. }
  17724. };
  17725. return Buffer;
  17726. }());
  17727. BABYLON.Buffer = Buffer;
  17728. })(BABYLON || (BABYLON = {}));
  17729. //# sourceMappingURL=babylon.buffer.js.map
  17730. var BABYLON;
  17731. (function (BABYLON) {
  17732. var VertexBuffer = (function () {
  17733. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  17734. if (!stride) {
  17735. // Deduce stride from kind
  17736. switch (kind) {
  17737. case VertexBuffer.PositionKind:
  17738. stride = 3;
  17739. break;
  17740. case VertexBuffer.NormalKind:
  17741. stride = 3;
  17742. break;
  17743. case VertexBuffer.UVKind:
  17744. case VertexBuffer.UV2Kind:
  17745. case VertexBuffer.UV3Kind:
  17746. case VertexBuffer.UV4Kind:
  17747. case VertexBuffer.UV5Kind:
  17748. case VertexBuffer.UV6Kind:
  17749. stride = 2;
  17750. break;
  17751. case VertexBuffer.TangentKind:
  17752. case VertexBuffer.ColorKind:
  17753. stride = 4;
  17754. break;
  17755. case VertexBuffer.MatricesIndicesKind:
  17756. case VertexBuffer.MatricesIndicesExtraKind:
  17757. stride = 4;
  17758. break;
  17759. case VertexBuffer.MatricesWeightsKind:
  17760. case VertexBuffer.MatricesWeightsExtraKind:
  17761. stride = 4;
  17762. break;
  17763. }
  17764. }
  17765. if (data instanceof BABYLON.Buffer) {
  17766. if (!stride) {
  17767. stride = data.getStrideSize();
  17768. }
  17769. this._buffer = data;
  17770. this._ownsBuffer = false;
  17771. }
  17772. else {
  17773. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  17774. this._ownsBuffer = true;
  17775. }
  17776. this._stride = stride;
  17777. this._offset = offset ? offset : 0;
  17778. this._size = size ? size : stride;
  17779. this._kind = kind;
  17780. }
  17781. /**
  17782. * Returns the kind of the VertexBuffer (string).
  17783. */
  17784. VertexBuffer.prototype.getKind = function () {
  17785. return this._kind;
  17786. };
  17787. // Properties
  17788. /**
  17789. * Boolean : is the VertexBuffer updatable ?
  17790. */
  17791. VertexBuffer.prototype.isUpdatable = function () {
  17792. return this._buffer.isUpdatable();
  17793. };
  17794. /**
  17795. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  17796. */
  17797. VertexBuffer.prototype.getData = function () {
  17798. return this._buffer.getData();
  17799. };
  17800. /**
  17801. * Returns the WebGLBuffer associated to the VertexBuffer.
  17802. */
  17803. VertexBuffer.prototype.getBuffer = function () {
  17804. return this._buffer.getBuffer();
  17805. };
  17806. /**
  17807. * Returns the stride of the VertexBuffer (integer).
  17808. */
  17809. VertexBuffer.prototype.getStrideSize = function () {
  17810. return this._stride;
  17811. };
  17812. /**
  17813. * Returns the offset (integer).
  17814. */
  17815. VertexBuffer.prototype.getOffset = function () {
  17816. return this._offset;
  17817. };
  17818. /**
  17819. * Returns the VertexBuffer total size (integer).
  17820. */
  17821. VertexBuffer.prototype.getSize = function () {
  17822. return this._size;
  17823. };
  17824. /**
  17825. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  17826. */
  17827. VertexBuffer.prototype.getIsInstanced = function () {
  17828. return this._buffer.getIsInstanced();
  17829. };
  17830. // Methods
  17831. /**
  17832. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  17833. * Returns the created WebGLBuffer.
  17834. */
  17835. VertexBuffer.prototype.create = function (data) {
  17836. return this._buffer.create(data);
  17837. };
  17838. /**
  17839. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  17840. * Returns the updated WebGLBuffer.
  17841. */
  17842. VertexBuffer.prototype.update = function (data) {
  17843. return this._buffer.update(data);
  17844. };
  17845. /**
  17846. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  17847. * Returns the directly updated WebGLBuffer.
  17848. */
  17849. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  17850. return this._buffer.updateDirectly(data, offset);
  17851. };
  17852. /**
  17853. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  17854. */
  17855. VertexBuffer.prototype.dispose = function () {
  17856. if (this._ownsBuffer) {
  17857. this._buffer.dispose();
  17858. }
  17859. };
  17860. Object.defineProperty(VertexBuffer, "PositionKind", {
  17861. get: function () {
  17862. return VertexBuffer._PositionKind;
  17863. },
  17864. enumerable: true,
  17865. configurable: true
  17866. });
  17867. Object.defineProperty(VertexBuffer, "NormalKind", {
  17868. get: function () {
  17869. return VertexBuffer._NormalKind;
  17870. },
  17871. enumerable: true,
  17872. configurable: true
  17873. });
  17874. Object.defineProperty(VertexBuffer, "TangentKind", {
  17875. get: function () {
  17876. return VertexBuffer._TangentKind;
  17877. },
  17878. enumerable: true,
  17879. configurable: true
  17880. });
  17881. Object.defineProperty(VertexBuffer, "UVKind", {
  17882. get: function () {
  17883. return VertexBuffer._UVKind;
  17884. },
  17885. enumerable: true,
  17886. configurable: true
  17887. });
  17888. Object.defineProperty(VertexBuffer, "UV2Kind", {
  17889. get: function () {
  17890. return VertexBuffer._UV2Kind;
  17891. },
  17892. enumerable: true,
  17893. configurable: true
  17894. });
  17895. Object.defineProperty(VertexBuffer, "UV3Kind", {
  17896. get: function () {
  17897. return VertexBuffer._UV3Kind;
  17898. },
  17899. enumerable: true,
  17900. configurable: true
  17901. });
  17902. Object.defineProperty(VertexBuffer, "UV4Kind", {
  17903. get: function () {
  17904. return VertexBuffer._UV4Kind;
  17905. },
  17906. enumerable: true,
  17907. configurable: true
  17908. });
  17909. Object.defineProperty(VertexBuffer, "UV5Kind", {
  17910. get: function () {
  17911. return VertexBuffer._UV5Kind;
  17912. },
  17913. enumerable: true,
  17914. configurable: true
  17915. });
  17916. Object.defineProperty(VertexBuffer, "UV6Kind", {
  17917. get: function () {
  17918. return VertexBuffer._UV6Kind;
  17919. },
  17920. enumerable: true,
  17921. configurable: true
  17922. });
  17923. Object.defineProperty(VertexBuffer, "ColorKind", {
  17924. get: function () {
  17925. return VertexBuffer._ColorKind;
  17926. },
  17927. enumerable: true,
  17928. configurable: true
  17929. });
  17930. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  17931. get: function () {
  17932. return VertexBuffer._MatricesIndicesKind;
  17933. },
  17934. enumerable: true,
  17935. configurable: true
  17936. });
  17937. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  17938. get: function () {
  17939. return VertexBuffer._MatricesWeightsKind;
  17940. },
  17941. enumerable: true,
  17942. configurable: true
  17943. });
  17944. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  17945. get: function () {
  17946. return VertexBuffer._MatricesIndicesExtraKind;
  17947. },
  17948. enumerable: true,
  17949. configurable: true
  17950. });
  17951. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  17952. get: function () {
  17953. return VertexBuffer._MatricesWeightsExtraKind;
  17954. },
  17955. enumerable: true,
  17956. configurable: true
  17957. });
  17958. return VertexBuffer;
  17959. }());
  17960. // Enums
  17961. VertexBuffer._PositionKind = "position";
  17962. VertexBuffer._NormalKind = "normal";
  17963. VertexBuffer._TangentKind = "tangent";
  17964. VertexBuffer._UVKind = "uv";
  17965. VertexBuffer._UV2Kind = "uv2";
  17966. VertexBuffer._UV3Kind = "uv3";
  17967. VertexBuffer._UV4Kind = "uv4";
  17968. VertexBuffer._UV5Kind = "uv5";
  17969. VertexBuffer._UV6Kind = "uv6";
  17970. VertexBuffer._ColorKind = "color";
  17971. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  17972. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  17973. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  17974. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  17975. BABYLON.VertexBuffer = VertexBuffer;
  17976. })(BABYLON || (BABYLON = {}));
  17977. //# sourceMappingURL=babylon.vertexBuffer.js.map
  17978. var BABYLON;
  17979. (function (BABYLON) {
  17980. var BaseTexture = (function () {
  17981. function BaseTexture(scene) {
  17982. this._hasAlpha = false;
  17983. this.getAlphaFromRGB = false;
  17984. this.level = 1;
  17985. this.coordinatesIndex = 0;
  17986. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  17987. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  17988. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  17989. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  17990. this.isCube = false;
  17991. this.isRenderTarget = false;
  17992. this.animations = new Array();
  17993. /**
  17994. * An event triggered when the texture is disposed.
  17995. * @type {BABYLON.Observable}
  17996. */
  17997. this.onDisposeObservable = new BABYLON.Observable();
  17998. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  17999. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  18000. this._scene.textures.push(this);
  18001. this._uid = null;
  18002. }
  18003. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  18004. get: function () {
  18005. return this._hasAlpha;
  18006. },
  18007. set: function (value) {
  18008. if (this._hasAlpha === value) {
  18009. return;
  18010. }
  18011. this._hasAlpha = value;
  18012. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  18013. },
  18014. enumerable: true,
  18015. configurable: true
  18016. });
  18017. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  18018. get: function () {
  18019. return this._coordinatesMode;
  18020. },
  18021. set: function (value) {
  18022. if (this._coordinatesMode === value) {
  18023. return;
  18024. }
  18025. this._coordinatesMode = value;
  18026. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  18027. },
  18028. enumerable: true,
  18029. configurable: true
  18030. });
  18031. Object.defineProperty(BaseTexture.prototype, "uid", {
  18032. get: function () {
  18033. if (!this._uid) {
  18034. this._uid = BABYLON.Tools.RandomId();
  18035. }
  18036. return this._uid;
  18037. },
  18038. enumerable: true,
  18039. configurable: true
  18040. });
  18041. BaseTexture.prototype.toString = function () {
  18042. return this.name;
  18043. };
  18044. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  18045. set: function (callback) {
  18046. if (this._onDisposeObserver) {
  18047. this.onDisposeObservable.remove(this._onDisposeObserver);
  18048. }
  18049. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  18050. },
  18051. enumerable: true,
  18052. configurable: true
  18053. });
  18054. BaseTexture.prototype.getScene = function () {
  18055. return this._scene;
  18056. };
  18057. BaseTexture.prototype.getTextureMatrix = function () {
  18058. return null;
  18059. };
  18060. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  18061. return null;
  18062. };
  18063. BaseTexture.prototype.getInternalTexture = function () {
  18064. return this._texture;
  18065. };
  18066. BaseTexture.prototype.isReady = function () {
  18067. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  18068. this.delayLoad();
  18069. return false;
  18070. }
  18071. if (this._texture) {
  18072. return this._texture.isReady;
  18073. }
  18074. return false;
  18075. };
  18076. BaseTexture.prototype.getSize = function () {
  18077. if (this._texture._width) {
  18078. return new BABYLON.Size(this._texture._width, this._texture._height);
  18079. }
  18080. if (this._texture._size) {
  18081. return new BABYLON.Size(this._texture._size, this._texture._size);
  18082. }
  18083. return BABYLON.Size.Zero();
  18084. };
  18085. BaseTexture.prototype.getBaseSize = function () {
  18086. if (!this.isReady() || !this._texture)
  18087. return BABYLON.Size.Zero();
  18088. if (this._texture._size) {
  18089. return new BABYLON.Size(this._texture._size, this._texture._size);
  18090. }
  18091. return new BABYLON.Size(this._texture._baseWidth, this._texture._baseHeight);
  18092. };
  18093. BaseTexture.prototype.scale = function (ratio) {
  18094. };
  18095. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  18096. get: function () {
  18097. return false;
  18098. },
  18099. enumerable: true,
  18100. configurable: true
  18101. });
  18102. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  18103. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  18104. for (var index = 0; index < texturesCache.length; index++) {
  18105. var texturesCacheEntry = texturesCache[index];
  18106. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  18107. texturesCache.splice(index, 1);
  18108. return;
  18109. }
  18110. }
  18111. };
  18112. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  18113. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  18114. for (var index = 0; index < texturesCache.length; index++) {
  18115. var texturesCacheEntry = texturesCache[index];
  18116. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  18117. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  18118. texturesCacheEntry.references++;
  18119. return texturesCacheEntry;
  18120. }
  18121. }
  18122. }
  18123. return null;
  18124. };
  18125. BaseTexture.prototype.delayLoad = function () {
  18126. };
  18127. BaseTexture.prototype.clone = function () {
  18128. return null;
  18129. };
  18130. BaseTexture.prototype.releaseInternalTexture = function () {
  18131. if (this._texture) {
  18132. this._scene.getEngine().releaseInternalTexture(this._texture);
  18133. delete this._texture;
  18134. }
  18135. };
  18136. BaseTexture.prototype.dispose = function () {
  18137. // Animations
  18138. this.getScene().stopAnimation(this);
  18139. // Remove from scene
  18140. this._scene._removePendingData(this);
  18141. var index = this._scene.textures.indexOf(this);
  18142. if (index >= 0) {
  18143. this._scene.textures.splice(index, 1);
  18144. }
  18145. if (this._texture === undefined) {
  18146. return;
  18147. }
  18148. // Release
  18149. this.releaseInternalTexture();
  18150. // Callback
  18151. this.onDisposeObservable.notifyObservers(this);
  18152. this.onDisposeObservable.clear();
  18153. };
  18154. BaseTexture.prototype.serialize = function () {
  18155. if (!this.name) {
  18156. return null;
  18157. }
  18158. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  18159. // Animations
  18160. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  18161. return serializationObject;
  18162. };
  18163. return BaseTexture;
  18164. }());
  18165. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  18166. __decorate([
  18167. BABYLON.serialize()
  18168. ], BaseTexture.prototype, "name", void 0);
  18169. __decorate([
  18170. BABYLON.serialize("hasAlpha")
  18171. ], BaseTexture.prototype, "_hasAlpha", void 0);
  18172. __decorate([
  18173. BABYLON.serialize()
  18174. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  18175. __decorate([
  18176. BABYLON.serialize()
  18177. ], BaseTexture.prototype, "level", void 0);
  18178. __decorate([
  18179. BABYLON.serialize()
  18180. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  18181. __decorate([
  18182. BABYLON.serialize("coordinatesMode")
  18183. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  18184. __decorate([
  18185. BABYLON.serialize()
  18186. ], BaseTexture.prototype, "wrapU", void 0);
  18187. __decorate([
  18188. BABYLON.serialize()
  18189. ], BaseTexture.prototype, "wrapV", void 0);
  18190. __decorate([
  18191. BABYLON.serialize()
  18192. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  18193. __decorate([
  18194. BABYLON.serialize()
  18195. ], BaseTexture.prototype, "isCube", void 0);
  18196. __decorate([
  18197. BABYLON.serialize()
  18198. ], BaseTexture.prototype, "isRenderTarget", void 0);
  18199. BABYLON.BaseTexture = BaseTexture;
  18200. })(BABYLON || (BABYLON = {}));
  18201. //# sourceMappingURL=babylon.baseTexture.js.map
  18202. var BABYLON;
  18203. (function (BABYLON) {
  18204. var Texture = (function (_super) {
  18205. __extends(Texture, _super);
  18206. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  18207. if (noMipmap === void 0) { noMipmap = false; }
  18208. if (invertY === void 0) { invertY = true; }
  18209. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  18210. if (onLoad === void 0) { onLoad = null; }
  18211. if (onError === void 0) { onError = null; }
  18212. if (buffer === void 0) { buffer = null; }
  18213. if (deleteBuffer === void 0) { deleteBuffer = false; }
  18214. var _this = _super.call(this, scene) || this;
  18215. _this.uOffset = 0;
  18216. _this.vOffset = 0;
  18217. _this.uScale = 1.0;
  18218. _this.vScale = 1.0;
  18219. _this.uAng = 0;
  18220. _this.vAng = 0;
  18221. _this.wAng = 0;
  18222. _this.name = url;
  18223. _this.url = url;
  18224. _this._noMipmap = noMipmap;
  18225. _this._invertY = invertY;
  18226. _this._samplingMode = samplingMode;
  18227. _this._buffer = buffer;
  18228. _this._deleteBuffer = deleteBuffer;
  18229. _this._format = format;
  18230. scene = _this.getScene();
  18231. if (!url) {
  18232. return _this;
  18233. }
  18234. _this._texture = _this._getFromCache(url, noMipmap, samplingMode);
  18235. var load = function () {
  18236. if (_this._onLoadObservarble && _this._onLoadObservarble.hasObservers()) {
  18237. _this.onLoadObservable.notifyObservers(true);
  18238. }
  18239. if (onLoad) {
  18240. onLoad();
  18241. }
  18242. };
  18243. if (!_this._texture) {
  18244. if (!scene.useDelayedTextureLoading) {
  18245. _this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, null, _this._format);
  18246. if (deleteBuffer) {
  18247. delete _this._buffer;
  18248. }
  18249. }
  18250. else {
  18251. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  18252. _this._delayedOnLoad = load;
  18253. _this._delayedOnError = onError;
  18254. }
  18255. }
  18256. else {
  18257. if (_this._texture.isReady) {
  18258. BABYLON.Tools.SetImmediate(function () { return load(); });
  18259. }
  18260. else {
  18261. _this._texture.onLoadedCallbacks.push(load);
  18262. }
  18263. }
  18264. return _this;
  18265. }
  18266. Object.defineProperty(Texture.prototype, "noMipmap", {
  18267. get: function () {
  18268. return this._noMipmap;
  18269. },
  18270. enumerable: true,
  18271. configurable: true
  18272. });
  18273. Texture.prototype.delayLoad = function () {
  18274. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  18275. return;
  18276. }
  18277. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  18278. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  18279. if (!this._texture) {
  18280. 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);
  18281. if (this._deleteBuffer) {
  18282. delete this._buffer;
  18283. }
  18284. }
  18285. };
  18286. Texture.prototype.updateSamplingMode = function (samplingMode) {
  18287. if (!this._texture) {
  18288. return;
  18289. }
  18290. this._samplingMode = samplingMode;
  18291. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  18292. };
  18293. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  18294. x *= this.uScale;
  18295. y *= this.vScale;
  18296. x -= 0.5 * this.uScale;
  18297. y -= 0.5 * this.vScale;
  18298. z -= 0.5;
  18299. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  18300. t.x += 0.5 * this.uScale + this.uOffset;
  18301. t.y += 0.5 * this.vScale + this.vOffset;
  18302. t.z += 0.5;
  18303. };
  18304. Texture.prototype.getTextureMatrix = function () {
  18305. if (this.uOffset === this._cachedUOffset &&
  18306. this.vOffset === this._cachedVOffset &&
  18307. this.uScale === this._cachedUScale &&
  18308. this.vScale === this._cachedVScale &&
  18309. this.uAng === this._cachedUAng &&
  18310. this.vAng === this._cachedVAng &&
  18311. this.wAng === this._cachedWAng) {
  18312. return this._cachedTextureMatrix;
  18313. }
  18314. this._cachedUOffset = this.uOffset;
  18315. this._cachedVOffset = this.vOffset;
  18316. this._cachedUScale = this.uScale;
  18317. this._cachedVScale = this.vScale;
  18318. this._cachedUAng = this.uAng;
  18319. this._cachedVAng = this.vAng;
  18320. this._cachedWAng = this.wAng;
  18321. if (!this._cachedTextureMatrix) {
  18322. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  18323. this._rowGenerationMatrix = new BABYLON.Matrix();
  18324. this._t0 = BABYLON.Vector3.Zero();
  18325. this._t1 = BABYLON.Vector3.Zero();
  18326. this._t2 = BABYLON.Vector3.Zero();
  18327. }
  18328. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  18329. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  18330. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  18331. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  18332. this._t1.subtractInPlace(this._t0);
  18333. this._t2.subtractInPlace(this._t0);
  18334. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  18335. this._cachedTextureMatrix.m[0] = this._t1.x;
  18336. this._cachedTextureMatrix.m[1] = this._t1.y;
  18337. this._cachedTextureMatrix.m[2] = this._t1.z;
  18338. this._cachedTextureMatrix.m[4] = this._t2.x;
  18339. this._cachedTextureMatrix.m[5] = this._t2.y;
  18340. this._cachedTextureMatrix.m[6] = this._t2.z;
  18341. this._cachedTextureMatrix.m[8] = this._t0.x;
  18342. this._cachedTextureMatrix.m[9] = this._t0.y;
  18343. this._cachedTextureMatrix.m[10] = this._t0.z;
  18344. return this._cachedTextureMatrix;
  18345. };
  18346. Texture.prototype.getReflectionTextureMatrix = function () {
  18347. if (this.uOffset === this._cachedUOffset &&
  18348. this.vOffset === this._cachedVOffset &&
  18349. this.uScale === this._cachedUScale &&
  18350. this.vScale === this._cachedVScale &&
  18351. this.coordinatesMode === this._cachedCoordinatesMode) {
  18352. return this._cachedTextureMatrix;
  18353. }
  18354. if (!this._cachedTextureMatrix) {
  18355. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  18356. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  18357. }
  18358. this._cachedCoordinatesMode = this.coordinatesMode;
  18359. switch (this.coordinatesMode) {
  18360. case Texture.PLANAR_MODE:
  18361. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  18362. this._cachedTextureMatrix[0] = this.uScale;
  18363. this._cachedTextureMatrix[5] = this.vScale;
  18364. this._cachedTextureMatrix[12] = this.uOffset;
  18365. this._cachedTextureMatrix[13] = this.vOffset;
  18366. break;
  18367. case Texture.PROJECTION_MODE:
  18368. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  18369. this._projectionModeMatrix.m[0] = 0.5;
  18370. this._projectionModeMatrix.m[5] = -0.5;
  18371. this._projectionModeMatrix.m[10] = 0.0;
  18372. this._projectionModeMatrix.m[12] = 0.5;
  18373. this._projectionModeMatrix.m[13] = 0.5;
  18374. this._projectionModeMatrix.m[14] = 1.0;
  18375. this._projectionModeMatrix.m[15] = 1.0;
  18376. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  18377. break;
  18378. default:
  18379. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  18380. break;
  18381. }
  18382. return this._cachedTextureMatrix;
  18383. };
  18384. Texture.prototype.clone = function () {
  18385. var _this = this;
  18386. return BABYLON.SerializationHelper.Clone(function () {
  18387. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  18388. }, this);
  18389. };
  18390. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  18391. get: function () {
  18392. if (!this._onLoadObservarble) {
  18393. this._onLoadObservarble = new BABYLON.Observable();
  18394. }
  18395. return this._onLoadObservarble;
  18396. },
  18397. enumerable: true,
  18398. configurable: true
  18399. });
  18400. // Statics
  18401. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  18402. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  18403. if (onLoad === void 0) { onLoad = null; }
  18404. if (onError === void 0) { onError = null; }
  18405. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  18406. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  18407. };
  18408. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  18409. if (parsedTexture.customType) {
  18410. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  18411. // Update Sampling Mode
  18412. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  18413. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  18414. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  18415. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  18416. }
  18417. }
  18418. return parsedCustomTexture;
  18419. }
  18420. if (parsedTexture.isCube) {
  18421. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  18422. }
  18423. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  18424. return null;
  18425. }
  18426. var texture = BABYLON.SerializationHelper.Parse(function () {
  18427. if (parsedTexture.mirrorPlane) {
  18428. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  18429. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  18430. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  18431. return mirrorTexture;
  18432. }
  18433. else if (parsedTexture.isRenderTarget) {
  18434. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  18435. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  18436. return renderTargetTexture;
  18437. }
  18438. else {
  18439. var texture;
  18440. if (parsedTexture.base64String) {
  18441. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  18442. }
  18443. else {
  18444. texture = new Texture(rootUrl + parsedTexture.name, scene);
  18445. }
  18446. return texture;
  18447. }
  18448. }, parsedTexture, scene);
  18449. // Update Sampling Mode
  18450. if (parsedTexture.samplingMode) {
  18451. var sampling = parsedTexture.samplingMode;
  18452. if (texture._samplingMode !== sampling) {
  18453. texture.updateSamplingMode(sampling);
  18454. }
  18455. }
  18456. // Animations
  18457. if (parsedTexture.animations) {
  18458. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  18459. var parsedAnimation = parsedTexture.animations[animationIndex];
  18460. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  18461. }
  18462. }
  18463. return texture;
  18464. };
  18465. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  18466. if (deleteBuffer === void 0) { deleteBuffer = false; }
  18467. if (noMipmap === void 0) { noMipmap = false; }
  18468. if (invertY === void 0) { invertY = true; }
  18469. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  18470. if (onLoad === void 0) { onLoad = null; }
  18471. if (onError === void 0) { onError = null; }
  18472. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  18473. if (name.substr(0, 5) !== "data:") {
  18474. name = "data:" + name;
  18475. }
  18476. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  18477. };
  18478. return Texture;
  18479. }(BABYLON.BaseTexture));
  18480. // Constants
  18481. Texture.NEAREST_SAMPLINGMODE = 1;
  18482. Texture.BILINEAR_SAMPLINGMODE = 2;
  18483. Texture.TRILINEAR_SAMPLINGMODE = 3;
  18484. Texture.EXPLICIT_MODE = 0;
  18485. Texture.SPHERICAL_MODE = 1;
  18486. Texture.PLANAR_MODE = 2;
  18487. Texture.CUBIC_MODE = 3;
  18488. Texture.PROJECTION_MODE = 4;
  18489. Texture.SKYBOX_MODE = 5;
  18490. Texture.INVCUBIC_MODE = 6;
  18491. Texture.EQUIRECTANGULAR_MODE = 7;
  18492. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  18493. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  18494. Texture.CLAMP_ADDRESSMODE = 0;
  18495. Texture.WRAP_ADDRESSMODE = 1;
  18496. Texture.MIRROR_ADDRESSMODE = 2;
  18497. __decorate([
  18498. BABYLON.serialize()
  18499. ], Texture.prototype, "url", void 0);
  18500. __decorate([
  18501. BABYLON.serialize()
  18502. ], Texture.prototype, "uOffset", void 0);
  18503. __decorate([
  18504. BABYLON.serialize()
  18505. ], Texture.prototype, "vOffset", void 0);
  18506. __decorate([
  18507. BABYLON.serialize()
  18508. ], Texture.prototype, "uScale", void 0);
  18509. __decorate([
  18510. BABYLON.serialize()
  18511. ], Texture.prototype, "vScale", void 0);
  18512. __decorate([
  18513. BABYLON.serialize()
  18514. ], Texture.prototype, "uAng", void 0);
  18515. __decorate([
  18516. BABYLON.serialize()
  18517. ], Texture.prototype, "vAng", void 0);
  18518. __decorate([
  18519. BABYLON.serialize()
  18520. ], Texture.prototype, "wAng", void 0);
  18521. BABYLON.Texture = Texture;
  18522. })(BABYLON || (BABYLON = {}));
  18523. //# sourceMappingURL=babylon.texture.js.map
  18524. var BABYLON;
  18525. (function (BABYLON) {
  18526. var _InstancesBatch = (function () {
  18527. function _InstancesBatch() {
  18528. this.mustReturn = false;
  18529. this.visibleInstances = new Array();
  18530. this.renderSelf = new Array();
  18531. }
  18532. return _InstancesBatch;
  18533. }());
  18534. BABYLON._InstancesBatch = _InstancesBatch;
  18535. var Mesh = (function (_super) {
  18536. __extends(Mesh, _super);
  18537. /**
  18538. * @constructor
  18539. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  18540. * @param {Scene} scene The scene to add this mesh to.
  18541. * @param {Node} parent The parent of this mesh, if it has one
  18542. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  18543. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  18544. * When false, achieved by calling a clone(), also passing False.
  18545. * This will make creation of children, recursive.
  18546. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  18547. */
  18548. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  18549. if (parent === void 0) { parent = null; }
  18550. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  18551. var _this = _super.call(this, name, scene) || this;
  18552. // Events
  18553. /**
  18554. * An event triggered before rendering the mesh
  18555. * @type {BABYLON.Observable}
  18556. */
  18557. _this.onBeforeRenderObservable = new BABYLON.Observable();
  18558. /**
  18559. * An event triggered after rendering the mesh
  18560. * @type {BABYLON.Observable}
  18561. */
  18562. _this.onAfterRenderObservable = new BABYLON.Observable();
  18563. /**
  18564. * An event triggered before drawing the mesh
  18565. * @type {BABYLON.Observable}
  18566. */
  18567. _this.onBeforeDrawObservable = new BABYLON.Observable();
  18568. // Members
  18569. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  18570. _this.instances = new Array();
  18571. _this._LODLevels = new Array();
  18572. _this._visibleInstances = {};
  18573. _this._renderIdForInstances = new Array();
  18574. _this._batchCache = new _InstancesBatch();
  18575. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  18576. _this._sideOrientation = Mesh._DEFAULTSIDE;
  18577. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  18578. // Will be used to save a source mesh reference, If any
  18579. _this._source = null;
  18580. if (source) {
  18581. // Source mesh
  18582. _this._source = source;
  18583. // Geometry
  18584. if (source._geometry) {
  18585. source._geometry.applyToMesh(_this);
  18586. }
  18587. // Deep copy
  18588. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId"], ["_poseMatrix"]);
  18589. // Parent
  18590. _this.parent = source.parent;
  18591. // Pivot
  18592. _this.setPivotMatrix(source.getPivotMatrix());
  18593. _this.id = name + "." + source.id;
  18594. // Material
  18595. _this.material = source.material;
  18596. var index;
  18597. if (!doNotCloneChildren) {
  18598. // Children
  18599. for (index = 0; index < scene.meshes.length; index++) {
  18600. var mesh = scene.meshes[index];
  18601. if (mesh.parent === source) {
  18602. // doNotCloneChildren is always going to be False
  18603. var newChild = mesh.clone(name + "." + mesh.name, _this, doNotCloneChildren);
  18604. }
  18605. }
  18606. }
  18607. // Physics clone
  18608. var physicsEngine = _this.getScene().getPhysicsEngine();
  18609. if (clonePhysicsImpostor && physicsEngine) {
  18610. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  18611. if (impostor) {
  18612. _this.physicsImpostor = impostor.clone(_this);
  18613. }
  18614. }
  18615. // Particles
  18616. for (index = 0; index < scene.particleSystems.length; index++) {
  18617. var system = scene.particleSystems[index];
  18618. if (system.emitter === source) {
  18619. system.clone(system.name, _this);
  18620. }
  18621. }
  18622. _this.computeWorldMatrix(true);
  18623. }
  18624. // Parent
  18625. if (parent !== null) {
  18626. _this.parent = parent;
  18627. }
  18628. return _this;
  18629. }
  18630. Object.defineProperty(Mesh, "FRONTSIDE", {
  18631. /**
  18632. * Mesh side orientation : usually the external or front surface
  18633. */
  18634. get: function () {
  18635. return Mesh._FRONTSIDE;
  18636. },
  18637. enumerable: true,
  18638. configurable: true
  18639. });
  18640. Object.defineProperty(Mesh, "BACKSIDE", {
  18641. /**
  18642. * Mesh side orientation : usually the internal or back surface
  18643. */
  18644. get: function () {
  18645. return Mesh._BACKSIDE;
  18646. },
  18647. enumerable: true,
  18648. configurable: true
  18649. });
  18650. Object.defineProperty(Mesh, "DOUBLESIDE", {
  18651. /**
  18652. * Mesh side orientation : both internal and external or front and back surfaces
  18653. */
  18654. get: function () {
  18655. return Mesh._DOUBLESIDE;
  18656. },
  18657. enumerable: true,
  18658. configurable: true
  18659. });
  18660. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  18661. /**
  18662. * Mesh side orientation : by default, `FRONTSIDE`
  18663. */
  18664. get: function () {
  18665. return Mesh._DEFAULTSIDE;
  18666. },
  18667. enumerable: true,
  18668. configurable: true
  18669. });
  18670. Object.defineProperty(Mesh, "NO_CAP", {
  18671. /**
  18672. * Mesh cap setting : no cap
  18673. */
  18674. get: function () {
  18675. return Mesh._NO_CAP;
  18676. },
  18677. enumerable: true,
  18678. configurable: true
  18679. });
  18680. Object.defineProperty(Mesh, "CAP_START", {
  18681. /**
  18682. * Mesh cap setting : one cap at the beginning of the mesh
  18683. */
  18684. get: function () {
  18685. return Mesh._CAP_START;
  18686. },
  18687. enumerable: true,
  18688. configurable: true
  18689. });
  18690. Object.defineProperty(Mesh, "CAP_END", {
  18691. /**
  18692. * Mesh cap setting : one cap at the end of the mesh
  18693. */
  18694. get: function () {
  18695. return Mesh._CAP_END;
  18696. },
  18697. enumerable: true,
  18698. configurable: true
  18699. });
  18700. Object.defineProperty(Mesh, "CAP_ALL", {
  18701. /**
  18702. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  18703. */
  18704. get: function () {
  18705. return Mesh._CAP_ALL;
  18706. },
  18707. enumerable: true,
  18708. configurable: true
  18709. });
  18710. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  18711. set: function (callback) {
  18712. if (this._onBeforeDrawObserver) {
  18713. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  18714. }
  18715. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  18716. },
  18717. enumerable: true,
  18718. configurable: true
  18719. });
  18720. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  18721. get: function () {
  18722. return this._morphTargetManager;
  18723. },
  18724. set: function (value) {
  18725. if (this._morphTargetManager === value) {
  18726. return;
  18727. }
  18728. this._morphTargetManager = value;
  18729. this._syncGeometryWithMorphTargetManager();
  18730. },
  18731. enumerable: true,
  18732. configurable: true
  18733. });
  18734. Object.defineProperty(Mesh.prototype, "source", {
  18735. get: function () {
  18736. return this._source;
  18737. },
  18738. enumerable: true,
  18739. configurable: true
  18740. });
  18741. // Methods
  18742. /**
  18743. * Returns the string "Mesh".
  18744. */
  18745. Mesh.prototype.getClassName = function () {
  18746. return "Mesh";
  18747. };
  18748. /**
  18749. * Returns a string.
  18750. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  18751. */
  18752. Mesh.prototype.toString = function (fullDetails) {
  18753. var ret = _super.prototype.toString.call(this, fullDetails);
  18754. ret += ", n vertices: " + this.getTotalVertices();
  18755. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  18756. if (this.animations) {
  18757. for (var i = 0; i < this.animations.length; i++) {
  18758. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  18759. }
  18760. }
  18761. if (fullDetails) {
  18762. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  18763. }
  18764. return ret;
  18765. };
  18766. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  18767. /**
  18768. * True if the mesh has some Levels Of Details (LOD).
  18769. * Returns a boolean.
  18770. */
  18771. get: function () {
  18772. return this._LODLevels.length > 0;
  18773. },
  18774. enumerable: true,
  18775. configurable: true
  18776. });
  18777. Mesh.prototype._sortLODLevels = function () {
  18778. this._LODLevels.sort(function (a, b) {
  18779. if (a.distance < b.distance) {
  18780. return 1;
  18781. }
  18782. if (a.distance > b.distance) {
  18783. return -1;
  18784. }
  18785. return 0;
  18786. });
  18787. };
  18788. /**
  18789. * Add a mesh as LOD level triggered at the given distance.
  18790. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  18791. * @param {number} distance The distance from the center of the object to show this level
  18792. * @param {Mesh} mesh The mesh to be added as LOD level
  18793. * @return {Mesh} This mesh (for chaining)
  18794. */
  18795. Mesh.prototype.addLODLevel = function (distance, mesh) {
  18796. if (mesh && mesh._masterMesh) {
  18797. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  18798. return this;
  18799. }
  18800. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  18801. this._LODLevels.push(level);
  18802. if (mesh) {
  18803. mesh._masterMesh = this;
  18804. }
  18805. this._sortLODLevels();
  18806. return this;
  18807. };
  18808. /**
  18809. * Returns the LOD level mesh at the passed distance or null if not found.
  18810. * It is related to the method `addLODLevel(distance, mesh)`.
  18811. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  18812. * Returns an object Mesh or `null`.
  18813. */
  18814. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  18815. for (var index = 0; index < this._LODLevels.length; index++) {
  18816. var level = this._LODLevels[index];
  18817. if (level.distance === distance) {
  18818. return level.mesh;
  18819. }
  18820. }
  18821. return null;
  18822. };
  18823. /**
  18824. * Remove a mesh from the LOD array
  18825. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  18826. * @param {Mesh} mesh The mesh to be removed.
  18827. * @return {Mesh} This mesh (for chaining)
  18828. */
  18829. Mesh.prototype.removeLODLevel = function (mesh) {
  18830. for (var index = 0; index < this._LODLevels.length; index++) {
  18831. if (this._LODLevels[index].mesh === mesh) {
  18832. this._LODLevels.splice(index, 1);
  18833. if (mesh) {
  18834. mesh._masterMesh = null;
  18835. }
  18836. }
  18837. }
  18838. this._sortLODLevels();
  18839. return this;
  18840. };
  18841. /**
  18842. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  18843. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  18844. */
  18845. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  18846. if (!this._LODLevels || this._LODLevels.length === 0) {
  18847. return this;
  18848. }
  18849. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  18850. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  18851. if (this.onLODLevelSelection) {
  18852. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  18853. }
  18854. return this;
  18855. }
  18856. for (var index = 0; index < this._LODLevels.length; index++) {
  18857. var level = this._LODLevels[index];
  18858. if (level.distance < distanceToCamera) {
  18859. if (level.mesh) {
  18860. level.mesh._preActivate();
  18861. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  18862. }
  18863. if (this.onLODLevelSelection) {
  18864. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  18865. }
  18866. return level.mesh;
  18867. }
  18868. }
  18869. if (this.onLODLevelSelection) {
  18870. this.onLODLevelSelection(distanceToCamera, this, this);
  18871. }
  18872. return this;
  18873. };
  18874. Object.defineProperty(Mesh.prototype, "geometry", {
  18875. /**
  18876. * Returns the mesh internal Geometry object.
  18877. */
  18878. get: function () {
  18879. return this._geometry;
  18880. },
  18881. enumerable: true,
  18882. configurable: true
  18883. });
  18884. /**
  18885. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  18886. */
  18887. Mesh.prototype.getTotalVertices = function () {
  18888. if (!this._geometry) {
  18889. return 0;
  18890. }
  18891. return this._geometry.getTotalVertices();
  18892. };
  18893. /**
  18894. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  18895. * 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.
  18896. * You can force the copy with forceCopy === true
  18897. * Returns null if the mesh has no geometry or no vertex buffer.
  18898. * Possible `kind` values :
  18899. * - BABYLON.VertexBuffer.PositionKind
  18900. * - BABYLON.VertexBuffer.UVKind
  18901. * - BABYLON.VertexBuffer.UV2Kind
  18902. * - BABYLON.VertexBuffer.UV3Kind
  18903. * - BABYLON.VertexBuffer.UV4Kind
  18904. * - BABYLON.VertexBuffer.UV5Kind
  18905. * - BABYLON.VertexBuffer.UV6Kind
  18906. * - BABYLON.VertexBuffer.ColorKind
  18907. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18908. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18909. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18910. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18911. */
  18912. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  18913. if (!this._geometry) {
  18914. return null;
  18915. }
  18916. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  18917. };
  18918. /**
  18919. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  18920. * Returns `undefined` if the mesh has no geometry.
  18921. * Possible `kind` values :
  18922. * - BABYLON.VertexBuffer.PositionKind
  18923. * - BABYLON.VertexBuffer.UVKind
  18924. * - BABYLON.VertexBuffer.UV2Kind
  18925. * - BABYLON.VertexBuffer.UV3Kind
  18926. * - BABYLON.VertexBuffer.UV4Kind
  18927. * - BABYLON.VertexBuffer.UV5Kind
  18928. * - BABYLON.VertexBuffer.UV6Kind
  18929. * - BABYLON.VertexBuffer.ColorKind
  18930. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18931. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18932. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18933. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18934. */
  18935. Mesh.prototype.getVertexBuffer = function (kind) {
  18936. if (!this._geometry) {
  18937. return undefined;
  18938. }
  18939. return this._geometry.getVertexBuffer(kind);
  18940. };
  18941. /**
  18942. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  18943. * Possible `kind` values :
  18944. * - BABYLON.VertexBuffer.PositionKind
  18945. * - BABYLON.VertexBuffer.UVKind
  18946. * - BABYLON.VertexBuffer.UV2Kind
  18947. * - BABYLON.VertexBuffer.UV3Kind
  18948. * - BABYLON.VertexBuffer.UV4Kind
  18949. * - BABYLON.VertexBuffer.UV5Kind
  18950. * - BABYLON.VertexBuffer.UV6Kind
  18951. * - BABYLON.VertexBuffer.ColorKind
  18952. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18953. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18954. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18955. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18956. */
  18957. Mesh.prototype.isVerticesDataPresent = function (kind) {
  18958. if (!this._geometry) {
  18959. if (this._delayInfo) {
  18960. return this._delayInfo.indexOf(kind) !== -1;
  18961. }
  18962. return false;
  18963. }
  18964. return this._geometry.isVerticesDataPresent(kind);
  18965. };
  18966. /**
  18967. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  18968. * Possible `kind` values :
  18969. * - BABYLON.VertexBuffer.PositionKind
  18970. * - BABYLON.VertexBuffer.UVKind
  18971. * - BABYLON.VertexBuffer.UV2Kind
  18972. * - BABYLON.VertexBuffer.UV3Kind
  18973. * - BABYLON.VertexBuffer.UV4Kind
  18974. * - BABYLON.VertexBuffer.UV5Kind
  18975. * - BABYLON.VertexBuffer.UV6Kind
  18976. * - BABYLON.VertexBuffer.ColorKind
  18977. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18978. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18979. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18980. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18981. */
  18982. Mesh.prototype.getVerticesDataKinds = function () {
  18983. if (!this._geometry) {
  18984. var result = [];
  18985. if (this._delayInfo) {
  18986. this._delayInfo.forEach(function (kind, index, array) {
  18987. result.push(kind);
  18988. });
  18989. }
  18990. return result;
  18991. }
  18992. return this._geometry.getVerticesDataKinds();
  18993. };
  18994. /**
  18995. * Returns a positive integer : the total number of indices in this mesh geometry.
  18996. * Returns zero if the mesh has no geometry.
  18997. */
  18998. Mesh.prototype.getTotalIndices = function () {
  18999. if (!this._geometry) {
  19000. return 0;
  19001. }
  19002. return this._geometry.getTotalIndices();
  19003. };
  19004. /**
  19005. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  19006. * 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.
  19007. * Returns an empty array if the mesh has no geometry.
  19008. */
  19009. Mesh.prototype.getIndices = function (copyWhenShared) {
  19010. if (!this._geometry) {
  19011. return [];
  19012. }
  19013. return this._geometry.getIndices(copyWhenShared);
  19014. };
  19015. Object.defineProperty(Mesh.prototype, "isBlocked", {
  19016. get: function () {
  19017. return this._masterMesh !== null && this._masterMesh !== undefined;
  19018. },
  19019. enumerable: true,
  19020. configurable: true
  19021. });
  19022. /**
  19023. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  19024. */
  19025. Mesh.prototype.isReady = function () {
  19026. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  19027. return false;
  19028. }
  19029. return _super.prototype.isReady.call(this);
  19030. };
  19031. /**
  19032. * Boolean : true if the mesh has been disposed.
  19033. */
  19034. Mesh.prototype.isDisposed = function () {
  19035. return this._isDisposed;
  19036. };
  19037. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  19038. get: function () {
  19039. return this._sideOrientation;
  19040. },
  19041. /**
  19042. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  19043. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  19044. */
  19045. set: function (sideO) {
  19046. this._sideOrientation = sideO;
  19047. },
  19048. enumerable: true,
  19049. configurable: true
  19050. });
  19051. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  19052. /**
  19053. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  19054. * This property is pertinent only for updatable parametric shapes.
  19055. */
  19056. get: function () {
  19057. return this._areNormalsFrozen;
  19058. },
  19059. enumerable: true,
  19060. configurable: true
  19061. });
  19062. /**
  19063. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  19064. * It has no effect at all on other shapes.
  19065. * It prevents the mesh normals from being recomputed on next `positions` array update.
  19066. * Returns the Mesh.
  19067. */
  19068. Mesh.prototype.freezeNormals = function () {
  19069. this._areNormalsFrozen = true;
  19070. return this;
  19071. };
  19072. /**
  19073. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  19074. * It has no effect at all on other shapes.
  19075. * It reactivates the mesh normals computation if it was previously frozen.
  19076. * Returns the Mesh.
  19077. */
  19078. Mesh.prototype.unfreezeNormals = function () {
  19079. this._areNormalsFrozen = false;
  19080. return this;
  19081. };
  19082. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  19083. /**
  19084. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  19085. */
  19086. set: function (count) {
  19087. this._overridenInstanceCount = count;
  19088. },
  19089. enumerable: true,
  19090. configurable: true
  19091. });
  19092. // Methods
  19093. Mesh.prototype._preActivate = function () {
  19094. var sceneRenderId = this.getScene().getRenderId();
  19095. if (this._preActivateId === sceneRenderId) {
  19096. return this;
  19097. }
  19098. this._preActivateId = sceneRenderId;
  19099. this._visibleInstances = null;
  19100. return this;
  19101. };
  19102. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  19103. if (this._visibleInstances) {
  19104. this._visibleInstances.intermediateDefaultRenderId = renderId;
  19105. }
  19106. return this;
  19107. };
  19108. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  19109. if (!this._visibleInstances) {
  19110. this._visibleInstances = {};
  19111. this._visibleInstances.defaultRenderId = renderId;
  19112. this._visibleInstances.selfDefaultRenderId = this._renderId;
  19113. }
  19114. if (!this._visibleInstances[renderId]) {
  19115. this._visibleInstances[renderId] = new Array();
  19116. }
  19117. this._visibleInstances[renderId].push(instance);
  19118. return this;
  19119. };
  19120. /**
  19121. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  19122. * This means the mesh underlying bounding box and sphere are recomputed.
  19123. * Returns the Mesh.
  19124. */
  19125. Mesh.prototype.refreshBoundingInfo = function () {
  19126. if (this._boundingInfo.isLocked) {
  19127. return;
  19128. }
  19129. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19130. if (data) {
  19131. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  19132. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  19133. }
  19134. if (this.subMeshes) {
  19135. for (var index = 0; index < this.subMeshes.length; index++) {
  19136. this.subMeshes[index].refreshBoundingInfo();
  19137. }
  19138. }
  19139. this._updateBoundingInfo();
  19140. return this;
  19141. };
  19142. Mesh.prototype._createGlobalSubMesh = function () {
  19143. var totalVertices = this.getTotalVertices();
  19144. if (!totalVertices || !this.getIndices()) {
  19145. return null;
  19146. }
  19147. this.releaseSubMeshes();
  19148. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  19149. };
  19150. Mesh.prototype.subdivide = function (count) {
  19151. if (count < 1) {
  19152. return;
  19153. }
  19154. var totalIndices = this.getTotalIndices();
  19155. var subdivisionSize = (totalIndices / count) | 0;
  19156. var offset = 0;
  19157. // Ensure that subdivisionSize is a multiple of 3
  19158. while (subdivisionSize % 3 !== 0) {
  19159. subdivisionSize++;
  19160. }
  19161. this.releaseSubMeshes();
  19162. for (var index = 0; index < count; index++) {
  19163. if (offset >= totalIndices) {
  19164. break;
  19165. }
  19166. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  19167. offset += subdivisionSize;
  19168. }
  19169. this.synchronizeInstances();
  19170. };
  19171. /**
  19172. * Sets the vertex data of the mesh geometry for the requested `kind`.
  19173. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  19174. * The `data` are either a numeric array either a Float32Array.
  19175. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  19176. * 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).
  19177. * Note that a new underlying VertexBuffer object is created each call.
  19178. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  19179. *
  19180. * Possible `kind` values :
  19181. * - BABYLON.VertexBuffer.PositionKind
  19182. * - BABYLON.VertexBuffer.UVKind
  19183. * - BABYLON.VertexBuffer.UV2Kind
  19184. * - BABYLON.VertexBuffer.UV3Kind
  19185. * - BABYLON.VertexBuffer.UV4Kind
  19186. * - BABYLON.VertexBuffer.UV5Kind
  19187. * - BABYLON.VertexBuffer.UV6Kind
  19188. * - BABYLON.VertexBuffer.ColorKind
  19189. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19190. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19191. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19192. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19193. *
  19194. * Returns the Mesh.
  19195. */
  19196. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  19197. if (!this._geometry) {
  19198. var vertexData = new BABYLON.VertexData();
  19199. vertexData.set(data, kind);
  19200. var scene = this.getScene();
  19201. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  19202. }
  19203. else {
  19204. this._geometry.setVerticesData(kind, data, updatable, stride);
  19205. }
  19206. return this;
  19207. };
  19208. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  19209. if (updatable === void 0) { updatable = true; }
  19210. if (this.getVertexBuffer(kind).isUpdatable() === updatable) {
  19211. return;
  19212. }
  19213. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  19214. };
  19215. /**
  19216. * Sets the mesh VertexBuffer.
  19217. * Returns the Mesh.
  19218. */
  19219. Mesh.prototype.setVerticesBuffer = function (buffer) {
  19220. if (!this._geometry) {
  19221. var scene = this.getScene();
  19222. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene).applyToMesh(this);
  19223. }
  19224. this._geometry.setVerticesBuffer(buffer);
  19225. return this;
  19226. };
  19227. /**
  19228. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  19229. * If the mesh has no geometry, it is simply returned as it is.
  19230. * The `data` are either a numeric array either a Float32Array.
  19231. * No new underlying VertexBuffer object is created.
  19232. * 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.
  19233. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  19234. *
  19235. * Possible `kind` values :
  19236. * - BABYLON.VertexBuffer.PositionKind
  19237. * - BABYLON.VertexBuffer.UVKind
  19238. * - BABYLON.VertexBuffer.UV2Kind
  19239. * - BABYLON.VertexBuffer.UV3Kind
  19240. * - BABYLON.VertexBuffer.UV4Kind
  19241. * - BABYLON.VertexBuffer.UV5Kind
  19242. * - BABYLON.VertexBuffer.UV6Kind
  19243. * - BABYLON.VertexBuffer.ColorKind
  19244. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19245. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19246. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19247. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19248. *
  19249. * Returns the Mesh.
  19250. */
  19251. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  19252. if (!this._geometry) {
  19253. return;
  19254. }
  19255. if (!makeItUnique) {
  19256. this._geometry.updateVerticesData(kind, data, updateExtends);
  19257. }
  19258. else {
  19259. this.makeGeometryUnique();
  19260. this.updateVerticesData(kind, data, updateExtends, false);
  19261. }
  19262. return this;
  19263. };
  19264. /**
  19265. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  19266. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  19267. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  19268. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  19269. * Returns the Mesh.
  19270. */
  19271. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  19272. if (computeNormals === void 0) { computeNormals = true; }
  19273. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19274. positionFunction(positions);
  19275. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  19276. if (computeNormals) {
  19277. var indices = this.getIndices();
  19278. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19279. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  19280. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  19281. }
  19282. return this;
  19283. };
  19284. /**
  19285. * Creates a un-shared specific occurence of the geometry for the mesh.
  19286. * Returns the Mesh.
  19287. */
  19288. Mesh.prototype.makeGeometryUnique = function () {
  19289. if (!this._geometry) {
  19290. return;
  19291. }
  19292. var oldGeometry = this._geometry;
  19293. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  19294. oldGeometry.releaseForMesh(this, true);
  19295. geometry.applyToMesh(this);
  19296. return this;
  19297. };
  19298. /**
  19299. * Sets the mesh indices.
  19300. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  19301. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  19302. * This method creates a new index buffer each call.
  19303. * Returns the Mesh.
  19304. */
  19305. Mesh.prototype.setIndices = function (indices, totalVertices) {
  19306. if (!this._geometry) {
  19307. var vertexData = new BABYLON.VertexData();
  19308. vertexData.indices = indices;
  19309. var scene = this.getScene();
  19310. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  19311. }
  19312. else {
  19313. this._geometry.setIndices(indices, totalVertices);
  19314. }
  19315. return this;
  19316. };
  19317. /**
  19318. * Invert the geometry to move from a right handed system to a left handed one.
  19319. * Returns the Mesh.
  19320. */
  19321. Mesh.prototype.toLeftHanded = function () {
  19322. if (!this._geometry) {
  19323. return;
  19324. }
  19325. this._geometry.toLeftHanded();
  19326. return this;
  19327. };
  19328. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  19329. var engine = this.getScene().getEngine();
  19330. // Wireframe
  19331. var indexToBind;
  19332. if (this._unIndexed) {
  19333. indexToBind = null;
  19334. }
  19335. else {
  19336. switch (fillMode) {
  19337. case BABYLON.Material.PointFillMode:
  19338. indexToBind = null;
  19339. break;
  19340. case BABYLON.Material.WireFrameFillMode:
  19341. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  19342. break;
  19343. default:
  19344. case BABYLON.Material.TriangleFillMode:
  19345. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  19346. break;
  19347. }
  19348. }
  19349. // VBOs
  19350. this._geometry._bind(effect, indexToBind);
  19351. return this;
  19352. };
  19353. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  19354. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  19355. return this;
  19356. }
  19357. this.onBeforeDrawObservable.notifyObservers(this);
  19358. var engine = this.getScene().getEngine();
  19359. // Draw order
  19360. switch (fillMode) {
  19361. case BABYLON.Material.PointFillMode:
  19362. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  19363. break;
  19364. case BABYLON.Material.WireFrameFillMode:
  19365. if (this._unIndexed) {
  19366. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  19367. }
  19368. else {
  19369. engine.draw(false, 0, instancesCount > 0 ? subMesh.linesIndexCount / 2 : subMesh.linesIndexCount, instancesCount);
  19370. }
  19371. break;
  19372. default:
  19373. if (this._unIndexed) {
  19374. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  19375. }
  19376. else {
  19377. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  19378. }
  19379. }
  19380. return this;
  19381. };
  19382. /**
  19383. * Registers for this mesh a javascript function called just before the rendering process.
  19384. * This function is passed the current mesh.
  19385. * Return the Mesh.
  19386. */
  19387. Mesh.prototype.registerBeforeRender = function (func) {
  19388. this.onBeforeRenderObservable.add(func);
  19389. return this;
  19390. };
  19391. /**
  19392. * Disposes a previously registered javascript function called before the rendering.
  19393. * This function is passed the current mesh.
  19394. * Returns the Mesh.
  19395. */
  19396. Mesh.prototype.unregisterBeforeRender = function (func) {
  19397. this.onBeforeRenderObservable.removeCallback(func);
  19398. return this;
  19399. };
  19400. /**
  19401. * Registers for this mesh a javascript function called just after the rendering is complete.
  19402. * This function is passed the current mesh.
  19403. * Returns the Mesh.
  19404. */
  19405. Mesh.prototype.registerAfterRender = function (func) {
  19406. this.onAfterRenderObservable.add(func);
  19407. return this;
  19408. };
  19409. /**
  19410. * Disposes a previously registered javascript function called after the rendering.
  19411. * This function is passed the current mesh.
  19412. * Return the Mesh.
  19413. */
  19414. Mesh.prototype.unregisterAfterRender = function (func) {
  19415. this.onAfterRenderObservable.removeCallback(func);
  19416. return this;
  19417. };
  19418. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  19419. var scene = this.getScene();
  19420. this._batchCache.mustReturn = false;
  19421. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  19422. this._batchCache.visibleInstances[subMeshId] = null;
  19423. if (this._visibleInstances) {
  19424. var currentRenderId = scene.getRenderId();
  19425. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  19426. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  19427. var selfRenderId = this._renderId;
  19428. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  19429. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  19430. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  19431. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  19432. }
  19433. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  19434. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  19435. this._batchCache.mustReturn = true;
  19436. return this._batchCache;
  19437. }
  19438. if (currentRenderId !== selfRenderId) {
  19439. this._batchCache.renderSelf[subMeshId] = false;
  19440. }
  19441. }
  19442. this._renderIdForInstances[subMeshId] = currentRenderId;
  19443. }
  19444. return this._batchCache;
  19445. };
  19446. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  19447. var visibleInstances = batch.visibleInstances[subMesh._id];
  19448. var matricesCount = visibleInstances.length + 1;
  19449. var bufferSize = matricesCount * 16 * 4;
  19450. var currentInstancesBufferSize = this._instancesBufferSize;
  19451. var instancesBuffer = this._instancesBuffer;
  19452. while (this._instancesBufferSize < bufferSize) {
  19453. this._instancesBufferSize *= 2;
  19454. }
  19455. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  19456. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  19457. }
  19458. var offset = 0;
  19459. var instancesCount = 0;
  19460. var world = this.getWorldMatrix();
  19461. if (batch.renderSelf[subMesh._id]) {
  19462. world.copyToArray(this._instancesData, offset);
  19463. offset += 16;
  19464. instancesCount++;
  19465. }
  19466. if (visibleInstances) {
  19467. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  19468. var instance = visibleInstances[instanceIndex];
  19469. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  19470. offset += 16;
  19471. instancesCount++;
  19472. }
  19473. }
  19474. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  19475. if (instancesBuffer) {
  19476. instancesBuffer.dispose();
  19477. }
  19478. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  19479. this._instancesBuffer = instancesBuffer;
  19480. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  19481. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  19482. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  19483. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  19484. }
  19485. else {
  19486. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  19487. }
  19488. this.geometry._bind(effect);
  19489. this._draw(subMesh, fillMode, instancesCount);
  19490. engine.unbindInstanceAttributes();
  19491. return this;
  19492. };
  19493. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  19494. var scene = this.getScene();
  19495. var engine = scene.getEngine();
  19496. if (hardwareInstancedRendering) {
  19497. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  19498. }
  19499. else {
  19500. if (batch.renderSelf[subMesh._id]) {
  19501. // Draw
  19502. if (onBeforeDraw) {
  19503. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  19504. }
  19505. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  19506. }
  19507. if (batch.visibleInstances[subMesh._id]) {
  19508. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  19509. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  19510. // World
  19511. var world = instance.getWorldMatrix();
  19512. if (onBeforeDraw) {
  19513. onBeforeDraw(true, world, effectiveMaterial);
  19514. }
  19515. // Draw
  19516. this._draw(subMesh, fillMode);
  19517. }
  19518. }
  19519. }
  19520. return this;
  19521. };
  19522. /**
  19523. * Triggers the draw call for the mesh.
  19524. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  19525. * Returns the Mesh.
  19526. */
  19527. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  19528. var scene = this.getScene();
  19529. // Managing instances
  19530. var batch = this._getInstancesRenderList(subMesh._id);
  19531. if (batch.mustReturn) {
  19532. return this;
  19533. }
  19534. // Checking geometry state
  19535. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  19536. return this;
  19537. }
  19538. var callbackIndex;
  19539. this.onBeforeRenderObservable.notifyObservers(this);
  19540. var engine = scene.getEngine();
  19541. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  19542. // Material
  19543. var effectiveMaterial = subMesh.getMaterial();
  19544. if (!effectiveMaterial) {
  19545. return this;
  19546. }
  19547. if (effectiveMaterial.storeEffectOnSubMeshes) {
  19548. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  19549. return this;
  19550. }
  19551. }
  19552. else if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  19553. return this;
  19554. }
  19555. // Outline - step 1
  19556. var savedDepthWrite = engine.getDepthWrite();
  19557. if (this.renderOutline) {
  19558. engine.setDepthWrite(false);
  19559. scene.getOutlineRenderer().render(subMesh, batch);
  19560. engine.setDepthWrite(savedDepthWrite);
  19561. }
  19562. var effect;
  19563. if (effectiveMaterial.storeEffectOnSubMeshes) {
  19564. effect = subMesh.effect;
  19565. }
  19566. else {
  19567. effect = effectiveMaterial.getEffect();
  19568. }
  19569. effectiveMaterial._preBind(effect);
  19570. // Bind
  19571. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  19572. this._bind(subMesh, effect, fillMode);
  19573. var world = this.getWorldMatrix();
  19574. if (effectiveMaterial.storeEffectOnSubMeshes) {
  19575. effectiveMaterial.bindForSubMesh(world, this, subMesh);
  19576. }
  19577. else {
  19578. effectiveMaterial.bind(world, this);
  19579. }
  19580. // Alpha mode
  19581. if (enableAlphaMode) {
  19582. engine.setAlphaMode(effectiveMaterial.alphaMode);
  19583. }
  19584. // Draw
  19585. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, effectiveMaterial);
  19586. // Unbind
  19587. effectiveMaterial.unbind();
  19588. // Outline - step 2
  19589. if (this.renderOutline && savedDepthWrite) {
  19590. engine.setDepthWrite(true);
  19591. engine.setColorWrite(false);
  19592. scene.getOutlineRenderer().render(subMesh, batch);
  19593. engine.setColorWrite(true);
  19594. }
  19595. // Overlay
  19596. if (this.renderOverlay) {
  19597. var currentMode = engine.getAlphaMode();
  19598. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  19599. scene.getOutlineRenderer().render(subMesh, batch, true);
  19600. engine.setAlphaMode(currentMode);
  19601. }
  19602. this.onAfterRenderObservable.notifyObservers(this);
  19603. return this;
  19604. };
  19605. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  19606. if (isInstance) {
  19607. effectiveMaterial.bindOnlyWorldMatrix(world);
  19608. }
  19609. return this;
  19610. };
  19611. /**
  19612. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  19613. */
  19614. Mesh.prototype.getEmittedParticleSystems = function () {
  19615. var results = new Array();
  19616. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  19617. var particleSystem = this.getScene().particleSystems[index];
  19618. if (particleSystem.emitter === this) {
  19619. results.push(particleSystem);
  19620. }
  19621. }
  19622. return results;
  19623. };
  19624. /**
  19625. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  19626. */
  19627. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  19628. var results = new Array();
  19629. var descendants = this.getDescendants();
  19630. descendants.push(this);
  19631. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  19632. var particleSystem = this.getScene().particleSystems[index];
  19633. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  19634. results.push(particleSystem);
  19635. }
  19636. }
  19637. return results;
  19638. };
  19639. Mesh.prototype._checkDelayState = function () {
  19640. var scene = this.getScene();
  19641. if (this._geometry) {
  19642. this._geometry.load(scene);
  19643. }
  19644. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  19645. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  19646. this._queueLoad(this, scene);
  19647. }
  19648. return this;
  19649. };
  19650. Mesh.prototype._queueLoad = function (mesh, scene) {
  19651. var _this = this;
  19652. scene._addPendingData(mesh);
  19653. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  19654. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  19655. if (data instanceof ArrayBuffer) {
  19656. _this._delayLoadingFunction(data, _this);
  19657. }
  19658. else {
  19659. _this._delayLoadingFunction(JSON.parse(data), _this);
  19660. }
  19661. _this.instances.forEach(function (instance) {
  19662. instance._syncSubMeshes();
  19663. });
  19664. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  19665. scene._removePendingData(_this);
  19666. }, function () { }, scene.database, getBinaryData);
  19667. return this;
  19668. };
  19669. /**
  19670. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  19671. */
  19672. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  19673. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  19674. return false;
  19675. }
  19676. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  19677. return false;
  19678. }
  19679. this._checkDelayState();
  19680. return true;
  19681. };
  19682. /**
  19683. * Sets the mesh material by the material or multiMaterial `id` property.
  19684. * The material `id` is a string identifying the material or the multiMaterial.
  19685. * This method returns the Mesh.
  19686. */
  19687. Mesh.prototype.setMaterialByID = function (id) {
  19688. var materials = this.getScene().materials;
  19689. var index;
  19690. for (index = materials.length - 1; index > -1; index--) {
  19691. if (materials[index].id === id) {
  19692. this.material = materials[index];
  19693. return this;
  19694. }
  19695. }
  19696. // Multi
  19697. var multiMaterials = this.getScene().multiMaterials;
  19698. for (index = multiMaterials.length - 1; index > -1; index--) {
  19699. if (multiMaterials[index].id === id) {
  19700. this.material = multiMaterials[index];
  19701. return this;
  19702. }
  19703. }
  19704. return this;
  19705. };
  19706. /**
  19707. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  19708. */
  19709. Mesh.prototype.getAnimatables = function () {
  19710. var results = [];
  19711. if (this.material) {
  19712. results.push(this.material);
  19713. }
  19714. if (this.skeleton) {
  19715. results.push(this.skeleton);
  19716. }
  19717. return results;
  19718. };
  19719. /**
  19720. * Modifies the mesh geometry according to the passed transformation matrix.
  19721. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  19722. * The mesh normals are modified accordingly the same transformation.
  19723. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  19724. * Note that, under the hood, this method sets a new VertexBuffer each call.
  19725. * Returns the Mesh.
  19726. */
  19727. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  19728. // Position
  19729. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  19730. return this;
  19731. }
  19732. var submeshes = this.subMeshes.splice(0);
  19733. this._resetPointsArrayCache();
  19734. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19735. var temp = [];
  19736. var index;
  19737. for (index = 0; index < data.length; index += 3) {
  19738. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  19739. }
  19740. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  19741. // Normals
  19742. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  19743. return this;
  19744. }
  19745. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19746. temp = [];
  19747. for (index = 0; index < data.length; index += 3) {
  19748. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  19749. }
  19750. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  19751. // flip faces?
  19752. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  19753. this.flipFaces();
  19754. }
  19755. // Restore submeshes
  19756. this.releaseSubMeshes();
  19757. this.subMeshes = submeshes;
  19758. return this;
  19759. };
  19760. /**
  19761. * Modifies the mesh geometry according to its own current World Matrix.
  19762. * The mesh World Matrix is then reset.
  19763. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  19764. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  19765. * Note that, under the hood, this method sets a new VertexBuffer each call.
  19766. * Returns the Mesh.
  19767. */
  19768. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  19769. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  19770. this.scaling.copyFromFloats(1, 1, 1);
  19771. this.position.copyFromFloats(0, 0, 0);
  19772. this.rotation.copyFromFloats(0, 0, 0);
  19773. //only if quaternion is already set
  19774. if (this.rotationQuaternion) {
  19775. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  19776. }
  19777. this._worldMatrix = BABYLON.Matrix.Identity();
  19778. return this;
  19779. };
  19780. // Cache
  19781. Mesh.prototype._resetPointsArrayCache = function () {
  19782. this._positions = null;
  19783. return this;
  19784. };
  19785. Mesh.prototype._generatePointsArray = function () {
  19786. if (this._positions)
  19787. return true;
  19788. this._positions = [];
  19789. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19790. if (!data) {
  19791. return false;
  19792. }
  19793. for (var index = 0; index < data.length; index += 3) {
  19794. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  19795. }
  19796. return true;
  19797. };
  19798. /**
  19799. * Returns a new Mesh object generated from the current mesh properties.
  19800. * This method must not get confused with createInstance().
  19801. * The parameter `name` is a string, the name given to the new mesh.
  19802. * The optional parameter `newParent` can be any Node object (default `null`).
  19803. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  19804. * 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.
  19805. */
  19806. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  19807. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  19808. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  19809. };
  19810. /**
  19811. * Disposes the mesh.
  19812. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  19813. */
  19814. Mesh.prototype.dispose = function (doNotRecurse) {
  19815. var _this = this;
  19816. this.morphTargetManager = undefined;
  19817. if (this._geometry) {
  19818. this._geometry.releaseForMesh(this, true);
  19819. }
  19820. // Sources
  19821. var meshes = this.getScene().meshes;
  19822. meshes.forEach(function (mesh) {
  19823. if (mesh._source && mesh._source === _this) {
  19824. mesh._source = null;
  19825. }
  19826. });
  19827. this._source = null;
  19828. // Instances
  19829. if (this._instancesBuffer) {
  19830. this._instancesBuffer.dispose();
  19831. this._instancesBuffer = null;
  19832. }
  19833. while (this.instances.length) {
  19834. this.instances[0].dispose();
  19835. }
  19836. // Highlight layers.
  19837. var highlightLayers = this.getScene().highlightLayers;
  19838. for (var i = 0; i < highlightLayers.length; i++) {
  19839. var highlightLayer = highlightLayers[i];
  19840. if (highlightLayer) {
  19841. highlightLayer.removeMesh(this);
  19842. highlightLayer.removeExcludedMesh(this);
  19843. }
  19844. }
  19845. _super.prototype.dispose.call(this, doNotRecurse);
  19846. };
  19847. /**
  19848. * Modifies the mesh geometry according to a displacement map.
  19849. * 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.
  19850. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  19851. * This method returns nothing.
  19852. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  19853. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  19854. * 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.
  19855. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  19856. * The parameter `uvScale` is an optional vector2 used to scale UV.
  19857. *
  19858. * Returns the Mesh.
  19859. */
  19860. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  19861. var _this = this;
  19862. var scene = this.getScene();
  19863. var onload = function (img) {
  19864. // Getting height map data
  19865. var canvas = document.createElement("canvas");
  19866. var context = canvas.getContext("2d");
  19867. var heightMapWidth = img.width;
  19868. var heightMapHeight = img.height;
  19869. canvas.width = heightMapWidth;
  19870. canvas.height = heightMapHeight;
  19871. context.drawImage(img, 0, 0);
  19872. // Create VertexData from map data
  19873. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  19874. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  19875. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  19876. //execute success callback, if set
  19877. if (onSuccess) {
  19878. onSuccess(_this);
  19879. }
  19880. };
  19881. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  19882. return this;
  19883. };
  19884. /**
  19885. * Modifies the mesh geometry according to a displacementMap buffer.
  19886. * 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.
  19887. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  19888. * This method returns nothing.
  19889. * 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.
  19890. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  19891. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  19892. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  19893. * The parameter `uvScale` is an optional vector2 used to scale UV.
  19894. *
  19895. * Returns the Mesh.
  19896. */
  19897. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  19898. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  19899. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  19900. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  19901. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  19902. return this;
  19903. }
  19904. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19905. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19906. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  19907. var position = BABYLON.Vector3.Zero();
  19908. var normal = BABYLON.Vector3.Zero();
  19909. var uv = BABYLON.Vector2.Zero();
  19910. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  19911. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  19912. for (var index = 0; index < positions.length; index += 3) {
  19913. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  19914. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  19915. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  19916. // Compute height
  19917. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  19918. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  19919. var pos = (u + v * heightMapWidth) * 4;
  19920. var r = buffer[pos] / 255.0;
  19921. var g = buffer[pos + 1] / 255.0;
  19922. var b = buffer[pos + 2] / 255.0;
  19923. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  19924. normal.normalize();
  19925. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  19926. position = position.add(normal);
  19927. position.toArray(positions, index);
  19928. }
  19929. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  19930. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  19931. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  19932. return this;
  19933. };
  19934. /**
  19935. * Modify the mesh to get a flat shading rendering.
  19936. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  19937. * This method returns the Mesh.
  19938. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  19939. */
  19940. Mesh.prototype.convertToFlatShadedMesh = function () {
  19941. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  19942. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  19943. var kinds = this.getVerticesDataKinds();
  19944. var vbs = [];
  19945. var data = [];
  19946. var newdata = [];
  19947. var updatableNormals = false;
  19948. var kindIndex;
  19949. var kind;
  19950. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19951. kind = kinds[kindIndex];
  19952. var vertexBuffer = this.getVertexBuffer(kind);
  19953. if (kind === BABYLON.VertexBuffer.NormalKind) {
  19954. updatableNormals = vertexBuffer.isUpdatable();
  19955. kinds.splice(kindIndex, 1);
  19956. kindIndex--;
  19957. continue;
  19958. }
  19959. vbs[kind] = vertexBuffer;
  19960. data[kind] = vbs[kind].getData();
  19961. newdata[kind] = [];
  19962. }
  19963. // Save previous submeshes
  19964. var previousSubmeshes = this.subMeshes.slice(0);
  19965. var indices = this.getIndices();
  19966. var totalIndices = this.getTotalIndices();
  19967. // Generating unique vertices per face
  19968. var index;
  19969. for (index = 0; index < totalIndices; index++) {
  19970. var vertexIndex = indices[index];
  19971. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19972. kind = kinds[kindIndex];
  19973. var stride = vbs[kind].getStrideSize();
  19974. for (var offset = 0; offset < stride; offset++) {
  19975. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  19976. }
  19977. }
  19978. }
  19979. // Updating faces & normal
  19980. var normals = [];
  19981. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  19982. for (index = 0; index < totalIndices; index += 3) {
  19983. indices[index] = index;
  19984. indices[index + 1] = index + 1;
  19985. indices[index + 2] = index + 2;
  19986. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  19987. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  19988. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  19989. var p1p2 = p1.subtract(p2);
  19990. var p3p2 = p3.subtract(p2);
  19991. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  19992. // Store same normals for every vertex
  19993. for (var localIndex = 0; localIndex < 3; localIndex++) {
  19994. normals.push(normal.x);
  19995. normals.push(normal.y);
  19996. normals.push(normal.z);
  19997. }
  19998. }
  19999. this.setIndices(indices);
  20000. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  20001. // Updating vertex buffers
  20002. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20003. kind = kinds[kindIndex];
  20004. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  20005. }
  20006. // Updating submeshes
  20007. this.releaseSubMeshes();
  20008. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  20009. var previousOne = previousSubmeshes[submeshIndex];
  20010. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  20011. }
  20012. this.synchronizeInstances();
  20013. return this;
  20014. };
  20015. /**
  20016. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  20017. * In other words, more vertices, no more indices and a single bigger VBO.
  20018. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  20019. * Returns the Mesh.
  20020. */
  20021. Mesh.prototype.convertToUnIndexedMesh = function () {
  20022. /// <summary>Remove indices by unfolding faces into buffers</summary>
  20023. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  20024. var kinds = this.getVerticesDataKinds();
  20025. var vbs = [];
  20026. var data = [];
  20027. var newdata = [];
  20028. var updatableNormals = false;
  20029. var kindIndex;
  20030. var kind;
  20031. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20032. kind = kinds[kindIndex];
  20033. var vertexBuffer = this.getVertexBuffer(kind);
  20034. vbs[kind] = vertexBuffer;
  20035. data[kind] = vbs[kind].getData();
  20036. newdata[kind] = [];
  20037. }
  20038. // Save previous submeshes
  20039. var previousSubmeshes = this.subMeshes.slice(0);
  20040. var indices = this.getIndices();
  20041. var totalIndices = this.getTotalIndices();
  20042. // Generating unique vertices per face
  20043. var index;
  20044. for (index = 0; index < totalIndices; index++) {
  20045. var vertexIndex = indices[index];
  20046. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20047. kind = kinds[kindIndex];
  20048. var stride = vbs[kind].getStrideSize();
  20049. for (var offset = 0; offset < stride; offset++) {
  20050. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  20051. }
  20052. }
  20053. }
  20054. // Updating indices
  20055. for (index = 0; index < totalIndices; index += 3) {
  20056. indices[index] = index;
  20057. indices[index + 1] = index + 1;
  20058. indices[index + 2] = index + 2;
  20059. }
  20060. this.setIndices(indices);
  20061. // Updating vertex buffers
  20062. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20063. kind = kinds[kindIndex];
  20064. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  20065. }
  20066. // Updating submeshes
  20067. this.releaseSubMeshes();
  20068. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  20069. var previousOne = previousSubmeshes[submeshIndex];
  20070. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  20071. }
  20072. this._unIndexed = true;
  20073. this.synchronizeInstances();
  20074. return this;
  20075. };
  20076. /**
  20077. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  20078. * This method returns the Mesh.
  20079. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  20080. */
  20081. Mesh.prototype.flipFaces = function (flipNormals) {
  20082. if (flipNormals === void 0) { flipNormals = false; }
  20083. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  20084. var i;
  20085. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20086. for (i = 0; i < vertex_data.normals.length; i++) {
  20087. vertex_data.normals[i] *= -1;
  20088. }
  20089. }
  20090. var temp;
  20091. for (i = 0; i < vertex_data.indices.length; i += 3) {
  20092. // reassign indices
  20093. temp = vertex_data.indices[i + 1];
  20094. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  20095. vertex_data.indices[i + 2] = temp;
  20096. }
  20097. vertex_data.applyToMesh(this);
  20098. return this;
  20099. };
  20100. // Instances
  20101. /**
  20102. * Creates a new InstancedMesh object from the mesh model.
  20103. * An instance shares the same properties and the same material than its model.
  20104. * Only these properties of each instance can then be set individually :
  20105. * - position
  20106. * - rotation
  20107. * - rotationQuaternion
  20108. * - setPivotMatrix
  20109. * - scaling
  20110. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  20111. * Warning : this method is not supported for Line mesh and LineSystem
  20112. */
  20113. Mesh.prototype.createInstance = function (name) {
  20114. return new BABYLON.InstancedMesh(name, this);
  20115. };
  20116. /**
  20117. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  20118. * After this call, all the mesh instances have the same submeshes than the current mesh.
  20119. * This method returns the Mesh.
  20120. */
  20121. Mesh.prototype.synchronizeInstances = function () {
  20122. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  20123. var instance = this.instances[instanceIndex];
  20124. instance._syncSubMeshes();
  20125. }
  20126. return this;
  20127. };
  20128. /**
  20129. * Simplify the mesh according to the given array of settings.
  20130. * Function will return immediately and will simplify async. It returns the Mesh.
  20131. * @param settings a collection of simplification settings.
  20132. * @param parallelProcessing should all levels calculate parallel or one after the other.
  20133. * @param type the type of simplification to run.
  20134. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  20135. */
  20136. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  20137. if (parallelProcessing === void 0) { parallelProcessing = true; }
  20138. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  20139. this.getScene().simplificationQueue.addTask({
  20140. settings: settings,
  20141. parallelProcessing: parallelProcessing,
  20142. mesh: this,
  20143. simplificationType: simplificationType,
  20144. successCallback: successCallback
  20145. });
  20146. return this;
  20147. };
  20148. /**
  20149. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  20150. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  20151. * This should be used together with the simplification to avoid disappearing triangles.
  20152. * Returns the Mesh.
  20153. * @param successCallback an optional success callback to be called after the optimization finished.
  20154. */
  20155. Mesh.prototype.optimizeIndices = function (successCallback) {
  20156. var _this = this;
  20157. var indices = this.getIndices();
  20158. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20159. var vectorPositions = [];
  20160. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  20161. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  20162. }
  20163. var dupes = [];
  20164. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  20165. var realPos = vectorPositions.length - 1 - iteration;
  20166. var testedPosition = vectorPositions[realPos];
  20167. for (var j = 0; j < realPos; ++j) {
  20168. var againstPosition = vectorPositions[j];
  20169. if (testedPosition.equals(againstPosition)) {
  20170. dupes[realPos] = j;
  20171. break;
  20172. }
  20173. }
  20174. }, function () {
  20175. for (var i = 0; i < indices.length; ++i) {
  20176. indices[i] = dupes[indices[i]] || indices[i];
  20177. }
  20178. //indices are now reordered
  20179. var originalSubMeshes = _this.subMeshes.slice(0);
  20180. _this.setIndices(indices);
  20181. _this.subMeshes = originalSubMeshes;
  20182. if (successCallback) {
  20183. successCallback(_this);
  20184. }
  20185. });
  20186. return this;
  20187. };
  20188. Mesh.prototype.serialize = function (serializationObject) {
  20189. serializationObject.name = this.name;
  20190. serializationObject.id = this.id;
  20191. serializationObject.type = this.getClassName();
  20192. if (BABYLON.Tags.HasTags(this)) {
  20193. serializationObject.tags = BABYLON.Tags.GetTags(this);
  20194. }
  20195. serializationObject.position = this.position.asArray();
  20196. if (this.rotationQuaternion) {
  20197. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  20198. }
  20199. else if (this.rotation) {
  20200. serializationObject.rotation = this.rotation.asArray();
  20201. }
  20202. serializationObject.scaling = this.scaling.asArray();
  20203. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  20204. serializationObject.isEnabled = this.isEnabled();
  20205. serializationObject.isVisible = this.isVisible;
  20206. serializationObject.infiniteDistance = this.infiniteDistance;
  20207. serializationObject.pickable = this.isPickable;
  20208. serializationObject.receiveShadows = this.receiveShadows;
  20209. serializationObject.billboardMode = this.billboardMode;
  20210. serializationObject.visibility = this.visibility;
  20211. serializationObject.checkCollisions = this.checkCollisions;
  20212. serializationObject.isBlocker = this.isBlocker;
  20213. // Parent
  20214. if (this.parent) {
  20215. serializationObject.parentId = this.parent.id;
  20216. }
  20217. // Geometry
  20218. var geometry = this._geometry;
  20219. if (geometry) {
  20220. var geometryId = geometry.id;
  20221. serializationObject.geometryId = geometryId;
  20222. // SubMeshes
  20223. serializationObject.subMeshes = [];
  20224. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20225. var subMesh = this.subMeshes[subIndex];
  20226. serializationObject.subMeshes.push({
  20227. materialIndex: subMesh.materialIndex,
  20228. verticesStart: subMesh.verticesStart,
  20229. verticesCount: subMesh.verticesCount,
  20230. indexStart: subMesh.indexStart,
  20231. indexCount: subMesh.indexCount
  20232. });
  20233. }
  20234. }
  20235. // Material
  20236. if (this.material) {
  20237. serializationObject.materialId = this.material.id;
  20238. }
  20239. else {
  20240. this.material = null;
  20241. }
  20242. // Morph targets
  20243. if (this.morphTargetManager) {
  20244. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  20245. }
  20246. // Skeleton
  20247. if (this.skeleton) {
  20248. serializationObject.skeletonId = this.skeleton.id;
  20249. }
  20250. // Physics
  20251. //TODO implement correct serialization for physics impostors.
  20252. if (this.getPhysicsImpostor()) {
  20253. var impostor = this.getPhysicsImpostor();
  20254. serializationObject.physicsMass = impostor.getParam("mass");
  20255. serializationObject.physicsFriction = impostor.getParam("friction");
  20256. serializationObject.physicsRestitution = impostor.getParam("mass");
  20257. serializationObject.physicsImpostor = this.getPhysicsImpostor().type;
  20258. }
  20259. // Metadata
  20260. if (this.metadata) {
  20261. serializationObject.metadata = this.metadata;
  20262. }
  20263. // Instances
  20264. serializationObject.instances = [];
  20265. for (var index = 0; index < this.instances.length; index++) {
  20266. var instance = this.instances[index];
  20267. var serializationInstance = {
  20268. name: instance.name,
  20269. position: instance.position.asArray(),
  20270. scaling: instance.scaling.asArray()
  20271. };
  20272. if (instance.rotationQuaternion) {
  20273. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  20274. }
  20275. else if (instance.rotation) {
  20276. serializationInstance.rotation = instance.rotation.asArray();
  20277. }
  20278. serializationObject.instances.push(serializationInstance);
  20279. // Animations
  20280. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  20281. serializationInstance.ranges = instance.serializeAnimationRanges();
  20282. }
  20283. //
  20284. // Animations
  20285. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  20286. serializationObject.ranges = this.serializeAnimationRanges();
  20287. // Layer mask
  20288. serializationObject.layerMask = this.layerMask;
  20289. // Alpha
  20290. serializationObject.alphaIndex = this.alphaIndex;
  20291. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  20292. // Overlay
  20293. serializationObject.overlayAlpha = this.overlayAlpha;
  20294. serializationObject.overlayColor = this.overlayColor.asArray();
  20295. serializationObject.renderOverlay = this.renderOverlay;
  20296. // Fog
  20297. serializationObject.applyFog = this.applyFog;
  20298. // Action Manager
  20299. if (this.actionManager) {
  20300. serializationObject.actions = this.actionManager.serialize(this.name);
  20301. }
  20302. };
  20303. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  20304. if (!this.geometry) {
  20305. return;
  20306. }
  20307. this._markSubMeshesAsAttributesDirty();
  20308. if (this._morphTargetManager && this._morphTargetManager.vertexCount) {
  20309. if (this._morphTargetManager.vertexCount !== this.getTotalVertices()) {
  20310. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  20311. this.morphTargetManager = undefined;
  20312. return;
  20313. }
  20314. for (var index = 0; index < this.morphTargetManager.numInfluencers; index++) {
  20315. var morphTarget = this.morphTargetManager.getActiveTarget(index);
  20316. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, morphTarget.getPositions(), false, 3);
  20317. if (morphTarget.hasNormals) {
  20318. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, morphTarget.getNormals(), false, 3);
  20319. }
  20320. if (morphTarget.hasTangents) {
  20321. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, morphTarget.getTangents(), false, 3);
  20322. }
  20323. }
  20324. }
  20325. else {
  20326. var index = 0;
  20327. // Positions
  20328. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  20329. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  20330. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  20331. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  20332. }
  20333. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  20334. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  20335. }
  20336. index++;
  20337. }
  20338. }
  20339. };
  20340. // Statics
  20341. /**
  20342. * Returns a new Mesh object what is a deep copy of the passed mesh.
  20343. * The parameter `parsedMesh` is the mesh to be copied.
  20344. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  20345. */
  20346. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  20347. var mesh;
  20348. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  20349. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  20350. }
  20351. else {
  20352. mesh = new Mesh(parsedMesh.name, scene);
  20353. }
  20354. mesh.id = parsedMesh.id;
  20355. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  20356. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  20357. if (parsedMesh.metadata !== undefined) {
  20358. mesh.metadata = parsedMesh.metadata;
  20359. }
  20360. if (parsedMesh.rotationQuaternion) {
  20361. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  20362. }
  20363. else if (parsedMesh.rotation) {
  20364. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  20365. }
  20366. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  20367. if (parsedMesh.localMatrix) {
  20368. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  20369. }
  20370. else if (parsedMesh.pivotMatrix) {
  20371. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  20372. }
  20373. mesh.setEnabled(parsedMesh.isEnabled);
  20374. mesh.isVisible = parsedMesh.isVisible;
  20375. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  20376. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  20377. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  20378. if (parsedMesh.applyFog !== undefined) {
  20379. mesh.applyFog = parsedMesh.applyFog;
  20380. }
  20381. if (parsedMesh.pickable !== undefined) {
  20382. mesh.isPickable = parsedMesh.pickable;
  20383. }
  20384. if (parsedMesh.alphaIndex !== undefined) {
  20385. mesh.alphaIndex = parsedMesh.alphaIndex;
  20386. }
  20387. mesh.receiveShadows = parsedMesh.receiveShadows;
  20388. mesh.billboardMode = parsedMesh.billboardMode;
  20389. if (parsedMesh.visibility !== undefined) {
  20390. mesh.visibility = parsedMesh.visibility;
  20391. }
  20392. mesh.checkCollisions = parsedMesh.checkCollisions;
  20393. if (parsedMesh.isBlocker !== undefined) {
  20394. mesh.isBlocker = parsedMesh.isBlocker;
  20395. }
  20396. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  20397. // freezeWorldMatrix
  20398. if (parsedMesh.freezeWorldMatrix) {
  20399. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  20400. }
  20401. // Parent
  20402. if (parsedMesh.parentId) {
  20403. mesh._waitingParentId = parsedMesh.parentId;
  20404. }
  20405. // Actions
  20406. if (parsedMesh.actions !== undefined) {
  20407. mesh._waitingActions = parsedMesh.actions;
  20408. }
  20409. // Overlay
  20410. if (parsedMesh.overlayAlpha !== undefined) {
  20411. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  20412. }
  20413. if (parsedMesh.overlayColor !== undefined) {
  20414. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  20415. }
  20416. if (parsedMesh.renderOverlay !== undefined) {
  20417. mesh.renderOverlay = parsedMesh.renderOverlay;
  20418. }
  20419. // Geometry
  20420. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  20421. if (parsedMesh.delayLoadingFile) {
  20422. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20423. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  20424. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  20425. if (parsedMesh._binaryInfo) {
  20426. mesh._binaryInfo = parsedMesh._binaryInfo;
  20427. }
  20428. mesh._delayInfo = [];
  20429. if (parsedMesh.hasUVs) {
  20430. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  20431. }
  20432. if (parsedMesh.hasUVs2) {
  20433. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  20434. }
  20435. if (parsedMesh.hasUVs3) {
  20436. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  20437. }
  20438. if (parsedMesh.hasUVs4) {
  20439. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  20440. }
  20441. if (parsedMesh.hasUVs5) {
  20442. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  20443. }
  20444. if (parsedMesh.hasUVs6) {
  20445. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  20446. }
  20447. if (parsedMesh.hasColors) {
  20448. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  20449. }
  20450. if (parsedMesh.hasMatricesIndices) {
  20451. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  20452. }
  20453. if (parsedMesh.hasMatricesWeights) {
  20454. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  20455. }
  20456. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  20457. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  20458. mesh._checkDelayState();
  20459. }
  20460. }
  20461. else {
  20462. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  20463. }
  20464. // Material
  20465. if (parsedMesh.materialId) {
  20466. mesh.setMaterialByID(parsedMesh.materialId);
  20467. }
  20468. else {
  20469. mesh.material = null;
  20470. }
  20471. // Morph targets
  20472. if (parsedMesh.morphTargetManagerId > -1) {
  20473. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  20474. }
  20475. // Skeleton
  20476. if (parsedMesh.skeletonId > -1) {
  20477. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  20478. if (parsedMesh.numBoneInfluencers) {
  20479. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  20480. }
  20481. }
  20482. // Animations
  20483. if (parsedMesh.animations) {
  20484. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  20485. var parsedAnimation = parsedMesh.animations[animationIndex];
  20486. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20487. }
  20488. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  20489. }
  20490. if (parsedMesh.autoAnimate) {
  20491. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  20492. }
  20493. // Layer Mask
  20494. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  20495. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  20496. }
  20497. else {
  20498. mesh.layerMask = 0x0FFFFFFF;
  20499. }
  20500. // Physics
  20501. if (parsedMesh.physicsImpostor) {
  20502. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  20503. mass: parsedMesh.physicsMass,
  20504. friction: parsedMesh.physicsFriction,
  20505. restitution: parsedMesh.physicsRestitution
  20506. }, scene);
  20507. }
  20508. // Instances
  20509. if (parsedMesh.instances) {
  20510. for (var index = 0; index < parsedMesh.instances.length; index++) {
  20511. var parsedInstance = parsedMesh.instances[index];
  20512. var instance = mesh.createInstance(parsedInstance.name);
  20513. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  20514. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  20515. if (parsedInstance.parentId) {
  20516. instance._waitingParentId = parsedInstance.parentId;
  20517. }
  20518. if (parsedInstance.rotationQuaternion) {
  20519. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  20520. }
  20521. else if (parsedInstance.rotation) {
  20522. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  20523. }
  20524. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  20525. instance.checkCollisions = mesh.checkCollisions;
  20526. if (parsedMesh.animations) {
  20527. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  20528. parsedAnimation = parsedMesh.animations[animationIndex];
  20529. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20530. }
  20531. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  20532. }
  20533. }
  20534. }
  20535. return mesh;
  20536. };
  20537. /**
  20538. * Creates a ribbon mesh.
  20539. * Please consider using the same method from the MeshBuilder class instead.
  20540. * 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.
  20541. *
  20542. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  20543. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  20544. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  20545. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  20546. * 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.
  20547. * 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.
  20548. * 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
  20549. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20550. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20551. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20552. */
  20553. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  20554. return BABYLON.MeshBuilder.CreateRibbon(name, {
  20555. pathArray: pathArray,
  20556. closeArray: closeArray,
  20557. closePath: closePath,
  20558. offset: offset,
  20559. updatable: updatable,
  20560. sideOrientation: sideOrientation,
  20561. instance: instance
  20562. }, scene);
  20563. };
  20564. /**
  20565. * Creates a plane polygonal mesh. By default, this is a disc.
  20566. * Please consider using the same method from the MeshBuilder class instead.
  20567. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  20568. * 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.
  20569. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20570. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20571. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20572. */
  20573. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  20574. var options = {
  20575. radius: radius,
  20576. tessellation: tessellation,
  20577. sideOrientation: sideOrientation,
  20578. updatable: updatable
  20579. };
  20580. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  20581. };
  20582. /**
  20583. * Creates a box mesh.
  20584. * Please consider using the same method from the MeshBuilder class instead.
  20585. * The parameter `size` sets the size (float) of each box side (default 1).
  20586. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20587. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20588. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20589. */
  20590. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  20591. var options = {
  20592. size: size,
  20593. sideOrientation: sideOrientation,
  20594. updatable: updatable
  20595. };
  20596. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  20597. };
  20598. /**
  20599. * Creates a sphere mesh.
  20600. * Please consider using the same method from the MeshBuilder class instead.
  20601. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  20602. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  20603. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20604. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20605. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20606. */
  20607. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  20608. var options = {
  20609. segments: segments,
  20610. diameterX: diameter,
  20611. diameterY: diameter,
  20612. diameterZ: diameter,
  20613. sideOrientation: sideOrientation,
  20614. updatable: updatable
  20615. };
  20616. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  20617. };
  20618. /**
  20619. * Creates a cylinder or a cone mesh.
  20620. * Please consider using the same method from the MeshBuilder class instead.
  20621. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  20622. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  20623. * 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.
  20624. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  20625. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  20626. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20627. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20628. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20629. */
  20630. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  20631. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  20632. if (scene !== undefined) {
  20633. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  20634. updatable = scene;
  20635. }
  20636. scene = subdivisions;
  20637. subdivisions = 1;
  20638. }
  20639. var options = {
  20640. height: height,
  20641. diameterTop: diameterTop,
  20642. diameterBottom: diameterBottom,
  20643. tessellation: tessellation,
  20644. subdivisions: subdivisions,
  20645. sideOrientation: sideOrientation,
  20646. updatable: updatable
  20647. };
  20648. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  20649. };
  20650. // Torus (Code from SharpDX.org)
  20651. /**
  20652. * Creates a torus mesh.
  20653. * Please consider using the same method from the MeshBuilder class instead.
  20654. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  20655. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  20656. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  20657. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20658. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20659. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20660. */
  20661. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  20662. var options = {
  20663. diameter: diameter,
  20664. thickness: thickness,
  20665. tessellation: tessellation,
  20666. sideOrientation: sideOrientation,
  20667. updatable: updatable
  20668. };
  20669. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  20670. };
  20671. /**
  20672. * Creates a torus knot mesh.
  20673. * Please consider using the same method from the MeshBuilder class instead.
  20674. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  20675. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  20676. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  20677. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  20678. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20679. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20680. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20681. */
  20682. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  20683. var options = {
  20684. radius: radius,
  20685. tube: tube,
  20686. radialSegments: radialSegments,
  20687. tubularSegments: tubularSegments,
  20688. p: p,
  20689. q: q,
  20690. sideOrientation: sideOrientation,
  20691. updatable: updatable
  20692. };
  20693. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  20694. };
  20695. /**
  20696. * Creates a line mesh.
  20697. * Please consider using the same method from the MeshBuilder class instead.
  20698. * 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.
  20699. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  20700. * The parameter `points` is an array successive Vector3.
  20701. * 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
  20702. * When updating an instance, remember that only point positions can change, not the number of points.
  20703. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20704. */
  20705. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  20706. var options = {
  20707. points: points,
  20708. updatable: updatable,
  20709. instance: instance
  20710. };
  20711. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  20712. };
  20713. /**
  20714. * Creates a dashed line mesh.
  20715. * Please consider using the same method from the MeshBuilder class instead.
  20716. * 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.
  20717. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  20718. * The parameter `points` is an array successive Vector3.
  20719. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  20720. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  20721. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  20722. * 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
  20723. * When updating an instance, remember that only point positions can change, not the number of points.
  20724. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20725. */
  20726. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  20727. var options = {
  20728. points: points,
  20729. dashSize: dashSize,
  20730. gapSize: gapSize,
  20731. dashNb: dashNb,
  20732. updatable: updatable,
  20733. instance: instance
  20734. };
  20735. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  20736. };
  20737. /**
  20738. * Creates an extruded shape mesh.
  20739. * 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.
  20740. * Please consider using the same method from the MeshBuilder class instead.
  20741. *
  20742. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  20743. * 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
  20744. * extruded along the Z axis.
  20745. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  20746. * 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.
  20747. * The parameter `scale` (float, default 1) is the value to scale the shape.
  20748. * 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
  20749. * 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
  20750. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  20751. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20752. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20753. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20754. */
  20755. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  20756. var options = {
  20757. shape: shape,
  20758. path: path,
  20759. scale: scale,
  20760. rotation: rotation,
  20761. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  20762. sideOrientation: sideOrientation,
  20763. instance: instance,
  20764. updatable: updatable
  20765. };
  20766. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  20767. };
  20768. /**
  20769. * Creates an custom extruded shape mesh.
  20770. * 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.
  20771. * Please consider using the same method from the MeshBuilder class instead.
  20772. *
  20773. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  20774. * 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
  20775. * extruded along the Z axis.
  20776. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  20777. * 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
  20778. * and the distance of this point from the begining of the path :
  20779. * ```javascript
  20780. * var rotationFunction = function(i, distance) {
  20781. * // do things
  20782. * return rotationValue; }
  20783. * ```
  20784. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  20785. * 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
  20786. * and the distance of this point from the begining of the path :
  20787. * ```javascript
  20788. * var scaleFunction = function(i, distance) {
  20789. * // do things
  20790. * return scaleValue;}
  20791. * ```
  20792. * It must returns a float value that will be the scale value applied to the shape on each path point.
  20793. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  20794. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  20795. * 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
  20796. * 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
  20797. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  20798. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20799. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20800. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20801. */
  20802. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  20803. var options = {
  20804. shape: shape,
  20805. path: path,
  20806. scaleFunction: scaleFunction,
  20807. rotationFunction: rotationFunction,
  20808. ribbonCloseArray: ribbonCloseArray,
  20809. ribbonClosePath: ribbonClosePath,
  20810. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  20811. sideOrientation: sideOrientation,
  20812. instance: instance,
  20813. updatable: updatable
  20814. };
  20815. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  20816. };
  20817. /**
  20818. * Creates lathe mesh.
  20819. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  20820. * Please consider using the same method from the MeshBuilder class instead.
  20821. * 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
  20822. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  20823. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  20824. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  20825. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20826. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20827. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20828. */
  20829. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  20830. var options = {
  20831. shape: shape,
  20832. radius: radius,
  20833. tessellation: tessellation,
  20834. sideOrientation: sideOrientation,
  20835. updatable: updatable
  20836. };
  20837. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  20838. };
  20839. /**
  20840. * Creates a plane mesh.
  20841. * Please consider using the same method from the MeshBuilder class instead.
  20842. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  20843. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20844. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20845. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20846. */
  20847. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  20848. var options = {
  20849. size: size,
  20850. width: size,
  20851. height: size,
  20852. sideOrientation: sideOrientation,
  20853. updatable: updatable
  20854. };
  20855. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  20856. };
  20857. /**
  20858. * Creates a ground mesh.
  20859. * Please consider using the same method from the MeshBuilder class instead.
  20860. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  20861. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  20862. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20863. */
  20864. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  20865. var options = {
  20866. width: width,
  20867. height: height,
  20868. subdivisions: subdivisions,
  20869. updatable: updatable
  20870. };
  20871. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  20872. };
  20873. /**
  20874. * Creates a tiled ground mesh.
  20875. * Please consider using the same method from the MeshBuilder class instead.
  20876. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  20877. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  20878. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  20879. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  20880. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  20881. * numbers of subdivisions on the ground width and height of each tile.
  20882. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20883. */
  20884. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  20885. var options = {
  20886. xmin: xmin,
  20887. zmin: zmin,
  20888. xmax: xmax,
  20889. zmax: zmax,
  20890. subdivisions: subdivisions,
  20891. precision: precision,
  20892. updatable: updatable
  20893. };
  20894. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  20895. };
  20896. /**
  20897. * Creates a ground mesh from a height map.
  20898. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  20899. * Please consider using the same method from the MeshBuilder class instead.
  20900. * The parameter `url` sets the URL of the height map image resource.
  20901. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  20902. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  20903. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  20904. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  20905. * 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).
  20906. * This function is passed the newly built mesh :
  20907. * ```javascript
  20908. * function(mesh) { // do things
  20909. * return; }
  20910. * ```
  20911. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20912. */
  20913. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  20914. var options = {
  20915. width: width,
  20916. height: height,
  20917. subdivisions: subdivisions,
  20918. minHeight: minHeight,
  20919. maxHeight: maxHeight,
  20920. updatable: updatable,
  20921. onReady: onReady
  20922. };
  20923. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  20924. };
  20925. /**
  20926. * Creates a tube mesh.
  20927. * 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.
  20928. * Please consider using the same method from the MeshBuilder class instead.
  20929. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  20930. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  20931. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  20932. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  20933. * 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.
  20934. * It must return a radius value (positive float) :
  20935. * ```javascript
  20936. * var radiusFunction = function(i, distance) {
  20937. * // do things
  20938. * return radius; }
  20939. * ```
  20940. * 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
  20941. * 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
  20942. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20943. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20944. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20945. */
  20946. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  20947. var options = {
  20948. path: path,
  20949. radius: radius,
  20950. tessellation: tessellation,
  20951. radiusFunction: radiusFunction,
  20952. arc: 1,
  20953. cap: cap,
  20954. updatable: updatable,
  20955. sideOrientation: sideOrientation,
  20956. instance: instance
  20957. };
  20958. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  20959. };
  20960. /**
  20961. * Creates a polyhedron mesh.
  20962. * Please consider using the same method from the MeshBuilder class instead.
  20963. * 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
  20964. * to choose the wanted type.
  20965. * The parameter `size` (positive float, default 1) sets the polygon size.
  20966. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  20967. * 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`.
  20968. * 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
  20969. * 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)`).
  20970. * 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
  20971. * 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.
  20972. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20973. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20974. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20975. */
  20976. Mesh.CreatePolyhedron = function (name, options, scene) {
  20977. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  20978. };
  20979. /**
  20980. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  20981. * Please consider using the same method from the MeshBuilder class instead.
  20982. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  20983. * 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`).
  20984. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  20985. * 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.
  20986. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20987. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20988. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20989. */
  20990. Mesh.CreateIcoSphere = function (name, options, scene) {
  20991. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  20992. };
  20993. /**
  20994. * Creates a decal mesh.
  20995. * Please consider using the same method from the MeshBuilder class instead.
  20996. * 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.
  20997. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  20998. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  20999. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  21000. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  21001. */
  21002. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  21003. var options = {
  21004. position: position,
  21005. normal: normal,
  21006. size: size,
  21007. angle: angle
  21008. };
  21009. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  21010. };
  21011. // Skeletons
  21012. /**
  21013. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  21014. */
  21015. Mesh.prototype.setPositionsForCPUSkinning = function () {
  21016. var source;
  21017. if (!this._sourcePositions) {
  21018. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21019. this._sourcePositions = new Float32Array(source);
  21020. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  21021. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  21022. }
  21023. }
  21024. return this._sourcePositions;
  21025. };
  21026. /**
  21027. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  21028. */
  21029. Mesh.prototype.setNormalsForCPUSkinning = function () {
  21030. var source;
  21031. if (!this._sourceNormals) {
  21032. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21033. this._sourceNormals = new Float32Array(source);
  21034. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  21035. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  21036. }
  21037. }
  21038. return this._sourceNormals;
  21039. };
  21040. /**
  21041. * Updates the vertex buffer by applying transformation from the bones.
  21042. * Returns the Mesh.
  21043. *
  21044. * @param {skeleton} skeleton to apply
  21045. */
  21046. Mesh.prototype.applySkeleton = function (skeleton) {
  21047. if (!this.geometry) {
  21048. return this;
  21049. }
  21050. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  21051. return this;
  21052. }
  21053. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  21054. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  21055. return this;
  21056. }
  21057. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21058. return this;
  21059. }
  21060. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  21061. return this;
  21062. }
  21063. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  21064. return this;
  21065. }
  21066. if (!this._sourcePositions) {
  21067. var submeshes = this.subMeshes.slice();
  21068. this.setPositionsForCPUSkinning();
  21069. this.subMeshes = submeshes;
  21070. }
  21071. if (!this._sourceNormals) {
  21072. this.setNormalsForCPUSkinning();
  21073. }
  21074. // positionsData checks for not being Float32Array will only pass at most once
  21075. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21076. if (!(positionsData instanceof Float32Array)) {
  21077. positionsData = new Float32Array(positionsData);
  21078. }
  21079. // normalsData checks for not being Float32Array will only pass at most once
  21080. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21081. if (!(normalsData instanceof Float32Array)) {
  21082. normalsData = new Float32Array(normalsData);
  21083. }
  21084. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  21085. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  21086. var needExtras = this.numBoneInfluencers > 4;
  21087. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  21088. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  21089. var skeletonMatrices = skeleton.getTransformMatrices(this);
  21090. var tempVector3 = BABYLON.Vector3.Zero();
  21091. var finalMatrix = new BABYLON.Matrix();
  21092. var tempMatrix = new BABYLON.Matrix();
  21093. var matWeightIdx = 0;
  21094. var inf;
  21095. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  21096. var weight;
  21097. for (inf = 0; inf < 4; inf++) {
  21098. weight = matricesWeightsData[matWeightIdx + inf];
  21099. if (weight > 0) {
  21100. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  21101. finalMatrix.addToSelf(tempMatrix);
  21102. }
  21103. else
  21104. break;
  21105. }
  21106. if (needExtras) {
  21107. for (inf = 0; inf < 4; inf++) {
  21108. weight = matricesWeightsExtraData[matWeightIdx + inf];
  21109. if (weight > 0) {
  21110. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  21111. finalMatrix.addToSelf(tempMatrix);
  21112. }
  21113. else
  21114. break;
  21115. }
  21116. }
  21117. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  21118. tempVector3.toArray(positionsData, index);
  21119. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  21120. tempVector3.toArray(normalsData, index);
  21121. finalMatrix.reset();
  21122. }
  21123. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  21124. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  21125. return this;
  21126. };
  21127. // Tools
  21128. /**
  21129. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  21130. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  21131. */
  21132. Mesh.MinMax = function (meshes) {
  21133. var minVector = null;
  21134. var maxVector = null;
  21135. meshes.forEach(function (mesh, index, array) {
  21136. var boundingBox = mesh.getBoundingInfo().boundingBox;
  21137. if (!minVector) {
  21138. minVector = boundingBox.minimumWorld;
  21139. maxVector = boundingBox.maximumWorld;
  21140. }
  21141. else {
  21142. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  21143. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  21144. }
  21145. });
  21146. return {
  21147. min: minVector,
  21148. max: maxVector
  21149. };
  21150. };
  21151. /**
  21152. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  21153. */
  21154. Mesh.Center = function (meshesOrMinMaxVector) {
  21155. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  21156. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  21157. };
  21158. /**
  21159. * Merge the array of meshes into a single mesh for performance reasons.
  21160. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  21161. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  21162. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  21163. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  21164. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  21165. */
  21166. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  21167. if (disposeSource === void 0) { disposeSource = true; }
  21168. var index;
  21169. if (!allow32BitsIndices) {
  21170. var totalVertices = 0;
  21171. // Counting vertices
  21172. for (index = 0; index < meshes.length; index++) {
  21173. if (meshes[index]) {
  21174. totalVertices += meshes[index].getTotalVertices();
  21175. if (totalVertices > 65536) {
  21176. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  21177. return null;
  21178. }
  21179. }
  21180. }
  21181. }
  21182. // Merge
  21183. var vertexData;
  21184. var otherVertexData;
  21185. var indiceArray = new Array();
  21186. var source;
  21187. for (index = 0; index < meshes.length; index++) {
  21188. if (meshes[index]) {
  21189. meshes[index].computeWorldMatrix(true);
  21190. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], false, true);
  21191. otherVertexData.transform(meshes[index].getWorldMatrix());
  21192. if (vertexData) {
  21193. vertexData.merge(otherVertexData);
  21194. }
  21195. else {
  21196. vertexData = otherVertexData;
  21197. source = meshes[index];
  21198. }
  21199. if (subdivideWithSubMeshes) {
  21200. indiceArray.push(meshes[index].getTotalIndices());
  21201. }
  21202. }
  21203. }
  21204. if (!meshSubclass) {
  21205. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  21206. }
  21207. vertexData.applyToMesh(meshSubclass);
  21208. // Setting properties
  21209. meshSubclass.material = source.material;
  21210. meshSubclass.checkCollisions = source.checkCollisions;
  21211. // Cleaning
  21212. if (disposeSource) {
  21213. for (index = 0; index < meshes.length; index++) {
  21214. if (meshes[index]) {
  21215. meshes[index].dispose();
  21216. }
  21217. }
  21218. }
  21219. // Subdivide
  21220. if (subdivideWithSubMeshes) {
  21221. //-- Suppresions du submesh global
  21222. meshSubclass.releaseSubMeshes();
  21223. index = 0;
  21224. var offset = 0;
  21225. //-- aplique la subdivision en fonction du tableau d'indices
  21226. while (index < indiceArray.length) {
  21227. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  21228. offset += indiceArray[index];
  21229. index++;
  21230. }
  21231. }
  21232. return meshSubclass;
  21233. };
  21234. return Mesh;
  21235. }(BABYLON.AbstractMesh));
  21236. // Consts
  21237. Mesh._FRONTSIDE = 0;
  21238. Mesh._BACKSIDE = 1;
  21239. Mesh._DOUBLESIDE = 2;
  21240. Mesh._DEFAULTSIDE = 0;
  21241. Mesh._NO_CAP = 0;
  21242. Mesh._CAP_START = 1;
  21243. Mesh._CAP_END = 2;
  21244. Mesh._CAP_ALL = 3;
  21245. BABYLON.Mesh = Mesh;
  21246. })(BABYLON || (BABYLON = {}));
  21247. //# sourceMappingURL=babylon.mesh.js.map
  21248. var BABYLON;
  21249. (function (BABYLON) {
  21250. var SubMesh = (function () {
  21251. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  21252. if (createBoundingBox === void 0) { createBoundingBox = true; }
  21253. this.materialIndex = materialIndex;
  21254. this.verticesStart = verticesStart;
  21255. this.verticesCount = verticesCount;
  21256. this.indexStart = indexStart;
  21257. this.indexCount = indexCount;
  21258. this._renderId = 0;
  21259. this._mesh = mesh;
  21260. this._renderingMesh = renderingMesh || mesh;
  21261. mesh.subMeshes.push(this);
  21262. this._trianglePlanes = [];
  21263. this._id = mesh.subMeshes.length - 1;
  21264. if (createBoundingBox) {
  21265. this.refreshBoundingInfo();
  21266. mesh.computeWorldMatrix(true);
  21267. }
  21268. }
  21269. Object.defineProperty(SubMesh.prototype, "effect", {
  21270. get: function () {
  21271. return this._materialEffect;
  21272. },
  21273. enumerable: true,
  21274. configurable: true
  21275. });
  21276. SubMesh.prototype.setEffect = function (effect, defines) {
  21277. if (this._materialEffect === effect) {
  21278. return;
  21279. }
  21280. this._materialDefines = defines;
  21281. this._materialEffect = effect;
  21282. };
  21283. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  21284. get: function () {
  21285. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  21286. },
  21287. enumerable: true,
  21288. configurable: true
  21289. });
  21290. /**
  21291. * Returns the submesh BoudingInfo object.
  21292. */
  21293. SubMesh.prototype.getBoundingInfo = function () {
  21294. if (this.IsGlobal) {
  21295. return this._mesh.getBoundingInfo();
  21296. }
  21297. return this._boundingInfo;
  21298. };
  21299. /**
  21300. * Sets the submesh BoundingInfo.
  21301. * Return the SubMesh.
  21302. */
  21303. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  21304. this._boundingInfo = boundingInfo;
  21305. return this;
  21306. };
  21307. /**
  21308. * Returns the mesh of the current submesh.
  21309. */
  21310. SubMesh.prototype.getMesh = function () {
  21311. return this._mesh;
  21312. };
  21313. /**
  21314. * Returns the rendering mesh of the submesh.
  21315. */
  21316. SubMesh.prototype.getRenderingMesh = function () {
  21317. return this._renderingMesh;
  21318. };
  21319. /**
  21320. * Returns the submesh material.
  21321. */
  21322. SubMesh.prototype.getMaterial = function () {
  21323. var rootMaterial = this._renderingMesh.material;
  21324. if (rootMaterial && rootMaterial.getSubMaterial) {
  21325. var multiMaterial = rootMaterial;
  21326. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  21327. if (this._currentMaterial !== effectiveMaterial) {
  21328. this._currentMaterial = effectiveMaterial;
  21329. if (this._materialDefines) {
  21330. this._materialDefines.markAllAsDirty();
  21331. }
  21332. }
  21333. return effectiveMaterial;
  21334. }
  21335. if (!rootMaterial) {
  21336. return this._mesh.getScene().defaultMaterial;
  21337. }
  21338. return rootMaterial;
  21339. };
  21340. // Methods
  21341. /**
  21342. * Sets a new updated BoundingInfo object to the submesh.
  21343. * Returns the SubMesh.
  21344. */
  21345. SubMesh.prototype.refreshBoundingInfo = function () {
  21346. this._lastColliderWorldVertices = null;
  21347. if (this.IsGlobal) {
  21348. return;
  21349. }
  21350. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21351. if (!data) {
  21352. this._boundingInfo = this._mesh._boundingInfo;
  21353. return;
  21354. }
  21355. var indices = this._renderingMesh.getIndices();
  21356. var extend;
  21357. //is this the only submesh?
  21358. if (this.indexStart === 0 && this.indexCount === indices.length) {
  21359. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  21360. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  21361. }
  21362. else {
  21363. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  21364. }
  21365. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  21366. return this;
  21367. };
  21368. SubMesh.prototype._checkCollision = function (collider) {
  21369. return this.getBoundingInfo()._checkCollision(collider);
  21370. };
  21371. /**
  21372. * Updates the submesh BoundingInfo.
  21373. * Returns the Submesh.
  21374. */
  21375. SubMesh.prototype.updateBoundingInfo = function (world) {
  21376. if (!this.getBoundingInfo()) {
  21377. this.refreshBoundingInfo();
  21378. }
  21379. this.getBoundingInfo().update(world);
  21380. return this;
  21381. };
  21382. /**
  21383. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  21384. * Boolean returned.
  21385. */
  21386. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  21387. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  21388. };
  21389. /**
  21390. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  21391. * Boolean returned.
  21392. */
  21393. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  21394. return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes);
  21395. };
  21396. /**
  21397. * Renders the submesh.
  21398. * Returns it.
  21399. */
  21400. SubMesh.prototype.render = function (enableAlphaMode) {
  21401. this._renderingMesh.render(this, enableAlphaMode);
  21402. return this;
  21403. };
  21404. /**
  21405. * Returns a new Index Buffer.
  21406. * Type returned : WebGLBuffer.
  21407. */
  21408. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  21409. if (!this._linesIndexBuffer) {
  21410. var linesIndices = [];
  21411. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  21412. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  21413. }
  21414. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  21415. this.linesIndexCount = linesIndices.length;
  21416. }
  21417. return this._linesIndexBuffer;
  21418. };
  21419. /**
  21420. * True is the passed Ray intersects the submesh bounding box.
  21421. * Boolean returned.
  21422. */
  21423. SubMesh.prototype.canIntersects = function (ray) {
  21424. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  21425. };
  21426. /**
  21427. * Returns an object IntersectionInfo.
  21428. */
  21429. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  21430. var intersectInfo = null;
  21431. // LineMesh first as it's also a Mesh...
  21432. if (this._mesh instanceof BABYLON.LinesMesh) {
  21433. var lineMesh = this._mesh;
  21434. // Line test
  21435. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  21436. var p0 = positions[indices[index]];
  21437. var p1 = positions[indices[index + 1]];
  21438. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  21439. if (length < 0) {
  21440. continue;
  21441. }
  21442. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  21443. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  21444. if (fastCheck) {
  21445. break;
  21446. }
  21447. }
  21448. }
  21449. }
  21450. else {
  21451. // Triangles test
  21452. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  21453. var p0 = positions[indices[index]];
  21454. var p1 = positions[indices[index + 1]];
  21455. var p2 = positions[indices[index + 2]];
  21456. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  21457. if (currentIntersectInfo) {
  21458. if (currentIntersectInfo.distance < 0) {
  21459. continue;
  21460. }
  21461. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  21462. intersectInfo = currentIntersectInfo;
  21463. intersectInfo.faceId = index / 3;
  21464. if (fastCheck) {
  21465. break;
  21466. }
  21467. }
  21468. }
  21469. }
  21470. }
  21471. return intersectInfo;
  21472. };
  21473. // Clone
  21474. /**
  21475. * Creates a new Submesh from the passed Mesh.
  21476. */
  21477. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  21478. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  21479. if (!this.IsGlobal) {
  21480. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  21481. }
  21482. return result;
  21483. };
  21484. // Dispose
  21485. /**
  21486. * Disposes the Submesh.
  21487. * Returns nothing.
  21488. */
  21489. SubMesh.prototype.dispose = function () {
  21490. if (this._linesIndexBuffer) {
  21491. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  21492. this._linesIndexBuffer = null;
  21493. }
  21494. // Remove from mesh
  21495. var index = this._mesh.subMeshes.indexOf(this);
  21496. this._mesh.subMeshes.splice(index, 1);
  21497. };
  21498. // Statics
  21499. /**
  21500. * Creates a new Submesh from the passed parameters :
  21501. * - materialIndex (integer) : the index of the main mesh material.
  21502. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  21503. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  21504. * - mesh (Mesh) : the main mesh to create the submesh from.
  21505. * - renderingMesh (optional Mesh) : rendering mesh.
  21506. */
  21507. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  21508. var minVertexIndex = Number.MAX_VALUE;
  21509. var maxVertexIndex = -Number.MAX_VALUE;
  21510. renderingMesh = renderingMesh || mesh;
  21511. var indices = renderingMesh.getIndices();
  21512. for (var index = startIndex; index < startIndex + indexCount; index++) {
  21513. var vertexIndex = indices[index];
  21514. if (vertexIndex < minVertexIndex)
  21515. minVertexIndex = vertexIndex;
  21516. if (vertexIndex > maxVertexIndex)
  21517. maxVertexIndex = vertexIndex;
  21518. }
  21519. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  21520. };
  21521. return SubMesh;
  21522. }());
  21523. BABYLON.SubMesh = SubMesh;
  21524. })(BABYLON || (BABYLON = {}));
  21525. //# sourceMappingURL=babylon.subMesh.js.map
  21526. var BABYLON;
  21527. (function (BABYLON) {
  21528. var EffectFallbacks = (function () {
  21529. function EffectFallbacks() {
  21530. this._defines = {};
  21531. this._currentRank = 32;
  21532. this._maxRank = -1;
  21533. }
  21534. EffectFallbacks.prototype.addFallback = function (rank, define) {
  21535. if (!this._defines[rank]) {
  21536. if (rank < this._currentRank) {
  21537. this._currentRank = rank;
  21538. }
  21539. if (rank > this._maxRank) {
  21540. this._maxRank = rank;
  21541. }
  21542. this._defines[rank] = new Array();
  21543. }
  21544. this._defines[rank].push(define);
  21545. };
  21546. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  21547. this._meshRank = rank;
  21548. this._mesh = mesh;
  21549. if (rank < this._currentRank) {
  21550. this._currentRank = rank;
  21551. }
  21552. if (rank > this._maxRank) {
  21553. this._maxRank = rank;
  21554. }
  21555. };
  21556. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  21557. get: function () {
  21558. return this._currentRank <= this._maxRank;
  21559. },
  21560. enumerable: true,
  21561. configurable: true
  21562. });
  21563. EffectFallbacks.prototype.reduce = function (currentDefines) {
  21564. // First we try to switch to CPU skinning
  21565. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  21566. this._mesh.computeBonesUsingShaders = false;
  21567. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  21568. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  21569. var scene = this._mesh.getScene();
  21570. for (var index = 0; index < scene.meshes.length; index++) {
  21571. var otherMesh = scene.meshes[index];
  21572. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  21573. otherMesh.computeBonesUsingShaders = false;
  21574. }
  21575. }
  21576. }
  21577. else {
  21578. var currentFallbacks = this._defines[this._currentRank];
  21579. if (currentFallbacks) {
  21580. for (var index = 0; index < currentFallbacks.length; index++) {
  21581. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  21582. }
  21583. }
  21584. this._currentRank++;
  21585. }
  21586. return currentDefines;
  21587. };
  21588. return EffectFallbacks;
  21589. }());
  21590. BABYLON.EffectFallbacks = EffectFallbacks;
  21591. var EffectCreationOptions = (function () {
  21592. function EffectCreationOptions() {
  21593. }
  21594. return EffectCreationOptions;
  21595. }());
  21596. BABYLON.EffectCreationOptions = EffectCreationOptions;
  21597. var Effect = (function () {
  21598. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  21599. var _this = this;
  21600. this.uniqueId = 0;
  21601. this._uniformBuffersNames = {};
  21602. this._isReady = false;
  21603. this._compilationError = "";
  21604. this._valueCache = {};
  21605. this.name = baseName;
  21606. if (attributesNamesOrOptions.attributes) {
  21607. var options = attributesNamesOrOptions;
  21608. this._engine = uniformsNamesOrEngine;
  21609. this._attributesNames = options.attributes;
  21610. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  21611. this._samplers = options.samplers;
  21612. this.defines = options.defines;
  21613. this.onError = options.onError;
  21614. this.onCompiled = options.onCompiled;
  21615. this._fallbacks = options.fallbacks;
  21616. this._indexParameters = options.indexParameters;
  21617. if (options.uniformBuffersNames) {
  21618. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  21619. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  21620. }
  21621. }
  21622. }
  21623. else {
  21624. this._engine = engine;
  21625. this.defines = defines;
  21626. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  21627. this._samplers = samplers;
  21628. this._attributesNames = attributesNamesOrOptions;
  21629. this.onError = onError;
  21630. this.onCompiled = onCompiled;
  21631. this._indexParameters = indexParameters;
  21632. this._fallbacks = fallbacks;
  21633. }
  21634. this.uniqueId = Effect._uniqueIdSeed++;
  21635. var vertexSource;
  21636. var fragmentSource;
  21637. if (baseName.vertexElement) {
  21638. vertexSource = document.getElementById(baseName.vertexElement);
  21639. if (!vertexSource) {
  21640. vertexSource = baseName.vertexElement;
  21641. }
  21642. }
  21643. else {
  21644. vertexSource = baseName.vertex || baseName;
  21645. }
  21646. if (baseName.fragmentElement) {
  21647. fragmentSource = document.getElementById(baseName.fragmentElement);
  21648. if (!fragmentSource) {
  21649. fragmentSource = baseName.fragmentElement;
  21650. }
  21651. }
  21652. else {
  21653. fragmentSource = baseName.fragment || baseName;
  21654. }
  21655. this._loadVertexShader(vertexSource, function (vertexCode) {
  21656. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  21657. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  21658. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  21659. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  21660. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  21661. _this._prepareEffect(migratedVertexCode, migratedFragmentCode, _this._attributesNames, _this.defines, _this._fallbacks);
  21662. });
  21663. });
  21664. });
  21665. });
  21666. });
  21667. });
  21668. }
  21669. Object.defineProperty(Effect.prototype, "key", {
  21670. get: function () {
  21671. return this._key;
  21672. },
  21673. enumerable: true,
  21674. configurable: true
  21675. });
  21676. // Properties
  21677. Effect.prototype.isReady = function () {
  21678. return this._isReady;
  21679. };
  21680. Effect.prototype.getProgram = function () {
  21681. return this._program;
  21682. };
  21683. Effect.prototype.getAttributesNames = function () {
  21684. return this._attributesNames;
  21685. };
  21686. Effect.prototype.getAttributeLocation = function (index) {
  21687. return this._attributes[index];
  21688. };
  21689. Effect.prototype.getAttributeLocationByName = function (name) {
  21690. var index = this._attributesNames.indexOf(name);
  21691. return this._attributes[index];
  21692. };
  21693. Effect.prototype.getAttributesCount = function () {
  21694. return this._attributes.length;
  21695. };
  21696. Effect.prototype.getUniformIndex = function (uniformName) {
  21697. return this._uniformsNames.indexOf(uniformName);
  21698. };
  21699. Effect.prototype.getUniform = function (uniformName) {
  21700. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  21701. };
  21702. Effect.prototype.getSamplers = function () {
  21703. return this._samplers;
  21704. };
  21705. Effect.prototype.getCompilationError = function () {
  21706. return this._compilationError;
  21707. };
  21708. Effect.prototype.getVertexShaderSource = function () {
  21709. return this._evaluateDefinesOnString(this._engine.getVertexShaderSource(this._program));
  21710. };
  21711. Effect.prototype.getFragmentShaderSource = function () {
  21712. return this._evaluateDefinesOnString(this._engine.getFragmentShaderSource(this._program));
  21713. };
  21714. // Methods
  21715. Effect.prototype._loadVertexShader = function (vertex, callback) {
  21716. // DOM element ?
  21717. if (vertex instanceof HTMLElement) {
  21718. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  21719. callback(vertexCode);
  21720. return;
  21721. }
  21722. // Base64 encoded ?
  21723. if (vertex.substr(0, 7) === "base64:") {
  21724. var vertexBinary = window.atob(vertex.substr(7));
  21725. callback(vertexBinary);
  21726. return;
  21727. }
  21728. // Is in local store ?
  21729. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  21730. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  21731. return;
  21732. }
  21733. var vertexShaderUrl;
  21734. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  21735. vertexShaderUrl = vertex;
  21736. }
  21737. else {
  21738. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  21739. }
  21740. // Vertex shader
  21741. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  21742. };
  21743. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  21744. // DOM element ?
  21745. if (fragment instanceof HTMLElement) {
  21746. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  21747. callback(fragmentCode);
  21748. return;
  21749. }
  21750. // Base64 encoded ?
  21751. if (fragment.substr(0, 7) === "base64:") {
  21752. var fragmentBinary = window.atob(fragment.substr(7));
  21753. callback(fragmentBinary);
  21754. return;
  21755. }
  21756. // Is in local store ?
  21757. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  21758. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  21759. return;
  21760. }
  21761. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  21762. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  21763. return;
  21764. }
  21765. var fragmentShaderUrl;
  21766. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  21767. fragmentShaderUrl = fragment;
  21768. }
  21769. else {
  21770. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  21771. }
  21772. // Fragment shader
  21773. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  21774. };
  21775. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  21776. // Rebuild shaders source code
  21777. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  21778. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  21779. vertexCode = prefix + vertexCode;
  21780. fragmentCode = prefix + fragmentCode;
  21781. // Number lines of shaders source code
  21782. var i = 2;
  21783. var regex = /\n/gm;
  21784. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  21785. i = 2;
  21786. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  21787. // Dump shaders name and formatted source code
  21788. if (this.name.vertexElement) {
  21789. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  21790. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  21791. }
  21792. else if (this.name.vertex) {
  21793. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  21794. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  21795. }
  21796. else {
  21797. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  21798. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  21799. }
  21800. };
  21801. ;
  21802. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  21803. var preparedSourceCode = this._processPrecision(sourceCode);
  21804. if (this._engine.webGLVersion == 1) {
  21805. callback(preparedSourceCode);
  21806. return;
  21807. }
  21808. // Already converted
  21809. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  21810. callback(preparedSourceCode);
  21811. return;
  21812. }
  21813. // Remove extensions
  21814. // #extension GL_OES_standard_derivatives : enable
  21815. // #extension GL_EXT_shader_texture_lod : enable
  21816. // #extension GL_EXT_frag_depth : enable
  21817. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth).+enable/g;
  21818. var result = preparedSourceCode.replace(regex, "");
  21819. // Migrate to GLSL v300
  21820. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  21821. result = result.replace(/attribute[ \t]/g, "in ");
  21822. result = result.replace(/[ \t]attribute/g, " in");
  21823. if (isFragment) {
  21824. result = result.replace(/texture2DLodEXT\(/g, "textureLod(");
  21825. result = result.replace(/textureCubeLodEXT\(/g, "textureLod(");
  21826. result = result.replace(/texture2D\(/g, "texture(");
  21827. result = result.replace(/textureCube\(/g, "texture(");
  21828. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  21829. result = result.replace(/gl_FragColor/g, "glFragColor");
  21830. result = result.replace(/void\s+?main\(/g, "out vec4 glFragColor;\nvoid main(");
  21831. }
  21832. callback(result);
  21833. };
  21834. Effect.prototype._processIncludes = function (sourceCode, callback) {
  21835. var _this = this;
  21836. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  21837. var match = regex.exec(sourceCode);
  21838. var returnValue = new String(sourceCode);
  21839. while (match != null) {
  21840. var includeFile = match[1];
  21841. // Uniform declaration
  21842. if (includeFile.indexOf("__decl__") !== -1) {
  21843. includeFile = includeFile.replace(/__decl__/, "");
  21844. if (this._engine.webGLVersion != 1) {
  21845. includeFile = includeFile.replace(/Vertex/, "Ubo");
  21846. includeFile = includeFile.replace(/Fragment/, "Ubo");
  21847. }
  21848. includeFile = includeFile + "Declaration";
  21849. }
  21850. if (Effect.IncludesShadersStore[includeFile]) {
  21851. // Substitution
  21852. var includeContent = Effect.IncludesShadersStore[includeFile];
  21853. if (match[2]) {
  21854. var splits = match[3].split(",");
  21855. for (var index = 0; index < splits.length; index += 2) {
  21856. var source = new RegExp(splits[index], "g");
  21857. var dest = splits[index + 1];
  21858. includeContent = includeContent.replace(source, dest);
  21859. }
  21860. }
  21861. if (match[4]) {
  21862. var indexString = match[5];
  21863. if (indexString.indexOf("..") !== -1) {
  21864. var indexSplits = indexString.split("..");
  21865. var minIndex = parseInt(indexSplits[0]);
  21866. var maxIndex = parseInt(indexSplits[1]);
  21867. var sourceIncludeContent = includeContent.slice(0);
  21868. includeContent = "";
  21869. if (isNaN(maxIndex)) {
  21870. maxIndex = this._indexParameters[indexSplits[1]];
  21871. }
  21872. for (var i = minIndex; i < maxIndex; i++) {
  21873. if (this._engine.webGLVersion === 1) {
  21874. // Ubo replacement
  21875. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  21876. return p1 + "{X}";
  21877. });
  21878. }
  21879. includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
  21880. }
  21881. }
  21882. else {
  21883. if (this._engine.webGLVersion === 1) {
  21884. // Ubo replacement
  21885. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  21886. return p1 + "{X}";
  21887. });
  21888. }
  21889. includeContent = includeContent.replace(/\{X\}/g, indexString);
  21890. }
  21891. }
  21892. // Replace
  21893. returnValue = returnValue.replace(match[0], includeContent);
  21894. }
  21895. else {
  21896. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  21897. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  21898. Effect.IncludesShadersStore[includeFile] = fileContent;
  21899. _this._processIncludes(returnValue, callback);
  21900. });
  21901. return;
  21902. }
  21903. match = regex.exec(sourceCode);
  21904. }
  21905. callback(returnValue);
  21906. };
  21907. Effect.prototype._processPrecision = function (source) {
  21908. if (source.indexOf("precision highp float") === -1) {
  21909. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  21910. source = "precision mediump float;\n" + source;
  21911. }
  21912. else {
  21913. source = "precision highp float;\n" + source;
  21914. }
  21915. }
  21916. else {
  21917. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  21918. source = source.replace("precision highp float", "precision mediump float");
  21919. }
  21920. }
  21921. return source;
  21922. };
  21923. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  21924. try {
  21925. var engine = this._engine;
  21926. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  21927. if (engine.webGLVersion > 1) {
  21928. for (var name in this._uniformBuffersNames) {
  21929. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  21930. }
  21931. }
  21932. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  21933. this._attributes = engine.getAttributes(this._program, attributesNames);
  21934. var index;
  21935. for (index = 0; index < this._samplers.length; index++) {
  21936. var sampler = this.getUniform(this._samplers[index]);
  21937. if (sampler == null) {
  21938. this._samplers.splice(index, 1);
  21939. index--;
  21940. }
  21941. }
  21942. engine.bindSamplers(this);
  21943. this._compilationError = "";
  21944. this._isReady = true;
  21945. if (this.onCompiled) {
  21946. this.onCompiled(this);
  21947. }
  21948. }
  21949. catch (e) {
  21950. this._compilationError = e.message;
  21951. // Let's go through fallbacks then
  21952. BABYLON.Tools.Error("Unable to compile effect:");
  21953. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  21954. return " " + uniform;
  21955. }));
  21956. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  21957. return " " + attribute;
  21958. }));
  21959. this._dumpShadersSource(vertexSourceCode, fragmentSourceCode, defines);
  21960. BABYLON.Tools.Error("Error: " + this._compilationError);
  21961. if (fallbacks && fallbacks.isMoreFallbacks) {
  21962. BABYLON.Tools.Error("Trying next fallback.");
  21963. defines = fallbacks.reduce(defines);
  21964. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  21965. }
  21966. else {
  21967. if (this.onError) {
  21968. this.onError(this, this._compilationError);
  21969. }
  21970. }
  21971. }
  21972. };
  21973. Object.defineProperty(Effect.prototype, "isSupported", {
  21974. get: function () {
  21975. return this._compilationError === "";
  21976. },
  21977. enumerable: true,
  21978. configurable: true
  21979. });
  21980. Effect.prototype._bindTexture = function (channel, texture) {
  21981. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  21982. };
  21983. Effect.prototype.setTexture = function (channel, texture) {
  21984. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  21985. };
  21986. Effect.prototype.setTextureArray = function (channel, textures) {
  21987. if (this._samplers.indexOf(channel + "Ex") === -1) {
  21988. var initialPos = this._samplers.indexOf(channel);
  21989. for (var index = 1; index < textures.length; index++) {
  21990. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  21991. }
  21992. }
  21993. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  21994. };
  21995. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  21996. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  21997. };
  21998. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  21999. var cache = this._valueCache[uniformName];
  22000. var flag = matrix.updateFlag;
  22001. if (cache !== undefined && cache === flag) {
  22002. return false;
  22003. }
  22004. this._valueCache[uniformName] = flag;
  22005. return true;
  22006. };
  22007. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  22008. var cache = this._valueCache[uniformName];
  22009. if (!cache) {
  22010. cache = [x, y];
  22011. this._valueCache[uniformName] = cache;
  22012. return true;
  22013. }
  22014. var changed = false;
  22015. if (cache[0] !== x) {
  22016. cache[0] = x;
  22017. changed = true;
  22018. }
  22019. if (cache[1] !== y) {
  22020. cache[1] = y;
  22021. changed = true;
  22022. }
  22023. return changed;
  22024. };
  22025. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  22026. var cache = this._valueCache[uniformName];
  22027. if (!cache) {
  22028. cache = [x, y, z];
  22029. this._valueCache[uniformName] = cache;
  22030. return true;
  22031. }
  22032. var changed = false;
  22033. if (cache[0] !== x) {
  22034. cache[0] = x;
  22035. changed = true;
  22036. }
  22037. if (cache[1] !== y) {
  22038. cache[1] = y;
  22039. changed = true;
  22040. }
  22041. if (cache[2] !== z) {
  22042. cache[2] = z;
  22043. changed = true;
  22044. }
  22045. return changed;
  22046. };
  22047. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  22048. var cache = this._valueCache[uniformName];
  22049. if (!cache) {
  22050. cache = [x, y, z, w];
  22051. this._valueCache[uniformName] = cache;
  22052. return true;
  22053. }
  22054. var changed = false;
  22055. if (cache[0] !== x) {
  22056. cache[0] = x;
  22057. changed = true;
  22058. }
  22059. if (cache[1] !== y) {
  22060. cache[1] = y;
  22061. changed = true;
  22062. }
  22063. if (cache[2] !== z) {
  22064. cache[2] = z;
  22065. changed = true;
  22066. }
  22067. if (cache[3] !== w) {
  22068. cache[3] = w;
  22069. changed = true;
  22070. }
  22071. return changed;
  22072. };
  22073. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  22074. if (Effect._baseCache[this._uniformBuffersNames[name]] === buffer) {
  22075. return;
  22076. }
  22077. Effect._baseCache[this._uniformBuffersNames[name]] = buffer;
  22078. this._engine.bindUniformBufferBase(buffer, this._uniformBuffersNames[name]);
  22079. };
  22080. Effect.prototype.bindUniformBlock = function (blockName, index) {
  22081. this._engine.bindUniformBlock(this._program, blockName, index);
  22082. };
  22083. Effect.prototype.setIntArray = function (uniformName, array) {
  22084. this._valueCache[uniformName] = null;
  22085. this._engine.setIntArray(this.getUniform(uniformName), array);
  22086. return this;
  22087. };
  22088. Effect.prototype.setIntArray2 = function (uniformName, array) {
  22089. this._valueCache[uniformName] = null;
  22090. this._engine.setIntArray2(this.getUniform(uniformName), array);
  22091. return this;
  22092. };
  22093. Effect.prototype.setIntArray3 = function (uniformName, array) {
  22094. this._valueCache[uniformName] = null;
  22095. this._engine.setIntArray3(this.getUniform(uniformName), array);
  22096. return this;
  22097. };
  22098. Effect.prototype.setIntArray4 = function (uniformName, array) {
  22099. this._valueCache[uniformName] = null;
  22100. this._engine.setIntArray4(this.getUniform(uniformName), array);
  22101. return this;
  22102. };
  22103. Effect.prototype.setFloatArray = function (uniformName, array) {
  22104. this._valueCache[uniformName] = null;
  22105. this._engine.setFloatArray(this.getUniform(uniformName), array);
  22106. return this;
  22107. };
  22108. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  22109. this._valueCache[uniformName] = null;
  22110. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  22111. return this;
  22112. };
  22113. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  22114. this._valueCache[uniformName] = null;
  22115. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  22116. return this;
  22117. };
  22118. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  22119. this._valueCache[uniformName] = null;
  22120. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  22121. return this;
  22122. };
  22123. Effect.prototype.setArray = function (uniformName, array) {
  22124. this._valueCache[uniformName] = null;
  22125. this._engine.setArray(this.getUniform(uniformName), array);
  22126. return this;
  22127. };
  22128. Effect.prototype.setArray2 = function (uniformName, array) {
  22129. this._valueCache[uniformName] = null;
  22130. this._engine.setArray2(this.getUniform(uniformName), array);
  22131. return this;
  22132. };
  22133. Effect.prototype.setArray3 = function (uniformName, array) {
  22134. this._valueCache[uniformName] = null;
  22135. this._engine.setArray3(this.getUniform(uniformName), array);
  22136. return this;
  22137. };
  22138. Effect.prototype.setArray4 = function (uniformName, array) {
  22139. this._valueCache[uniformName] = null;
  22140. this._engine.setArray4(this.getUniform(uniformName), array);
  22141. return this;
  22142. };
  22143. Effect.prototype.setMatrices = function (uniformName, matrices) {
  22144. if (!matrices) {
  22145. return;
  22146. }
  22147. this._valueCache[uniformName] = null;
  22148. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  22149. return this;
  22150. };
  22151. Effect.prototype.setMatrix = function (uniformName, matrix) {
  22152. if (this._cacheMatrix(uniformName, matrix)) {
  22153. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  22154. }
  22155. return this;
  22156. };
  22157. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  22158. this._valueCache[uniformName] = null;
  22159. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  22160. return this;
  22161. };
  22162. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  22163. this._valueCache[uniformName] = null;
  22164. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  22165. return this;
  22166. };
  22167. Effect.prototype.setFloat = function (uniformName, value) {
  22168. var cache = this._valueCache[uniformName];
  22169. if (cache !== undefined && cache === value)
  22170. return this;
  22171. this._valueCache[uniformName] = value;
  22172. this._engine.setFloat(this.getUniform(uniformName), value);
  22173. return this;
  22174. };
  22175. Effect.prototype.setBool = function (uniformName, bool) {
  22176. var cache = this._valueCache[uniformName];
  22177. if (cache !== undefined && cache === bool)
  22178. return this;
  22179. this._valueCache[uniformName] = bool;
  22180. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  22181. return this;
  22182. };
  22183. Effect.prototype.setVector2 = function (uniformName, vector2) {
  22184. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  22185. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  22186. }
  22187. return this;
  22188. };
  22189. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  22190. if (this._cacheFloat2(uniformName, x, y)) {
  22191. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  22192. }
  22193. return this;
  22194. };
  22195. Effect.prototype.setVector3 = function (uniformName, vector3) {
  22196. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  22197. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  22198. }
  22199. return this;
  22200. };
  22201. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  22202. if (this._cacheFloat3(uniformName, x, y, z)) {
  22203. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  22204. }
  22205. return this;
  22206. };
  22207. Effect.prototype.setVector4 = function (uniformName, vector4) {
  22208. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  22209. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  22210. }
  22211. return this;
  22212. };
  22213. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  22214. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  22215. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  22216. }
  22217. return this;
  22218. };
  22219. Effect.prototype.setColor3 = function (uniformName, color3) {
  22220. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  22221. this._engine.setColor3(this.getUniform(uniformName), color3);
  22222. }
  22223. return this;
  22224. };
  22225. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  22226. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  22227. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  22228. }
  22229. return this;
  22230. };
  22231. Effect.prototype._recombineShader = function (node) {
  22232. if (node.define) {
  22233. if (node.condition) {
  22234. var defineIndex = this.defines.indexOf("#define " + node.define);
  22235. if (defineIndex === -1) {
  22236. return null;
  22237. }
  22238. var nextComma = this.defines.indexOf("\n", defineIndex);
  22239. var defineValue = this.defines.substr(defineIndex + 7, nextComma - defineIndex - 7).replace(node.define, "").trim();
  22240. var condition = defineValue + node.condition;
  22241. if (!eval(condition)) {
  22242. return null;
  22243. }
  22244. }
  22245. else if (node.ndef) {
  22246. if (this.defines.indexOf("#define " + node.define) !== -1) {
  22247. return null;
  22248. }
  22249. }
  22250. else if (this.defines.indexOf("#define " + node.define) === -1) {
  22251. return null;
  22252. }
  22253. }
  22254. var result = "";
  22255. for (var index = 0; index < node.children.length; index++) {
  22256. var line = node.children[index];
  22257. if (line.children) {
  22258. var combined = this._recombineShader(line);
  22259. if (combined !== null) {
  22260. result += combined + "\r\n";
  22261. }
  22262. continue;
  22263. }
  22264. if (line.length > 0) {
  22265. result += line + "\r\n";
  22266. }
  22267. }
  22268. return result;
  22269. };
  22270. Effect.prototype._evaluateDefinesOnString = function (shaderString) {
  22271. var root = {
  22272. children: []
  22273. };
  22274. var currentNode = root;
  22275. var lines = shaderString.split("\n");
  22276. for (var index = 0; index < lines.length; index++) {
  22277. var line = lines[index].trim();
  22278. // #ifdef
  22279. var pos = line.indexOf("#ifdef ");
  22280. if (pos !== -1) {
  22281. var define = line.substr(pos + 7);
  22282. var newNode = {
  22283. condition: null,
  22284. ndef: false,
  22285. define: define,
  22286. children: [],
  22287. parent: currentNode
  22288. };
  22289. currentNode.children.push(newNode);
  22290. currentNode = newNode;
  22291. continue;
  22292. }
  22293. // #ifndef
  22294. var pos = line.indexOf("#ifndef ");
  22295. if (pos !== -1) {
  22296. var define = line.substr(pos + 8);
  22297. newNode = {
  22298. condition: null,
  22299. define: define,
  22300. ndef: true,
  22301. children: [],
  22302. parent: currentNode
  22303. };
  22304. currentNode.children.push(newNode);
  22305. currentNode = newNode;
  22306. continue;
  22307. }
  22308. // #if
  22309. var pos = line.indexOf("#if ");
  22310. if (pos !== -1) {
  22311. var define = line.substr(pos + 4).trim();
  22312. var conditionPos = define.indexOf(" ");
  22313. newNode = {
  22314. condition: define.substr(conditionPos + 1),
  22315. define: define.substr(0, conditionPos),
  22316. ndef: false,
  22317. children: [],
  22318. parent: currentNode
  22319. };
  22320. currentNode.children.push(newNode);
  22321. currentNode = newNode;
  22322. continue;
  22323. }
  22324. // #endif
  22325. pos = line.indexOf("#endif");
  22326. if (pos !== -1) {
  22327. currentNode = currentNode.parent;
  22328. continue;
  22329. }
  22330. currentNode.children.push(line);
  22331. }
  22332. // Recombine
  22333. return this._recombineShader(root);
  22334. };
  22335. return Effect;
  22336. }());
  22337. Effect._uniqueIdSeed = 0;
  22338. Effect._baseCache = {};
  22339. // Statics
  22340. Effect.ShadersStore = {};
  22341. Effect.IncludesShadersStore = {};
  22342. BABYLON.Effect = Effect;
  22343. })(BABYLON || (BABYLON = {}));
  22344. //# sourceMappingURL=babylon.effect.js.map
  22345. var BABYLON;
  22346. (function (BABYLON) {
  22347. var MaterialHelper = (function () {
  22348. function MaterialHelper() {
  22349. }
  22350. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, defines) {
  22351. if (defines._areMiscDirty) {
  22352. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  22353. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  22354. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  22355. }
  22356. };
  22357. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances) {
  22358. var changed = false;
  22359. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  22360. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  22361. changed = true;
  22362. }
  22363. if (defines["ALPHATEST"] !== engine.getAlphaTesting()) {
  22364. defines["ALPHATEST"] = !defines["ALPHATEST"];
  22365. changed = true;
  22366. }
  22367. if (defines["INSTANCES"] !== useInstances) {
  22368. defines["INSTANCES"] = useInstances;
  22369. changed = true;
  22370. }
  22371. if (changed) {
  22372. defines.markAsUnprocessed();
  22373. }
  22374. };
  22375. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets) {
  22376. if (useMorphTargets === void 0) { useMorphTargets = false; }
  22377. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  22378. return;
  22379. }
  22380. defines._normals = defines._needNormals;
  22381. defines._uvs = defines._needUVs;
  22382. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  22383. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  22384. defines["TANGENT"] = true;
  22385. }
  22386. if (defines._needUVs) {
  22387. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  22388. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  22389. }
  22390. else {
  22391. defines["UV1"] = false;
  22392. defines["UV2"] = false;
  22393. }
  22394. if (useVertexColor) {
  22395. defines["VERTEXCOLOR"] = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  22396. defines["VERTEXALPHA"] = mesh.hasVertexAlpha;
  22397. }
  22398. if (useBones) {
  22399. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  22400. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  22401. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  22402. }
  22403. else {
  22404. defines["NUM_BONE_INFLUENCERS"] = 0;
  22405. defines["BonesPerMesh"] = 0;
  22406. }
  22407. }
  22408. if (useMorphTargets) {
  22409. if (mesh.morphTargetManager) {
  22410. var manager = mesh.morphTargetManager;
  22411. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  22412. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  22413. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  22414. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  22415. }
  22416. else {
  22417. defines["MORPHTARGETS_TANGENT"] = false;
  22418. defines["MORPHTARGETS_NORMAL"] = false;
  22419. defines["MORPHTARGETS"] = false;
  22420. defines["NUM_MORPH_INFLUENCERS"] = 0;
  22421. }
  22422. }
  22423. };
  22424. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  22425. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  22426. if (disableLighting === void 0) { disableLighting = false; }
  22427. if (!defines._areLightsDirty) {
  22428. return defines._needNormals;
  22429. }
  22430. var lightIndex = 0;
  22431. var needNormals = false;
  22432. var needRebuild = false;
  22433. var lightmapMode = false;
  22434. var shadowEnabled = false;
  22435. var specularEnabled = false;
  22436. if (scene.lightsEnabled && !disableLighting) {
  22437. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  22438. var light = _a[_i];
  22439. needNormals = true;
  22440. if (defines["LIGHT" + lightIndex] === undefined) {
  22441. needRebuild = true;
  22442. }
  22443. defines["LIGHT" + lightIndex] = true;
  22444. defines["SPOTLIGHT" + lightIndex] = false;
  22445. defines["HEMILIGHT" + lightIndex] = false;
  22446. defines["POINTLIGHT" + lightIndex] = false;
  22447. defines["DIRLIGHT" + lightIndex] = false;
  22448. var type;
  22449. if (light.getTypeID() === 2) {
  22450. type = "SPOTLIGHT" + lightIndex;
  22451. }
  22452. else if (light.getTypeID() === 3) {
  22453. type = "HEMILIGHT" + lightIndex;
  22454. }
  22455. else if (light.getTypeID() === 0) {
  22456. type = "POINTLIGHT" + lightIndex;
  22457. }
  22458. else {
  22459. type = "DIRLIGHT" + lightIndex;
  22460. }
  22461. defines[type] = true;
  22462. // Specular
  22463. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  22464. specularEnabled = true;
  22465. }
  22466. // Shadows
  22467. defines["SHADOW" + lightIndex] = false;
  22468. if (scene.shadowsEnabled) {
  22469. var shadowGenerator = light.getShadowGenerator();
  22470. if (mesh && mesh.receiveShadows && shadowGenerator) {
  22471. defines["SHADOW" + lightIndex] = true;
  22472. shadowEnabled = true;
  22473. defines["SHADOWPCF" + lightIndex] = false;
  22474. defines["SHADOWESM" + lightIndex] = false;
  22475. if (shadowGenerator.usePoissonSampling) {
  22476. defines["SHADOWPCF" + lightIndex] = true;
  22477. }
  22478. else if (shadowGenerator.useExponentialShadowMap || shadowGenerator.useBlurExponentialShadowMap) {
  22479. defines["SHADOWESM" + lightIndex] = true;
  22480. }
  22481. }
  22482. }
  22483. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  22484. lightmapMode = true;
  22485. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  22486. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  22487. }
  22488. else {
  22489. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  22490. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  22491. }
  22492. lightIndex++;
  22493. if (lightIndex === maxSimultaneousLights)
  22494. break;
  22495. }
  22496. }
  22497. defines["SPECULARTERM"] = specularEnabled;
  22498. defines["SHADOWS"] = shadowEnabled;
  22499. // Resetting all other lights if any
  22500. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  22501. if (defines["LIGHT" + index] !== undefined) {
  22502. defines["LIGHT" + index] = false;
  22503. }
  22504. }
  22505. var caps = scene.getEngine().getCaps();
  22506. if (defines["SHADOWFULLFLOAT"] === undefined) {
  22507. needRebuild = true;
  22508. }
  22509. defines["SHADOWFULLFLOAT"] = (shadowEnabled && caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender);
  22510. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  22511. if (needRebuild) {
  22512. defines.rebuild();
  22513. }
  22514. return needNormals;
  22515. };
  22516. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  22517. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  22518. var uniformsList, uniformBuffersList, samplersList, defines;
  22519. if (uniformsListOrOptions.uniformsNames) {
  22520. var options = uniformsListOrOptions;
  22521. uniformsList = options.uniformsNames;
  22522. uniformBuffersList = options.uniformBuffersNames;
  22523. samplersList = options.samplers;
  22524. defines = options.defines;
  22525. maxSimultaneousLights = options.maxSimultaneousLights;
  22526. }
  22527. else {
  22528. uniformsList = uniformsListOrOptions;
  22529. }
  22530. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  22531. if (!defines["LIGHT" + lightIndex]) {
  22532. break;
  22533. }
  22534. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex);
  22535. if (uniformBuffersList) {
  22536. uniformBuffersList.push("Light" + lightIndex);
  22537. }
  22538. samplersList.push("shadowSampler" + lightIndex);
  22539. }
  22540. if (defines["NUM_MORPH_INFLUENCERS"]) {
  22541. uniformsList.push("morphTargetInfluences");
  22542. }
  22543. };
  22544. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  22545. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  22546. if (!defines["SHADOWS"]) {
  22547. return;
  22548. }
  22549. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  22550. if (!defines["LIGHT" + lightIndex]) {
  22551. break;
  22552. }
  22553. if (lightIndex > 0) {
  22554. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  22555. }
  22556. if (defines["SHADOW" + lightIndex]) {
  22557. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  22558. }
  22559. if (defines["SHADOWPCF" + lightIndex]) {
  22560. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  22561. }
  22562. if (defines["SHADOWESM" + lightIndex]) {
  22563. fallbacks.addFallback(0, "SHADOWESM" + lightIndex);
  22564. }
  22565. }
  22566. };
  22567. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  22568. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  22569. if (influencers > 0) {
  22570. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  22571. var manager = mesh.morphTargetManager;
  22572. var normal = manager.supportsNormals && defines["NORMAL"];
  22573. var tangent = manager.supportsTangents && defines["TANGENT"];
  22574. for (var index = 0; index < influencers; index++) {
  22575. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  22576. if (normal) {
  22577. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  22578. }
  22579. if (tangent) {
  22580. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  22581. }
  22582. if (attribs.length > maxAttributesCount) {
  22583. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  22584. }
  22585. }
  22586. }
  22587. };
  22588. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  22589. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  22590. fallbacks.addCPUSkinningFallback(0, mesh);
  22591. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  22592. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  22593. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  22594. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  22595. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  22596. }
  22597. }
  22598. };
  22599. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  22600. if (defines["INSTANCES"]) {
  22601. attribs.push("world0");
  22602. attribs.push("world1");
  22603. attribs.push("world2");
  22604. attribs.push("world3");
  22605. }
  22606. };
  22607. // Bindings
  22608. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect, depthValuesAlreadySet) {
  22609. var shadowGenerator = light.getShadowGenerator();
  22610. if (mesh.receiveShadows && shadowGenerator) {
  22611. if (!light.needCube()) {
  22612. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  22613. }
  22614. else {
  22615. if (!depthValuesAlreadySet) {
  22616. depthValuesAlreadySet = true;
  22617. effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  22618. }
  22619. }
  22620. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  22621. light._uniformBuffer.updateFloat3("shadowsInfo", shadowGenerator.getDarkness(), shadowGenerator.blurScale / shadowGenerator.getShadowMap().getSize().width, shadowGenerator.depthScale, lightIndex);
  22622. }
  22623. return depthValuesAlreadySet;
  22624. };
  22625. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  22626. light.transferToEffect(effect, lightIndex + "");
  22627. };
  22628. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights) {
  22629. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  22630. var lightIndex = 0;
  22631. var depthValuesAlreadySet = false;
  22632. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  22633. var light = _a[_i];
  22634. light._uniformBuffer.bindToEffect(effect, "Light" + lightIndex);
  22635. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  22636. light.diffuse.scaleToRef(light.intensity, BABYLON.Tmp.Color3[0]);
  22637. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], light.range, lightIndex + "");
  22638. if (defines["SPECULARTERM"]) {
  22639. light.specular.scaleToRef(light.intensity, BABYLON.Tmp.Color3[1]);
  22640. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], lightIndex + "");
  22641. }
  22642. // Shadows
  22643. if (scene.shadowsEnabled) {
  22644. depthValuesAlreadySet = this.BindLightShadow(light, scene, mesh, lightIndex + "", effect, depthValuesAlreadySet);
  22645. }
  22646. light._uniformBuffer.update();
  22647. lightIndex++;
  22648. if (lightIndex === maxSimultaneousLights)
  22649. break;
  22650. }
  22651. };
  22652. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  22653. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  22654. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  22655. effect.setColor3("vFogColor", scene.fogColor);
  22656. }
  22657. };
  22658. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  22659. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  22660. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  22661. if (matrices) {
  22662. effect.setMatrices("mBones", matrices);
  22663. }
  22664. }
  22665. };
  22666. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  22667. if (!abstractMesh || !abstractMesh.morphTargetManager) {
  22668. return;
  22669. }
  22670. effect.setFloatArray("morphTargetInfluences", abstractMesh.morphTargetManager.influences);
  22671. };
  22672. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  22673. if (defines["LOGARITHMICDEPTH"]) {
  22674. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  22675. }
  22676. };
  22677. MaterialHelper.BindClipPlane = function (effect, scene) {
  22678. if (scene.clipPlane) {
  22679. var clipPlane = scene.clipPlane;
  22680. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  22681. }
  22682. };
  22683. return MaterialHelper;
  22684. }());
  22685. BABYLON.MaterialHelper = MaterialHelper;
  22686. })(BABYLON || (BABYLON = {}));
  22687. //# sourceMappingURL=babylon.materialHelper.js.map
  22688. var BABYLON;
  22689. (function (BABYLON) {
  22690. var MaterialDefines = (function () {
  22691. function MaterialDefines() {
  22692. this._isDirty = true;
  22693. this._areLightsDirty = true;
  22694. this._areAttributesDirty = true;
  22695. this._areTexturesDirty = true;
  22696. this._areFresnelDirty = true;
  22697. this._areMiscDirty = true;
  22698. this._normals = false;
  22699. this._uvs = false;
  22700. this._needNormals = false;
  22701. this._needUVs = false;
  22702. }
  22703. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  22704. get: function () {
  22705. return this._isDirty;
  22706. },
  22707. enumerable: true,
  22708. configurable: true
  22709. });
  22710. MaterialDefines.prototype.markAsProcessed = function () {
  22711. this._isDirty = false;
  22712. this._areAttributesDirty = false;
  22713. this._areTexturesDirty = false;
  22714. this._areFresnelDirty = false;
  22715. this._areLightsDirty = false;
  22716. this._areMiscDirty = false;
  22717. };
  22718. MaterialDefines.prototype.markAsUnprocessed = function () {
  22719. this._isDirty = true;
  22720. };
  22721. MaterialDefines.prototype.markAllAsDirty = function () {
  22722. this._areTexturesDirty = true;
  22723. this._areAttributesDirty = true;
  22724. this._areLightsDirty = true;
  22725. this._areFresnelDirty = true;
  22726. this._areMiscDirty = true;
  22727. this._isDirty = true;
  22728. };
  22729. MaterialDefines.prototype.markAsLightDirty = function () {
  22730. this._areLightsDirty = true;
  22731. this._isDirty = true;
  22732. };
  22733. MaterialDefines.prototype.markAsAttributesDirty = function () {
  22734. this._areAttributesDirty = true;
  22735. this._isDirty = true;
  22736. };
  22737. MaterialDefines.prototype.markAsTexturesDirty = function () {
  22738. this._areTexturesDirty = true;
  22739. this._isDirty = true;
  22740. };
  22741. MaterialDefines.prototype.markAsFresnelDirty = function () {
  22742. this._areFresnelDirty = true;
  22743. this._isDirty = true;
  22744. };
  22745. MaterialDefines.prototype.markAsMiscDirty = function () {
  22746. this._areMiscDirty = true;
  22747. this._isDirty = true;
  22748. };
  22749. MaterialDefines.prototype.rebuild = function () {
  22750. if (this._keys) {
  22751. delete this._keys;
  22752. }
  22753. this._keys = [];
  22754. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  22755. var key = _a[_i];
  22756. if (key[0] === "_") {
  22757. continue;
  22758. }
  22759. this._keys.push(key);
  22760. }
  22761. };
  22762. MaterialDefines.prototype.isEqual = function (other) {
  22763. if (this._keys.length !== other._keys.length) {
  22764. return false;
  22765. }
  22766. for (var index = 0; index < this._keys.length; index++) {
  22767. var prop = this._keys[index];
  22768. if (this[prop] !== other[prop]) {
  22769. return false;
  22770. }
  22771. }
  22772. return true;
  22773. };
  22774. MaterialDefines.prototype.cloneTo = function (other) {
  22775. if (this._keys.length !== other._keys.length) {
  22776. other._keys = this._keys.slice(0);
  22777. }
  22778. for (var index = 0; index < this._keys.length; index++) {
  22779. var prop = this._keys[index];
  22780. other[prop] = this[prop];
  22781. }
  22782. };
  22783. MaterialDefines.prototype.reset = function () {
  22784. for (var index = 0; index < this._keys.length; index++) {
  22785. var prop = this._keys[index];
  22786. if (typeof (this[prop]) === "number") {
  22787. this[prop] = 0;
  22788. }
  22789. else {
  22790. this[prop] = false;
  22791. }
  22792. }
  22793. };
  22794. MaterialDefines.prototype.toString = function () {
  22795. var result = "";
  22796. for (var index = 0; index < this._keys.length; index++) {
  22797. var prop = this._keys[index];
  22798. var value = this[prop];
  22799. if (typeof (value) === "number") {
  22800. result += "#define " + prop + " " + this[prop] + "\n";
  22801. }
  22802. else if (value) {
  22803. result += "#define " + prop + "\n";
  22804. }
  22805. }
  22806. return result;
  22807. };
  22808. return MaterialDefines;
  22809. }());
  22810. BABYLON.MaterialDefines = MaterialDefines;
  22811. var Material = (function () {
  22812. function Material(name, scene, doNotAdd) {
  22813. this.checkReadyOnEveryCall = false;
  22814. this.checkReadyOnlyOnce = false;
  22815. this.state = "";
  22816. this.alpha = 1.0;
  22817. this._backFaceCulling = true;
  22818. this.doNotSerialize = false;
  22819. this.storeEffectOnSubMeshes = false;
  22820. /**
  22821. * An event triggered when the material is disposed.
  22822. * @type {BABYLON.Observable}
  22823. */
  22824. this.onDisposeObservable = new BABYLON.Observable();
  22825. /**
  22826. * An event triggered when the material is bound.
  22827. * @type {BABYLON.Observable}
  22828. */
  22829. this.onBindObservable = new BABYLON.Observable();
  22830. /**
  22831. * An event triggered when the material is unbound.
  22832. * @type {BABYLON.Observable}
  22833. */
  22834. this.onUnBindObservable = new BABYLON.Observable();
  22835. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  22836. this.disableDepthWrite = false;
  22837. this._fogEnabled = true;
  22838. this.pointSize = 1.0;
  22839. this.zOffset = 0;
  22840. this._wasPreviouslyReady = false;
  22841. this._fillMode = Material.TriangleFillMode;
  22842. this.name = name;
  22843. this.id = name;
  22844. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  22845. if (this._scene.useRightHandedSystem) {
  22846. this.sideOrientation = Material.ClockWiseSideOrientation;
  22847. }
  22848. else {
  22849. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  22850. }
  22851. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  22852. this._useUBO = this.getScene().getEngine().webGLVersion > 1;
  22853. if (!doNotAdd) {
  22854. this._scene.materials.push(this);
  22855. }
  22856. }
  22857. Object.defineProperty(Material, "TriangleFillMode", {
  22858. get: function () {
  22859. return Material._TriangleFillMode;
  22860. },
  22861. enumerable: true,
  22862. configurable: true
  22863. });
  22864. Object.defineProperty(Material, "WireFrameFillMode", {
  22865. get: function () {
  22866. return Material._WireFrameFillMode;
  22867. },
  22868. enumerable: true,
  22869. configurable: true
  22870. });
  22871. Object.defineProperty(Material, "PointFillMode", {
  22872. get: function () {
  22873. return Material._PointFillMode;
  22874. },
  22875. enumerable: true,
  22876. configurable: true
  22877. });
  22878. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  22879. get: function () {
  22880. return Material._ClockWiseSideOrientation;
  22881. },
  22882. enumerable: true,
  22883. configurable: true
  22884. });
  22885. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  22886. get: function () {
  22887. return Material._CounterClockWiseSideOrientation;
  22888. },
  22889. enumerable: true,
  22890. configurable: true
  22891. });
  22892. Object.defineProperty(Material, "TextureDirtyFlag", {
  22893. get: function () {
  22894. return Material._TextureDirtyFlag;
  22895. },
  22896. enumerable: true,
  22897. configurable: true
  22898. });
  22899. Object.defineProperty(Material, "LightDirtyFlag", {
  22900. get: function () {
  22901. return Material._LightDirtyFlag;
  22902. },
  22903. enumerable: true,
  22904. configurable: true
  22905. });
  22906. Object.defineProperty(Material, "FresnelDirtyFlag", {
  22907. get: function () {
  22908. return Material._FresnelDirtyFlag;
  22909. },
  22910. enumerable: true,
  22911. configurable: true
  22912. });
  22913. Object.defineProperty(Material, "AttributesDirtyFlag", {
  22914. get: function () {
  22915. return Material._AttributesDirtyFlag;
  22916. },
  22917. enumerable: true,
  22918. configurable: true
  22919. });
  22920. Object.defineProperty(Material, "MiscDirtyFlag", {
  22921. get: function () {
  22922. return Material._MiscDirtyFlag;
  22923. },
  22924. enumerable: true,
  22925. configurable: true
  22926. });
  22927. Object.defineProperty(Material.prototype, "backFaceCulling", {
  22928. get: function () {
  22929. return this._backFaceCulling;
  22930. },
  22931. set: function (value) {
  22932. if (this._backFaceCulling === value) {
  22933. return;
  22934. }
  22935. this._backFaceCulling = value;
  22936. this.markAsDirty(Material.TextureDirtyFlag);
  22937. },
  22938. enumerable: true,
  22939. configurable: true
  22940. });
  22941. Object.defineProperty(Material.prototype, "onDispose", {
  22942. set: function (callback) {
  22943. if (this._onDisposeObserver) {
  22944. this.onDisposeObservable.remove(this._onDisposeObserver);
  22945. }
  22946. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  22947. },
  22948. enumerable: true,
  22949. configurable: true
  22950. });
  22951. Object.defineProperty(Material.prototype, "onBind", {
  22952. set: function (callback) {
  22953. if (this._onBindObserver) {
  22954. this.onBindObservable.remove(this._onBindObserver);
  22955. }
  22956. this._onBindObserver = this.onBindObservable.add(callback);
  22957. },
  22958. enumerable: true,
  22959. configurable: true
  22960. });
  22961. Object.defineProperty(Material.prototype, "fogEnabled", {
  22962. get: function () {
  22963. return this._fogEnabled;
  22964. },
  22965. set: function (value) {
  22966. if (this._fogEnabled === value) {
  22967. return;
  22968. }
  22969. this._fogEnabled = value;
  22970. this.markAsDirty(Material.MiscDirtyFlag);
  22971. },
  22972. enumerable: true,
  22973. configurable: true
  22974. });
  22975. Object.defineProperty(Material.prototype, "wireframe", {
  22976. get: function () {
  22977. return this._fillMode === Material.WireFrameFillMode;
  22978. },
  22979. set: function (value) {
  22980. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  22981. },
  22982. enumerable: true,
  22983. configurable: true
  22984. });
  22985. Object.defineProperty(Material.prototype, "pointsCloud", {
  22986. get: function () {
  22987. return this._fillMode === Material.PointFillMode;
  22988. },
  22989. set: function (value) {
  22990. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  22991. },
  22992. enumerable: true,
  22993. configurable: true
  22994. });
  22995. Object.defineProperty(Material.prototype, "fillMode", {
  22996. get: function () {
  22997. return this._fillMode;
  22998. },
  22999. set: function (value) {
  23000. if (this._fillMode === value) {
  23001. return;
  23002. }
  23003. this._fillMode = value;
  23004. this.markAsDirty(Material.MiscDirtyFlag);
  23005. },
  23006. enumerable: true,
  23007. configurable: true
  23008. });
  23009. /**
  23010. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  23011. * subclasses should override adding information pertainent to themselves
  23012. */
  23013. Material.prototype.toString = function (fullDetails) {
  23014. var ret = "Name: " + this.name;
  23015. if (fullDetails) {
  23016. }
  23017. return ret;
  23018. };
  23019. /**
  23020. * Child classes can use it to update shaders
  23021. */
  23022. Material.prototype.markAsDirty = function (flag) {
  23023. };
  23024. Material.prototype.getClassName = function () {
  23025. return "Material";
  23026. };
  23027. Object.defineProperty(Material.prototype, "isFrozen", {
  23028. get: function () {
  23029. return this.checkReadyOnlyOnce;
  23030. },
  23031. enumerable: true,
  23032. configurable: true
  23033. });
  23034. Material.prototype.freeze = function () {
  23035. this.checkReadyOnlyOnce = true;
  23036. };
  23037. Material.prototype.unfreeze = function () {
  23038. this.checkReadyOnlyOnce = false;
  23039. };
  23040. Material.prototype.isReady = function (mesh, useInstances) {
  23041. return true;
  23042. };
  23043. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  23044. return false;
  23045. };
  23046. Material.prototype.getEffect = function () {
  23047. return this._effect;
  23048. };
  23049. Material.prototype.getScene = function () {
  23050. return this._scene;
  23051. };
  23052. Material.prototype.needAlphaBlending = function () {
  23053. return (this.alpha < 1.0);
  23054. };
  23055. Material.prototype.needAlphaTesting = function () {
  23056. return false;
  23057. };
  23058. Material.prototype.getAlphaTestTexture = function () {
  23059. return null;
  23060. };
  23061. Material.prototype.markDirty = function () {
  23062. this._wasPreviouslyReady = false;
  23063. };
  23064. Material.prototype._preBind = function (effect) {
  23065. var engine = this._scene.getEngine();
  23066. var reverse = this.sideOrientation === Material.ClockWiseSideOrientation;
  23067. engine.enableEffect(effect ? effect : this._effect);
  23068. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  23069. };
  23070. Material.prototype.bind = function (world, mesh) {
  23071. };
  23072. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  23073. };
  23074. Material.prototype.bindOnlyWorldMatrix = function (world) {
  23075. };
  23076. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  23077. sceneUbo.bindToEffect(effect, "Scene");
  23078. };
  23079. Material.prototype.bindView = function (effect) {
  23080. if (!this._useUBO) {
  23081. effect.setMatrix("view", this.getScene().getViewMatrix());
  23082. }
  23083. else {
  23084. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  23085. }
  23086. };
  23087. Material.prototype.bindViewProjection = function (effect) {
  23088. if (!this._useUBO) {
  23089. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  23090. }
  23091. else {
  23092. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  23093. }
  23094. };
  23095. Material.prototype._afterBind = function (mesh) {
  23096. this._scene._cachedMaterial = this;
  23097. this.onBindObservable.notifyObservers(mesh);
  23098. if (this.disableDepthWrite) {
  23099. var engine = this._scene.getEngine();
  23100. this._cachedDepthWriteState = engine.getDepthWrite();
  23101. engine.setDepthWrite(false);
  23102. }
  23103. };
  23104. Material.prototype.unbind = function () {
  23105. this.onUnBindObservable.notifyObservers(this);
  23106. if (this.disableDepthWrite) {
  23107. var engine = this._scene.getEngine();
  23108. engine.setDepthWrite(this._cachedDepthWriteState);
  23109. }
  23110. };
  23111. Material.prototype.clone = function (name) {
  23112. return null;
  23113. };
  23114. Material.prototype.getBindedMeshes = function () {
  23115. var result = new Array();
  23116. for (var index = 0; index < this._scene.meshes.length; index++) {
  23117. var mesh = this._scene.meshes[index];
  23118. if (mesh.material === this) {
  23119. result.push(mesh);
  23120. }
  23121. }
  23122. return result;
  23123. };
  23124. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  23125. // Animations
  23126. this.getScene().stopAnimation(this);
  23127. // Remove from scene
  23128. var index = this._scene.materials.indexOf(this);
  23129. if (index >= 0) {
  23130. this._scene.materials.splice(index, 1);
  23131. }
  23132. // Remove from meshes
  23133. for (index = 0; index < this._scene.meshes.length; index++) {
  23134. var mesh = this._scene.meshes[index];
  23135. if (mesh.material === this) {
  23136. mesh.material = null;
  23137. if (mesh.geometry) {
  23138. var geometry = mesh.geometry;
  23139. if (this.storeEffectOnSubMeshes) {
  23140. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  23141. var subMesh = _a[_i];
  23142. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  23143. }
  23144. }
  23145. else {
  23146. geometry._releaseVertexArrayObject(this._effect);
  23147. }
  23148. }
  23149. }
  23150. }
  23151. this._uniformBuffer.dispose();
  23152. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  23153. if (forceDisposeEffect && this._effect) {
  23154. if (this.storeEffectOnSubMeshes) {
  23155. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  23156. var subMesh = _c[_b];
  23157. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  23158. }
  23159. }
  23160. else {
  23161. this._scene.getEngine()._releaseEffect(this._effect);
  23162. }
  23163. this._effect = null;
  23164. }
  23165. // Callback
  23166. this.onDisposeObservable.notifyObservers(this);
  23167. this.onDisposeObservable.clear();
  23168. this.onBindObservable.clear();
  23169. this.onUnBindObservable.clear();
  23170. };
  23171. Material.prototype.serialize = function () {
  23172. return BABYLON.SerializationHelper.Serialize(this);
  23173. };
  23174. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  23175. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  23176. multiMaterial.id = parsedMultiMaterial.id;
  23177. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  23178. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  23179. var subMatId = parsedMultiMaterial.materials[matIndex];
  23180. if (subMatId) {
  23181. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  23182. }
  23183. else {
  23184. multiMaterial.subMaterials.push(null);
  23185. }
  23186. }
  23187. return multiMaterial;
  23188. };
  23189. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  23190. if (!parsedMaterial.customType) {
  23191. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  23192. }
  23193. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  23194. return materialType.Parse(parsedMaterial, scene, rootUrl);
  23195. ;
  23196. };
  23197. return Material;
  23198. }());
  23199. Material._TriangleFillMode = 0;
  23200. Material._WireFrameFillMode = 1;
  23201. Material._PointFillMode = 2;
  23202. Material._ClockWiseSideOrientation = 0;
  23203. Material._CounterClockWiseSideOrientation = 1;
  23204. Material._TextureDirtyFlag = 0;
  23205. Material._LightDirtyFlag = 1;
  23206. Material._FresnelDirtyFlag = 2;
  23207. Material._AttributesDirtyFlag = 4;
  23208. Material._MiscDirtyFlag = 8;
  23209. __decorate([
  23210. BABYLON.serialize()
  23211. ], Material.prototype, "id", void 0);
  23212. __decorate([
  23213. BABYLON.serialize()
  23214. ], Material.prototype, "name", void 0);
  23215. __decorate([
  23216. BABYLON.serialize()
  23217. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  23218. __decorate([
  23219. BABYLON.serialize()
  23220. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  23221. __decorate([
  23222. BABYLON.serialize()
  23223. ], Material.prototype, "state", void 0);
  23224. __decorate([
  23225. BABYLON.serialize()
  23226. ], Material.prototype, "alpha", void 0);
  23227. __decorate([
  23228. BABYLON.serialize("backFaceCulling")
  23229. ], Material.prototype, "_backFaceCulling", void 0);
  23230. __decorate([
  23231. BABYLON.serialize()
  23232. ], Material.prototype, "sideOrientation", void 0);
  23233. __decorate([
  23234. BABYLON.serialize()
  23235. ], Material.prototype, "alphaMode", void 0);
  23236. __decorate([
  23237. BABYLON.serialize()
  23238. ], Material.prototype, "disableDepthWrite", void 0);
  23239. __decorate([
  23240. BABYLON.serialize("fogEnabled")
  23241. ], Material.prototype, "_fogEnabled", void 0);
  23242. __decorate([
  23243. BABYLON.serialize()
  23244. ], Material.prototype, "pointSize", void 0);
  23245. __decorate([
  23246. BABYLON.serialize()
  23247. ], Material.prototype, "zOffset", void 0);
  23248. __decorate([
  23249. BABYLON.serialize()
  23250. ], Material.prototype, "wireframe", null);
  23251. __decorate([
  23252. BABYLON.serialize()
  23253. ], Material.prototype, "pointsCloud", null);
  23254. __decorate([
  23255. BABYLON.serialize()
  23256. ], Material.prototype, "fillMode", null);
  23257. BABYLON.Material = Material;
  23258. })(BABYLON || (BABYLON = {}));
  23259. //# sourceMappingURL=babylon.material.js.map
  23260. var BABYLON;
  23261. (function (BABYLON) {
  23262. var UniformBuffer = (function () {
  23263. /**
  23264. * Uniform buffer objects.
  23265. *
  23266. * Handles blocks of uniform on the GPU.
  23267. *
  23268. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  23269. *
  23270. * For more information, please refer to :
  23271. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  23272. */
  23273. function UniformBuffer(engine, data, dynamic) {
  23274. this._engine = engine;
  23275. this._noUBO = engine.webGLVersion === 1;
  23276. this._dynamic = dynamic;
  23277. this._data = data || [];
  23278. this._uniformLocations = {};
  23279. this._uniformSizes = {};
  23280. this._uniformLocationPointer = 0;
  23281. this._needSync = false;
  23282. if (this._noUBO) {
  23283. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  23284. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  23285. this.updateFloat = this._updateFloatForEffect;
  23286. this.updateFloat2 = this._updateFloat2ForEffect;
  23287. this.updateFloat3 = this._updateFloat3ForEffect;
  23288. this.updateFloat4 = this._updateFloat4ForEffect;
  23289. this.updateMatrix = this._updateMatrixForEffect;
  23290. this.updateVector3 = this._updateVector3ForEffect;
  23291. this.updateVector4 = this._updateVector4ForEffect;
  23292. this.updateColor3 = this._updateColor3ForEffect;
  23293. this.updateColor4 = this._updateColor4ForEffect;
  23294. }
  23295. else {
  23296. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  23297. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  23298. this.updateFloat = this._updateFloatForUniform;
  23299. this.updateFloat2 = this._updateFloat2ForUniform;
  23300. this.updateFloat3 = this._updateFloat3ForUniform;
  23301. this.updateFloat4 = this._updateFloat4ForUniform;
  23302. this.updateMatrix = this._updateMatrixForUniform;
  23303. this.updateVector3 = this._updateVector3ForUniform;
  23304. this.updateVector4 = this._updateVector4ForUniform;
  23305. this.updateColor3 = this._updateColor3ForUniform;
  23306. this.updateColor4 = this._updateColor4ForUniform;
  23307. }
  23308. }
  23309. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  23310. // Properties
  23311. /**
  23312. * Indicates if the buffer is using the WebGL2 UBO implementation,
  23313. * or just falling back on setUniformXXX calls.
  23314. */
  23315. get: function () {
  23316. return !this._noUBO;
  23317. },
  23318. enumerable: true,
  23319. configurable: true
  23320. });
  23321. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  23322. /**
  23323. * Indicates if the WebGL underlying uniform buffer is in sync
  23324. * with the javascript cache data.
  23325. */
  23326. get: function () {
  23327. return !this._needSync;
  23328. },
  23329. enumerable: true,
  23330. configurable: true
  23331. });
  23332. /**
  23333. * Indicates if the WebGL underlying uniform buffer is dynamic.
  23334. * Also, a dynamic UniformBuffer will disable cache verification and always
  23335. * update the underlying WebGL uniform buffer to the GPU.
  23336. */
  23337. UniformBuffer.prototype.isDynamic = function () {
  23338. return this._dynamic;
  23339. };
  23340. /**
  23341. * The data cache on JS side.
  23342. */
  23343. UniformBuffer.prototype.getData = function () {
  23344. return this._bufferData;
  23345. };
  23346. /**
  23347. * The underlying WebGL Uniform buffer.
  23348. */
  23349. UniformBuffer.prototype.getBuffer = function () {
  23350. return this._buffer;
  23351. };
  23352. /**
  23353. * std140 layout specifies how to align data within an UBO structure.
  23354. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  23355. * for specs.
  23356. */
  23357. UniformBuffer.prototype._fillAlignment = function (size) {
  23358. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  23359. // and 4x4 matrices
  23360. // TODO : change if other types are used
  23361. var alignment;
  23362. if (size <= 2) {
  23363. alignment = size;
  23364. }
  23365. else {
  23366. alignment = 4;
  23367. }
  23368. if ((this._uniformLocationPointer % alignment) !== 0) {
  23369. var oldPointer = this._uniformLocationPointer;
  23370. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  23371. var diff = this._uniformLocationPointer - oldPointer;
  23372. for (var i = 0; i < diff; i++) {
  23373. this._data.push(0);
  23374. }
  23375. }
  23376. };
  23377. /**
  23378. * Adds an uniform in the buffer.
  23379. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  23380. * for the layout to be correct !
  23381. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  23382. * @param {number|number[]} size Data size, or data directly.
  23383. */
  23384. UniformBuffer.prototype.addUniform = function (name, size) {
  23385. if (this._noUBO) {
  23386. return;
  23387. }
  23388. if (this._uniformLocations[name] !== undefined) {
  23389. // Already existing uniform
  23390. return;
  23391. }
  23392. // This function must be called in the order of the shader layout !
  23393. // size can be the size of the uniform, or data directly
  23394. var data;
  23395. if (size instanceof Array) {
  23396. data = size;
  23397. size = data.length;
  23398. }
  23399. else {
  23400. size = size;
  23401. data = [];
  23402. // Fill with zeros
  23403. for (var i = 0; i < size; i++) {
  23404. data.push(0);
  23405. }
  23406. }
  23407. this._fillAlignment(size);
  23408. this._uniformSizes[name] = size;
  23409. this._uniformLocations[name] = this._uniformLocationPointer;
  23410. this._uniformLocationPointer += size;
  23411. for (var i = 0; i < size; i++) {
  23412. this._data.push(data[i]);
  23413. }
  23414. this._needSync = true;
  23415. };
  23416. /**
  23417. * Wrapper for addUniform.
  23418. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  23419. * @param {Matrix} mat A 4x4 matrix.
  23420. */
  23421. UniformBuffer.prototype.addMatrix = function (name, mat) {
  23422. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  23423. };
  23424. /**
  23425. * Wrapper for addUniform.
  23426. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  23427. * @param {number} x
  23428. * @param {number} y
  23429. */
  23430. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  23431. var temp = [x, y];
  23432. this.addUniform(name, temp);
  23433. };
  23434. /**
  23435. * Wrapper for addUniform.
  23436. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  23437. * @param {number} x
  23438. * @param {number} y
  23439. * @param {number} z
  23440. */
  23441. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  23442. var temp = [x, y, z];
  23443. this.addUniform(name, temp);
  23444. };
  23445. /**
  23446. * Wrapper for addUniform.
  23447. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  23448. * @param {Color3} color
  23449. */
  23450. UniformBuffer.prototype.addColor3 = function (name, color) {
  23451. var temp = [];
  23452. color.toArray(temp);
  23453. this.addUniform(name, temp);
  23454. };
  23455. /**
  23456. * Wrapper for addUniform.
  23457. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  23458. * @param {Color3} color
  23459. * @param {number} alpha
  23460. */
  23461. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  23462. var temp = [];
  23463. color.toArray(temp);
  23464. temp.push(alpha);
  23465. this.addUniform(name, temp);
  23466. };
  23467. /**
  23468. * Wrapper for addUniform.
  23469. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  23470. * @param {Vector3} vector
  23471. */
  23472. UniformBuffer.prototype.addVector3 = function (name, vector) {
  23473. var temp = [];
  23474. vector.toArray(temp);
  23475. this.addUniform(name, temp);
  23476. };
  23477. /**
  23478. * Wrapper for addUniform.
  23479. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  23480. */
  23481. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  23482. this.addUniform(name, 12);
  23483. };
  23484. /**
  23485. * Wrapper for addUniform.
  23486. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  23487. */
  23488. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  23489. this.addUniform(name, 8);
  23490. };
  23491. /**
  23492. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  23493. */
  23494. UniformBuffer.prototype.create = function () {
  23495. if (this._noUBO) {
  23496. return;
  23497. }
  23498. if (this._buffer) {
  23499. return; // nothing to do
  23500. }
  23501. // See spec, alignment must be filled as a vec4
  23502. this._fillAlignment(4);
  23503. this._bufferData = new Float32Array(this._data);
  23504. if (this._dynamic) {
  23505. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  23506. }
  23507. else {
  23508. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  23509. }
  23510. this._needSync = true;
  23511. };
  23512. /**
  23513. * Updates the WebGL Uniform Buffer on the GPU.
  23514. * If the `dynamic` flag is set to true, no cache comparison is done.
  23515. * Otherwise, the buffer will be updated only if the cache differs.
  23516. */
  23517. UniformBuffer.prototype.update = function () {
  23518. if (!this._buffer) {
  23519. this.create();
  23520. return;
  23521. }
  23522. if (!this._dynamic && !this._needSync) {
  23523. return;
  23524. }
  23525. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  23526. this._needSync = false;
  23527. };
  23528. /**
  23529. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  23530. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  23531. * @param {number[]|Float32Array} data Flattened data
  23532. * @param {number} size Size of the data.
  23533. */
  23534. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  23535. var location = this._uniformLocations[uniformName];
  23536. if (location === undefined) {
  23537. if (this._buffer) {
  23538. // Cannot add an uniform if the buffer is already created
  23539. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  23540. return;
  23541. }
  23542. this.addUniform(uniformName, size);
  23543. location = this._uniformLocations[uniformName];
  23544. }
  23545. if (!this._buffer) {
  23546. this.create();
  23547. }
  23548. if (!this._dynamic) {
  23549. // Cache for static uniform buffers
  23550. var changed = false;
  23551. for (var i = 0; i < size; i++) {
  23552. if (this._bufferData[location + i] !== data[i]) {
  23553. changed = true;
  23554. this._bufferData[location + i] = data[i];
  23555. }
  23556. }
  23557. this._needSync = this._needSync || changed;
  23558. }
  23559. else {
  23560. // No cache for dynamic
  23561. for (var i = 0; i < size; i++) {
  23562. this._bufferData[location + i] = data[i];
  23563. }
  23564. }
  23565. };
  23566. // Update methods
  23567. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  23568. // To match std140, matrix must be realigned
  23569. for (var i = 0; i < 3; i++) {
  23570. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  23571. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  23572. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  23573. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  23574. }
  23575. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  23576. };
  23577. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  23578. this._currentEffect.setMatrix3x3(name, matrix);
  23579. };
  23580. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  23581. this._currentEffect.setMatrix2x2(name, matrix);
  23582. };
  23583. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  23584. // To match std140, matrix must be realigned
  23585. for (var i = 0; i < 2; i++) {
  23586. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  23587. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  23588. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  23589. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  23590. }
  23591. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  23592. };
  23593. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  23594. this._currentEffect.setFloat(name, x);
  23595. };
  23596. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  23597. UniformBuffer._tempBuffer[0] = x;
  23598. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  23599. };
  23600. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y) {
  23601. this._currentEffect.setFloat2(name, x, y);
  23602. };
  23603. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y) {
  23604. UniformBuffer._tempBuffer[0] = x;
  23605. UniformBuffer._tempBuffer[1] = y;
  23606. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  23607. };
  23608. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  23609. if (suffix === void 0) { suffix = ""; }
  23610. this._currentEffect.setFloat3(name + suffix, x, y, z);
  23611. };
  23612. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  23613. if (suffix === void 0) { suffix = ""; }
  23614. UniformBuffer._tempBuffer[0] = x;
  23615. UniformBuffer._tempBuffer[1] = y;
  23616. UniformBuffer._tempBuffer[2] = z;
  23617. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  23618. };
  23619. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  23620. if (suffix === void 0) { suffix = ""; }
  23621. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  23622. };
  23623. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  23624. if (suffix === void 0) { suffix = ""; }
  23625. UniformBuffer._tempBuffer[0] = x;
  23626. UniformBuffer._tempBuffer[1] = y;
  23627. UniformBuffer._tempBuffer[2] = z;
  23628. UniformBuffer._tempBuffer[3] = w;
  23629. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  23630. };
  23631. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  23632. this._currentEffect.setMatrix(name, mat);
  23633. };
  23634. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  23635. this.updateUniform(name, mat.toArray(), 16);
  23636. };
  23637. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  23638. this._currentEffect.setVector3(name, vector);
  23639. };
  23640. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  23641. vector.toArray(UniformBuffer._tempBuffer);
  23642. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  23643. };
  23644. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  23645. this._currentEffect.setVector4(name, vector);
  23646. };
  23647. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  23648. vector.toArray(UniformBuffer._tempBuffer);
  23649. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  23650. };
  23651. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  23652. if (suffix === void 0) { suffix = ""; }
  23653. this._currentEffect.setColor3(name + suffix, color);
  23654. };
  23655. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  23656. if (suffix === void 0) { suffix = ""; }
  23657. color.toArray(UniformBuffer._tempBuffer);
  23658. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  23659. };
  23660. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  23661. if (suffix === void 0) { suffix = ""; }
  23662. this._currentEffect.setColor4(name + suffix, color, alpha);
  23663. };
  23664. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  23665. if (suffix === void 0) { suffix = ""; }
  23666. color.toArray(UniformBuffer._tempBuffer);
  23667. UniformBuffer._tempBuffer[3] = alpha;
  23668. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  23669. };
  23670. /**
  23671. * Sets a sampler uniform on the effect.
  23672. * @param {string} name Name of the sampler.
  23673. * @param {Texture} texture
  23674. */
  23675. UniformBuffer.prototype.setTexture = function (name, texture) {
  23676. this._currentEffect.setTexture(name, texture);
  23677. };
  23678. /**
  23679. * Directly updates the value of the uniform in the cache AND on the GPU.
  23680. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  23681. * @param {number[]|Float32Array} data Flattened data
  23682. */
  23683. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  23684. this.updateUniform(uniformName, data, data.length);
  23685. this.update();
  23686. };
  23687. /**
  23688. * Binds this uniform buffer to an effect.
  23689. * @param {Effect} effect
  23690. * @param {string} name Name of the uniform block in the shader.
  23691. */
  23692. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  23693. this._currentEffect = effect;
  23694. if (this._noUBO) {
  23695. return;
  23696. }
  23697. effect.bindUniformBuffer(this._buffer, name);
  23698. };
  23699. /**
  23700. * Disposes the uniform buffer.
  23701. */
  23702. UniformBuffer.prototype.dispose = function () {
  23703. if (!this._buffer) {
  23704. return;
  23705. }
  23706. if (this._engine._releaseBuffer(this._buffer)) {
  23707. this._buffer = null;
  23708. }
  23709. };
  23710. return UniformBuffer;
  23711. }());
  23712. // Pool for avoiding memory leaks
  23713. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  23714. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  23715. BABYLON.UniformBuffer = UniformBuffer;
  23716. })(BABYLON || (BABYLON = {}));
  23717. //# sourceMappingURL=babylon.uniformBuffer.js.map
  23718. var BABYLON;
  23719. (function (BABYLON) {
  23720. var PushMaterial = (function (_super) {
  23721. __extends(PushMaterial, _super);
  23722. function PushMaterial(name, scene) {
  23723. var _this = _super.call(this, name, scene) || this;
  23724. _this.storeEffectOnSubMeshes = true;
  23725. return _this;
  23726. }
  23727. PushMaterial.prototype.getEffect = function () {
  23728. return this._activeEffect;
  23729. };
  23730. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  23731. if (!mesh) {
  23732. return false;
  23733. }
  23734. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  23735. return true;
  23736. }
  23737. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  23738. };
  23739. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  23740. this._activeEffect.setMatrix("world", world);
  23741. };
  23742. PushMaterial.prototype.bind = function (world, mesh) {
  23743. if (!mesh) {
  23744. return;
  23745. }
  23746. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  23747. };
  23748. PushMaterial.prototype._afterBind = function (mesh, effect) {
  23749. _super.prototype._afterBind.call(this, mesh);
  23750. this.getScene()._cachedEffect = effect;
  23751. };
  23752. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  23753. if (visibility === void 0) { visibility = 0; }
  23754. return scene.isCachedMaterialValid(this, effect, visibility);
  23755. };
  23756. PushMaterial.prototype.markAsDirty = function (flag) {
  23757. if (flag & BABYLON.Material.TextureDirtyFlag) {
  23758. this._markAllSubMeshesAsTexturesDirty();
  23759. }
  23760. if (flag & BABYLON.Material.LightDirtyFlag) {
  23761. this._markAllSubMeshesAsLightsDirty();
  23762. }
  23763. if (flag & BABYLON.Material.FresnelDirtyFlag) {
  23764. this._markAllSubMeshesAsFresnelDirty();
  23765. }
  23766. if (flag & BABYLON.Material.AttributesDirtyFlag) {
  23767. this._markAllSubMeshesAsAttributesDirty();
  23768. }
  23769. if (flag & BABYLON.Material.MiscDirtyFlag) {
  23770. this._markAllSubMeshesAsMiscDirty();
  23771. }
  23772. };
  23773. PushMaterial.prototype._markAllSubMeshesAsDirty = function (func) {
  23774. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  23775. var mesh = _a[_i];
  23776. if (!mesh.subMeshes) {
  23777. continue;
  23778. }
  23779. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  23780. var subMesh = _c[_b];
  23781. if (subMesh.getMaterial() !== this) {
  23782. continue;
  23783. }
  23784. if (!subMesh._materialDefines) {
  23785. return;
  23786. }
  23787. func(subMesh._materialDefines);
  23788. }
  23789. }
  23790. };
  23791. PushMaterial.prototype._markAllSubMeshesAsTexturesDirty = function () {
  23792. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  23793. };
  23794. PushMaterial.prototype._markAllSubMeshesAsFresnelDirty = function () {
  23795. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  23796. };
  23797. PushMaterial.prototype._markAllSubMeshesAsLightsDirty = function () {
  23798. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  23799. };
  23800. PushMaterial.prototype._markAllSubMeshesAsAttributesDirty = function () {
  23801. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  23802. };
  23803. PushMaterial.prototype._markAllSubMeshesAsMiscDirty = function () {
  23804. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  23805. };
  23806. return PushMaterial;
  23807. }(BABYLON.Material));
  23808. BABYLON.PushMaterial = PushMaterial;
  23809. })(BABYLON || (BABYLON = {}));
  23810. //# sourceMappingURL=babylon.pushMaterial.js.map
  23811. var BABYLON;
  23812. (function (BABYLON) {
  23813. var VertexData = (function () {
  23814. function VertexData() {
  23815. }
  23816. VertexData.prototype.set = function (data, kind) {
  23817. switch (kind) {
  23818. case BABYLON.VertexBuffer.PositionKind:
  23819. this.positions = data;
  23820. break;
  23821. case BABYLON.VertexBuffer.NormalKind:
  23822. this.normals = data;
  23823. break;
  23824. case BABYLON.VertexBuffer.TangentKind:
  23825. this.tangents = data;
  23826. break;
  23827. case BABYLON.VertexBuffer.UVKind:
  23828. this.uvs = data;
  23829. break;
  23830. case BABYLON.VertexBuffer.UV2Kind:
  23831. this.uvs2 = data;
  23832. break;
  23833. case BABYLON.VertexBuffer.UV3Kind:
  23834. this.uvs3 = data;
  23835. break;
  23836. case BABYLON.VertexBuffer.UV4Kind:
  23837. this.uvs4 = data;
  23838. break;
  23839. case BABYLON.VertexBuffer.UV5Kind:
  23840. this.uvs5 = data;
  23841. break;
  23842. case BABYLON.VertexBuffer.UV6Kind:
  23843. this.uvs6 = data;
  23844. break;
  23845. case BABYLON.VertexBuffer.ColorKind:
  23846. this.colors = data;
  23847. break;
  23848. case BABYLON.VertexBuffer.MatricesIndicesKind:
  23849. this.matricesIndices = data;
  23850. break;
  23851. case BABYLON.VertexBuffer.MatricesWeightsKind:
  23852. this.matricesWeights = data;
  23853. break;
  23854. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  23855. this.matricesIndicesExtra = data;
  23856. break;
  23857. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  23858. this.matricesWeightsExtra = data;
  23859. break;
  23860. }
  23861. };
  23862. /**
  23863. * Associates the vertexData to the passed Mesh.
  23864. * Sets it as updatable or not (default `false`).
  23865. * Returns the VertexData.
  23866. */
  23867. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  23868. this._applyTo(mesh, updatable);
  23869. return this;
  23870. };
  23871. /**
  23872. * Associates the vertexData to the passed Geometry.
  23873. * Sets it as updatable or not (default `false`).
  23874. * Returns the VertexData.
  23875. */
  23876. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  23877. this._applyTo(geometry, updatable);
  23878. return this;
  23879. };
  23880. /**
  23881. * Updates the associated mesh.
  23882. * Returns the VertexData.
  23883. */
  23884. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  23885. this._update(mesh);
  23886. return this;
  23887. };
  23888. /**
  23889. * Updates the associated geometry.
  23890. * Returns the VertexData.
  23891. */
  23892. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  23893. this._update(geometry);
  23894. return this;
  23895. };
  23896. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  23897. if (this.positions) {
  23898. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  23899. }
  23900. if (this.normals) {
  23901. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  23902. }
  23903. if (this.tangents) {
  23904. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  23905. }
  23906. if (this.uvs) {
  23907. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  23908. }
  23909. if (this.uvs2) {
  23910. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  23911. }
  23912. if (this.uvs3) {
  23913. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  23914. }
  23915. if (this.uvs4) {
  23916. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  23917. }
  23918. if (this.uvs5) {
  23919. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  23920. }
  23921. if (this.uvs6) {
  23922. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  23923. }
  23924. if (this.colors) {
  23925. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  23926. }
  23927. if (this.matricesIndices) {
  23928. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  23929. }
  23930. if (this.matricesWeights) {
  23931. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  23932. }
  23933. if (this.matricesIndicesExtra) {
  23934. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  23935. }
  23936. if (this.matricesWeightsExtra) {
  23937. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  23938. }
  23939. if (this.indices) {
  23940. meshOrGeometry.setIndices(this.indices);
  23941. }
  23942. return this;
  23943. };
  23944. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  23945. if (this.positions) {
  23946. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  23947. }
  23948. if (this.normals) {
  23949. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  23950. }
  23951. if (this.tangents) {
  23952. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  23953. }
  23954. if (this.uvs) {
  23955. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  23956. }
  23957. if (this.uvs2) {
  23958. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  23959. }
  23960. if (this.uvs3) {
  23961. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  23962. }
  23963. if (this.uvs4) {
  23964. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  23965. }
  23966. if (this.uvs5) {
  23967. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  23968. }
  23969. if (this.uvs6) {
  23970. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  23971. }
  23972. if (this.colors) {
  23973. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  23974. }
  23975. if (this.matricesIndices) {
  23976. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  23977. }
  23978. if (this.matricesWeights) {
  23979. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  23980. }
  23981. if (this.matricesIndicesExtra) {
  23982. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  23983. }
  23984. if (this.matricesWeightsExtra) {
  23985. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  23986. }
  23987. if (this.indices) {
  23988. meshOrGeometry.setIndices(this.indices);
  23989. }
  23990. return this;
  23991. };
  23992. /**
  23993. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  23994. * Returns the VertexData.
  23995. */
  23996. VertexData.prototype.transform = function (matrix) {
  23997. var transformed = BABYLON.Vector3.Zero();
  23998. var index;
  23999. if (this.positions) {
  24000. var position = BABYLON.Vector3.Zero();
  24001. for (index = 0; index < this.positions.length; index += 3) {
  24002. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  24003. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  24004. this.positions[index] = transformed.x;
  24005. this.positions[index + 1] = transformed.y;
  24006. this.positions[index + 2] = transformed.z;
  24007. }
  24008. }
  24009. if (this.normals) {
  24010. var normal = BABYLON.Vector3.Zero();
  24011. for (index = 0; index < this.normals.length; index += 3) {
  24012. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  24013. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  24014. this.normals[index] = transformed.x;
  24015. this.normals[index + 1] = transformed.y;
  24016. this.normals[index + 2] = transformed.z;
  24017. }
  24018. }
  24019. if (this.tangents) {
  24020. var tangent = BABYLON.Vector4.Zero();
  24021. var tangentTransformed = BABYLON.Vector4.Zero();
  24022. for (index = 0; index < this.tangents.length; index += 4) {
  24023. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  24024. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  24025. this.tangents[index] = tangentTransformed.x;
  24026. this.tangents[index + 1] = tangentTransformed.y;
  24027. this.tangents[index + 2] = tangentTransformed.z;
  24028. this.tangents[index + 3] = tangentTransformed.w;
  24029. }
  24030. }
  24031. return this;
  24032. };
  24033. /**
  24034. * Merges the passed VertexData into the current one.
  24035. * Returns the modified VertexData.
  24036. */
  24037. VertexData.prototype.merge = function (other) {
  24038. if (other.indices) {
  24039. if (!this.indices) {
  24040. this.indices = [];
  24041. }
  24042. var offset = this.positions ? this.positions.length / 3 : 0;
  24043. for (var index = 0; index < other.indices.length; index++) {
  24044. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  24045. this.indices.push(other.indices[index] + offset);
  24046. }
  24047. }
  24048. this.positions = this._mergeElement(this.positions, other.positions);
  24049. this.normals = this._mergeElement(this.normals, other.normals);
  24050. this.tangents = this._mergeElement(this.tangents, other.tangents);
  24051. this.uvs = this._mergeElement(this.uvs, other.uvs);
  24052. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  24053. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  24054. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  24055. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  24056. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  24057. this.colors = this._mergeElement(this.colors, other.colors);
  24058. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  24059. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  24060. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  24061. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  24062. return this;
  24063. };
  24064. VertexData.prototype._mergeElement = function (source, other) {
  24065. if (!other)
  24066. return source;
  24067. if (!source)
  24068. return other;
  24069. var len = other.length + source.length;
  24070. var isSrcTypedArray = source instanceof Float32Array;
  24071. var isOthTypedArray = other instanceof Float32Array;
  24072. // use non-loop method when the source is Float32Array
  24073. if (isSrcTypedArray) {
  24074. var ret32 = new Float32Array(len);
  24075. ret32.set(source);
  24076. ret32.set(other, source.length);
  24077. return ret32;
  24078. // source is number[], when other is also use concat
  24079. }
  24080. else if (!isOthTypedArray) {
  24081. return source.concat(other);
  24082. // source is a number[], but other is a Float32Array, loop required
  24083. }
  24084. else {
  24085. var ret = source.slice(0); // copy source to a separate array
  24086. for (var i = 0, len = other.length; i < len; i++) {
  24087. ret.push(other[i]);
  24088. }
  24089. return ret;
  24090. }
  24091. };
  24092. /**
  24093. * Serializes the VertexData.
  24094. * Returns a serialized object.
  24095. */
  24096. VertexData.prototype.serialize = function () {
  24097. var serializationObject = this.serialize();
  24098. if (this.positions) {
  24099. serializationObject.positions = this.positions;
  24100. }
  24101. if (this.normals) {
  24102. serializationObject.normals = this.normals;
  24103. }
  24104. if (this.tangents) {
  24105. serializationObject.tangents = this.tangents;
  24106. }
  24107. if (this.uvs) {
  24108. serializationObject.uvs = this.uvs;
  24109. }
  24110. if (this.uvs2) {
  24111. serializationObject.uvs2 = this.uvs2;
  24112. }
  24113. if (this.uvs3) {
  24114. serializationObject.uvs3 = this.uvs3;
  24115. }
  24116. if (this.uvs4) {
  24117. serializationObject.uvs4 = this.uvs4;
  24118. }
  24119. if (this.uvs5) {
  24120. serializationObject.uvs5 = this.uvs5;
  24121. }
  24122. if (this.uvs6) {
  24123. serializationObject.uvs6 = this.uvs6;
  24124. }
  24125. if (this.colors) {
  24126. serializationObject.colors = this.colors;
  24127. }
  24128. if (this.matricesIndices) {
  24129. serializationObject.matricesIndices = this.matricesIndices;
  24130. serializationObject.matricesIndices._isExpanded = true;
  24131. }
  24132. if (this.matricesWeights) {
  24133. serializationObject.matricesWeights = this.matricesWeights;
  24134. }
  24135. if (this.matricesIndicesExtra) {
  24136. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  24137. serializationObject.matricesIndicesExtra._isExpanded = true;
  24138. }
  24139. if (this.matricesWeightsExtra) {
  24140. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  24141. }
  24142. serializationObject.indices = this.indices;
  24143. return serializationObject;
  24144. };
  24145. // Statics
  24146. /**
  24147. * Returns the object VertexData associated to the passed mesh.
  24148. */
  24149. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  24150. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  24151. };
  24152. /**
  24153. * Returns the object VertexData associated to the passed geometry.
  24154. */
  24155. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  24156. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  24157. };
  24158. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  24159. var result = new VertexData();
  24160. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  24161. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  24162. }
  24163. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  24164. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  24165. }
  24166. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  24167. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  24168. }
  24169. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  24170. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  24171. }
  24172. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  24173. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  24174. }
  24175. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  24176. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  24177. }
  24178. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  24179. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  24180. }
  24181. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  24182. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  24183. }
  24184. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  24185. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  24186. }
  24187. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  24188. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  24189. }
  24190. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  24191. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  24192. }
  24193. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  24194. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  24195. }
  24196. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  24197. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  24198. }
  24199. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  24200. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  24201. }
  24202. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  24203. return result;
  24204. };
  24205. /**
  24206. * Creates the vertexData of the Ribbon.
  24207. */
  24208. VertexData.CreateRibbon = function (options) {
  24209. var pathArray = options.pathArray;
  24210. var closeArray = options.closeArray || false;
  24211. var closePath = options.closePath || false;
  24212. var invertUV = options.invertUV || false;
  24213. var defaultOffset = Math.floor(pathArray[0].length / 2);
  24214. var offset = options.offset || defaultOffset;
  24215. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  24216. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24217. var customUV = options.uvs;
  24218. var customColors = options.colors;
  24219. var positions = [];
  24220. var indices = [];
  24221. var normals = [];
  24222. var uvs = [];
  24223. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  24224. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  24225. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  24226. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  24227. var minlg; // minimal length among all paths from pathArray
  24228. var lg = []; // array of path lengths : nb of vertex per path
  24229. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  24230. var p; // path iterator
  24231. var i; // point iterator
  24232. var j; // point iterator
  24233. // if single path in pathArray
  24234. if (pathArray.length < 2) {
  24235. var ar1 = [];
  24236. var ar2 = [];
  24237. for (i = 0; i < pathArray[0].length - offset; i++) {
  24238. ar1.push(pathArray[0][i]);
  24239. ar2.push(pathArray[0][i + offset]);
  24240. }
  24241. pathArray = [ar1, ar2];
  24242. }
  24243. // positions and horizontal distances (u)
  24244. var idc = 0;
  24245. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  24246. var path;
  24247. var l;
  24248. minlg = pathArray[0].length;
  24249. var vectlg;
  24250. var dist;
  24251. for (p = 0; p < pathArray.length; p++) {
  24252. uTotalDistance[p] = 0;
  24253. us[p] = [0];
  24254. path = pathArray[p];
  24255. l = path.length;
  24256. minlg = (minlg < l) ? minlg : l;
  24257. j = 0;
  24258. while (j < l) {
  24259. positions.push(path[j].x, path[j].y, path[j].z);
  24260. if (j > 0) {
  24261. vectlg = path[j].subtract(path[j - 1]).length();
  24262. dist = vectlg + uTotalDistance[p];
  24263. us[p].push(dist);
  24264. uTotalDistance[p] = dist;
  24265. }
  24266. j++;
  24267. }
  24268. if (closePath) {
  24269. j--;
  24270. positions.push(path[0].x, path[0].y, path[0].z);
  24271. vectlg = path[j].subtract(path[0]).length();
  24272. dist = vectlg + uTotalDistance[p];
  24273. us[p].push(dist);
  24274. uTotalDistance[p] = dist;
  24275. }
  24276. lg[p] = l + closePathCorr;
  24277. idx[p] = idc;
  24278. idc += (l + closePathCorr);
  24279. }
  24280. // vertical distances (v)
  24281. var path1;
  24282. var path2;
  24283. var vertex1;
  24284. var vertex2;
  24285. for (i = 0; i < minlg + closePathCorr; i++) {
  24286. vTotalDistance[i] = 0;
  24287. vs[i] = [0];
  24288. for (p = 0; p < pathArray.length - 1; p++) {
  24289. path1 = pathArray[p];
  24290. path2 = pathArray[p + 1];
  24291. if (i === minlg) {
  24292. vertex1 = path1[0];
  24293. vertex2 = path2[0];
  24294. }
  24295. else {
  24296. vertex1 = path1[i];
  24297. vertex2 = path2[i];
  24298. }
  24299. vectlg = vertex2.subtract(vertex1).length();
  24300. dist = vectlg + vTotalDistance[i];
  24301. vs[i].push(dist);
  24302. vTotalDistance[i] = dist;
  24303. }
  24304. if (closeArray) {
  24305. path1 = pathArray[p];
  24306. path2 = pathArray[0];
  24307. if (i === minlg) {
  24308. vertex2 = path2[0];
  24309. }
  24310. vectlg = vertex2.subtract(vertex1).length();
  24311. dist = vectlg + vTotalDistance[i];
  24312. vTotalDistance[i] = dist;
  24313. }
  24314. }
  24315. // uvs
  24316. var u;
  24317. var v;
  24318. if (customUV) {
  24319. for (p = 0; p < customUV.length; p++) {
  24320. uvs.push(customUV[p].x, customUV[p].y);
  24321. }
  24322. }
  24323. else {
  24324. for (p = 0; p < pathArray.length; p++) {
  24325. for (i = 0; i < minlg + closePathCorr; i++) {
  24326. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  24327. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  24328. if (invertUV) {
  24329. uvs.push(v, u);
  24330. }
  24331. else {
  24332. uvs.push(u, v);
  24333. }
  24334. }
  24335. }
  24336. }
  24337. // indices
  24338. p = 0; // path index
  24339. var pi = 0; // positions array index
  24340. var l1 = lg[p] - 1; // path1 length
  24341. var l2 = lg[p + 1] - 1; // path2 length
  24342. var min = (l1 < l2) ? l1 : l2; // current path stop index
  24343. var shft = idx[1] - idx[0]; // shift
  24344. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  24345. while (pi <= min && p < path1nb) {
  24346. // 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
  24347. indices.push(pi, pi + shft, pi + 1);
  24348. indices.push(pi + shft + 1, pi + 1, pi + shft);
  24349. pi += 1;
  24350. if (pi === min) {
  24351. p++;
  24352. if (p === lg.length - 1) {
  24353. shft = idx[0] - idx[p];
  24354. l1 = lg[p] - 1;
  24355. l2 = lg[0] - 1;
  24356. }
  24357. else {
  24358. shft = idx[p + 1] - idx[p];
  24359. l1 = lg[p] - 1;
  24360. l2 = lg[p + 1] - 1;
  24361. }
  24362. pi = idx[p];
  24363. min = (l1 < l2) ? l1 + pi : l2 + pi;
  24364. }
  24365. }
  24366. // normals
  24367. VertexData.ComputeNormals(positions, indices, normals);
  24368. if (closePath) {
  24369. var indexFirst = 0;
  24370. var indexLast = 0;
  24371. for (p = 0; p < pathArray.length; p++) {
  24372. indexFirst = idx[p] * 3;
  24373. if (p + 1 < pathArray.length) {
  24374. indexLast = (idx[p + 1] - 1) * 3;
  24375. }
  24376. else {
  24377. indexLast = normals.length - 3;
  24378. }
  24379. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  24380. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  24381. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  24382. normals[indexLast] = normals[indexFirst];
  24383. normals[indexLast + 1] = normals[indexFirst + 1];
  24384. normals[indexLast + 2] = normals[indexFirst + 2];
  24385. }
  24386. }
  24387. // sides
  24388. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24389. // Colors
  24390. if (customColors) {
  24391. var colors = new Float32Array(customColors.length * 4);
  24392. for (var c = 0; c < customColors.length; c++) {
  24393. colors[c * 4] = customColors[c].r;
  24394. colors[c * 4 + 1] = customColors[c].g;
  24395. colors[c * 4 + 2] = customColors[c].b;
  24396. colors[c * 4 + 3] = customColors[c].a;
  24397. }
  24398. }
  24399. // Result
  24400. var vertexData = new VertexData();
  24401. var positions32 = new Float32Array(positions);
  24402. var normals32 = new Float32Array(normals);
  24403. var uvs32 = new Float32Array(uvs);
  24404. vertexData.indices = indices;
  24405. vertexData.positions = positions32;
  24406. vertexData.normals = normals32;
  24407. vertexData.uvs = uvs32;
  24408. if (customColors) {
  24409. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  24410. }
  24411. if (closePath) {
  24412. vertexData._idx = idx;
  24413. }
  24414. return vertexData;
  24415. };
  24416. /**
  24417. * Creates the VertexData of the Box.
  24418. */
  24419. VertexData.CreateBox = function (options) {
  24420. var normalsSource = [
  24421. new BABYLON.Vector3(0, 0, 1),
  24422. new BABYLON.Vector3(0, 0, -1),
  24423. new BABYLON.Vector3(1, 0, 0),
  24424. new BABYLON.Vector3(-1, 0, 0),
  24425. new BABYLON.Vector3(0, 1, 0),
  24426. new BABYLON.Vector3(0, -1, 0)
  24427. ];
  24428. var indices = [];
  24429. var positions = [];
  24430. var normals = [];
  24431. var uvs = [];
  24432. var width = options.width || options.size || 1;
  24433. var height = options.height || options.size || 1;
  24434. var depth = options.depth || options.size || 1;
  24435. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24436. var faceUV = options.faceUV || new Array(6);
  24437. var faceColors = options.faceColors;
  24438. var colors = [];
  24439. // default face colors and UV if undefined
  24440. for (var f = 0; f < 6; f++) {
  24441. if (faceUV[f] === undefined) {
  24442. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  24443. }
  24444. if (faceColors && faceColors[f] === undefined) {
  24445. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  24446. }
  24447. }
  24448. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  24449. // Create each face in turn.
  24450. for (var index = 0; index < normalsSource.length; index++) {
  24451. var normal = normalsSource[index];
  24452. // Get two vectors perpendicular to the face normal and to each other.
  24453. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  24454. var side2 = BABYLON.Vector3.Cross(normal, side1);
  24455. // Six indices (two triangles) per face.
  24456. var verticesLength = positions.length / 3;
  24457. indices.push(verticesLength);
  24458. indices.push(verticesLength + 1);
  24459. indices.push(verticesLength + 2);
  24460. indices.push(verticesLength);
  24461. indices.push(verticesLength + 2);
  24462. indices.push(verticesLength + 3);
  24463. // Four vertices per face.
  24464. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  24465. positions.push(vertex.x, vertex.y, vertex.z);
  24466. normals.push(normal.x, normal.y, normal.z);
  24467. uvs.push(faceUV[index].z, faceUV[index].w);
  24468. if (faceColors) {
  24469. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  24470. }
  24471. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  24472. positions.push(vertex.x, vertex.y, vertex.z);
  24473. normals.push(normal.x, normal.y, normal.z);
  24474. uvs.push(faceUV[index].x, faceUV[index].w);
  24475. if (faceColors) {
  24476. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  24477. }
  24478. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  24479. positions.push(vertex.x, vertex.y, vertex.z);
  24480. normals.push(normal.x, normal.y, normal.z);
  24481. uvs.push(faceUV[index].x, faceUV[index].y);
  24482. if (faceColors) {
  24483. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  24484. }
  24485. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  24486. positions.push(vertex.x, vertex.y, vertex.z);
  24487. normals.push(normal.x, normal.y, normal.z);
  24488. uvs.push(faceUV[index].z, faceUV[index].y);
  24489. if (faceColors) {
  24490. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  24491. }
  24492. }
  24493. // sides
  24494. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24495. // Result
  24496. var vertexData = new VertexData();
  24497. vertexData.indices = indices;
  24498. vertexData.positions = positions;
  24499. vertexData.normals = normals;
  24500. vertexData.uvs = uvs;
  24501. if (faceColors) {
  24502. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  24503. vertexData.colors = totalColors;
  24504. }
  24505. return vertexData;
  24506. };
  24507. /**
  24508. * Creates the VertexData of the Sphere.
  24509. */
  24510. VertexData.CreateSphere = function (options) {
  24511. var segments = options.segments || 32;
  24512. var diameterX = options.diameterX || options.diameter || 1;
  24513. var diameterY = options.diameterY || options.diameter || 1;
  24514. var diameterZ = options.diameterZ || options.diameter || 1;
  24515. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  24516. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  24517. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24518. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  24519. var totalZRotationSteps = 2 + segments;
  24520. var totalYRotationSteps = 2 * totalZRotationSteps;
  24521. var indices = [];
  24522. var positions = [];
  24523. var normals = [];
  24524. var uvs = [];
  24525. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  24526. var normalizedZ = zRotationStep / totalZRotationSteps;
  24527. var angleZ = normalizedZ * Math.PI * slice;
  24528. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  24529. var normalizedY = yRotationStep / totalYRotationSteps;
  24530. var angleY = normalizedY * Math.PI * 2 * arc;
  24531. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  24532. var rotationY = BABYLON.Matrix.RotationY(angleY);
  24533. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  24534. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  24535. var vertex = complete.multiply(radius);
  24536. var normal = complete.divide(radius).normalize();
  24537. positions.push(vertex.x, vertex.y, vertex.z);
  24538. normals.push(normal.x, normal.y, normal.z);
  24539. uvs.push(normalizedY, normalizedZ);
  24540. }
  24541. if (zRotationStep > 0) {
  24542. var verticesCount = positions.length / 3;
  24543. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  24544. indices.push((firstIndex));
  24545. indices.push((firstIndex + 1));
  24546. indices.push(firstIndex + totalYRotationSteps + 1);
  24547. indices.push((firstIndex + totalYRotationSteps + 1));
  24548. indices.push((firstIndex + 1));
  24549. indices.push((firstIndex + totalYRotationSteps + 2));
  24550. }
  24551. }
  24552. }
  24553. // Sides
  24554. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24555. // Result
  24556. var vertexData = new VertexData();
  24557. vertexData.indices = indices;
  24558. vertexData.positions = positions;
  24559. vertexData.normals = normals;
  24560. vertexData.uvs = uvs;
  24561. return vertexData;
  24562. };
  24563. /**
  24564. * Creates the VertexData of the Cylinder or Cone.
  24565. */
  24566. VertexData.CreateCylinder = function (options) {
  24567. var height = options.height || 2;
  24568. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  24569. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  24570. var tessellation = options.tessellation || 24;
  24571. var subdivisions = options.subdivisions || 1;
  24572. var hasRings = options.hasRings;
  24573. var enclose = options.enclose;
  24574. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  24575. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24576. var faceUV = options.faceUV || new Array(3);
  24577. var faceColors = options.faceColors;
  24578. // default face colors and UV if undefined
  24579. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  24580. var ringNb = (hasRings) ? subdivisions : 1;
  24581. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  24582. var f;
  24583. for (f = 0; f < surfaceNb; f++) {
  24584. if (faceColors && faceColors[f] === undefined) {
  24585. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  24586. }
  24587. }
  24588. for (f = 0; f < surfaceNb; f++) {
  24589. if (faceUV && faceUV[f] === undefined) {
  24590. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  24591. }
  24592. }
  24593. var indices = [];
  24594. var positions = [];
  24595. var normals = [];
  24596. var uvs = [];
  24597. var colors = [];
  24598. var angle_step = Math.PI * 2 * arc / tessellation;
  24599. var angle;
  24600. var h;
  24601. var radius;
  24602. var tan = (diameterBottom - diameterTop) / 2 / height;
  24603. var ringVertex = BABYLON.Vector3.Zero();
  24604. var ringNormal = BABYLON.Vector3.Zero();
  24605. var ringFirstVertex = BABYLON.Vector3.Zero();
  24606. var ringFirstNormal = BABYLON.Vector3.Zero();
  24607. var quadNormal = BABYLON.Vector3.Zero();
  24608. var Y = BABYLON.Axis.Y;
  24609. // positions, normals, uvs
  24610. var i;
  24611. var j;
  24612. var r;
  24613. var ringIdx = 1;
  24614. var s = 1; // surface index
  24615. var cs = 0;
  24616. var v = 0;
  24617. for (i = 0; i <= subdivisions; i++) {
  24618. h = i / subdivisions;
  24619. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  24620. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  24621. for (r = 0; r < ringIdx; r++) {
  24622. if (hasRings) {
  24623. s += r;
  24624. }
  24625. if (enclose) {
  24626. s += 2 * r;
  24627. }
  24628. for (j = 0; j <= tessellation; j++) {
  24629. angle = j * angle_step;
  24630. // position
  24631. ringVertex.x = Math.cos(-angle) * radius;
  24632. ringVertex.y = -height / 2 + h * height;
  24633. ringVertex.z = Math.sin(-angle) * radius;
  24634. // normal
  24635. if (diameterTop === 0 && i === subdivisions) {
  24636. // if no top cap, reuse former normals
  24637. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  24638. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  24639. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  24640. }
  24641. else {
  24642. ringNormal.x = ringVertex.x;
  24643. ringNormal.z = ringVertex.z;
  24644. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  24645. ringNormal.normalize();
  24646. }
  24647. // keep first ring vertex values for enclose
  24648. if (j === 0) {
  24649. ringFirstVertex.copyFrom(ringVertex);
  24650. ringFirstNormal.copyFrom(ringNormal);
  24651. }
  24652. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  24653. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  24654. if (hasRings) {
  24655. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  24656. }
  24657. else {
  24658. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  24659. }
  24660. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  24661. if (faceColors) {
  24662. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  24663. }
  24664. }
  24665. // if enclose, add four vertices and their dedicated normals
  24666. if (arc !== 1 && enclose) {
  24667. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  24668. positions.push(0, ringVertex.y, 0);
  24669. positions.push(0, ringVertex.y, 0);
  24670. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  24671. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  24672. quadNormal.normalize();
  24673. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  24674. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  24675. quadNormal.normalize();
  24676. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  24677. if (hasRings) {
  24678. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  24679. }
  24680. else {
  24681. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  24682. }
  24683. uvs.push(faceUV[s + 1].x, v);
  24684. uvs.push(faceUV[s + 1].z, v);
  24685. if (hasRings) {
  24686. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  24687. }
  24688. else {
  24689. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  24690. }
  24691. uvs.push(faceUV[s + 2].x, v);
  24692. uvs.push(faceUV[s + 2].z, v);
  24693. if (faceColors) {
  24694. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  24695. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  24696. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  24697. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  24698. }
  24699. }
  24700. if (cs !== s) {
  24701. cs = s;
  24702. }
  24703. }
  24704. }
  24705. // indices
  24706. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  24707. var s;
  24708. i = 0;
  24709. for (s = 0; s < subdivisions; s++) {
  24710. for (j = 0; j < tessellation; j++) {
  24711. var i0 = i * (e + 1) + j;
  24712. var i1 = (i + 1) * (e + 1) + j;
  24713. var i2 = i * (e + 1) + (j + 1);
  24714. var i3 = (i + 1) * (e + 1) + (j + 1);
  24715. indices.push(i0, i1, i2);
  24716. indices.push(i3, i2, i1);
  24717. }
  24718. if (arc !== 1 && enclose) {
  24719. indices.push(i0 + 2, i1 + 2, i2 + 2);
  24720. indices.push(i3 + 2, i2 + 2, i1 + 2);
  24721. indices.push(i0 + 4, i1 + 4, i2 + 4);
  24722. indices.push(i3 + 4, i2 + 4, i1 + 4);
  24723. }
  24724. i = (hasRings) ? (i + 2) : (i + 1);
  24725. }
  24726. // Caps
  24727. var createCylinderCap = function (isTop) {
  24728. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  24729. if (radius === 0) {
  24730. return;
  24731. }
  24732. // Cap positions, normals & uvs
  24733. var angle;
  24734. var circleVector;
  24735. var i;
  24736. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  24737. var c;
  24738. if (faceColors) {
  24739. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  24740. }
  24741. // cap center
  24742. var vbase = positions.length / 3;
  24743. var offset = isTop ? height / 2 : -height / 2;
  24744. var center = new BABYLON.Vector3(0, offset, 0);
  24745. positions.push(center.x, center.y, center.z);
  24746. normals.push(0, isTop ? 1 : -1, 0);
  24747. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  24748. if (faceColors) {
  24749. colors.push(c.r, c.g, c.b, c.a);
  24750. }
  24751. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  24752. for (i = 0; i <= tessellation; i++) {
  24753. angle = Math.PI * 2 * i * arc / tessellation;
  24754. var cos = Math.cos(-angle);
  24755. var sin = Math.sin(-angle);
  24756. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  24757. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  24758. positions.push(circleVector.x, circleVector.y, circleVector.z);
  24759. normals.push(0, isTop ? 1 : -1, 0);
  24760. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  24761. if (faceColors) {
  24762. colors.push(c.r, c.g, c.b, c.a);
  24763. }
  24764. }
  24765. // Cap indices
  24766. for (i = 0; i < tessellation; i++) {
  24767. if (!isTop) {
  24768. indices.push(vbase);
  24769. indices.push(vbase + (i + 1));
  24770. indices.push(vbase + (i + 2));
  24771. }
  24772. else {
  24773. indices.push(vbase);
  24774. indices.push(vbase + (i + 2));
  24775. indices.push(vbase + (i + 1));
  24776. }
  24777. }
  24778. };
  24779. // add caps to geometry
  24780. createCylinderCap(false);
  24781. createCylinderCap(true);
  24782. // Sides
  24783. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24784. var vertexData = new VertexData();
  24785. vertexData.indices = indices;
  24786. vertexData.positions = positions;
  24787. vertexData.normals = normals;
  24788. vertexData.uvs = uvs;
  24789. if (faceColors) {
  24790. vertexData.colors = colors;
  24791. }
  24792. return vertexData;
  24793. };
  24794. /**
  24795. * Creates the VertexData of the Torus.
  24796. */
  24797. VertexData.CreateTorus = function (options) {
  24798. var indices = [];
  24799. var positions = [];
  24800. var normals = [];
  24801. var uvs = [];
  24802. var diameter = options.diameter || 1;
  24803. var thickness = options.thickness || 0.5;
  24804. var tessellation = options.tessellation || 16;
  24805. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24806. var stride = tessellation + 1;
  24807. for (var i = 0; i <= tessellation; i++) {
  24808. var u = i / tessellation;
  24809. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  24810. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  24811. for (var j = 0; j <= tessellation; j++) {
  24812. var v = 1 - j / tessellation;
  24813. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  24814. var dx = Math.cos(innerAngle);
  24815. var dy = Math.sin(innerAngle);
  24816. // Create a vertex.
  24817. var normal = new BABYLON.Vector3(dx, dy, 0);
  24818. var position = normal.scale(thickness / 2);
  24819. var textureCoordinate = new BABYLON.Vector2(u, v);
  24820. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  24821. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  24822. positions.push(position.x, position.y, position.z);
  24823. normals.push(normal.x, normal.y, normal.z);
  24824. uvs.push(textureCoordinate.x, textureCoordinate.y);
  24825. // And create indices for two triangles.
  24826. var nextI = (i + 1) % stride;
  24827. var nextJ = (j + 1) % stride;
  24828. indices.push(i * stride + j);
  24829. indices.push(i * stride + nextJ);
  24830. indices.push(nextI * stride + j);
  24831. indices.push(i * stride + nextJ);
  24832. indices.push(nextI * stride + nextJ);
  24833. indices.push(nextI * stride + j);
  24834. }
  24835. }
  24836. // Sides
  24837. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24838. // Result
  24839. var vertexData = new VertexData();
  24840. vertexData.indices = indices;
  24841. vertexData.positions = positions;
  24842. vertexData.normals = normals;
  24843. vertexData.uvs = uvs;
  24844. return vertexData;
  24845. };
  24846. /**
  24847. * Creates the VertexData of the LineSystem.
  24848. */
  24849. VertexData.CreateLineSystem = function (options) {
  24850. var indices = [];
  24851. var positions = [];
  24852. var lines = options.lines;
  24853. var idx = 0;
  24854. for (var l = 0; l < lines.length; l++) {
  24855. var points = lines[l];
  24856. for (var index = 0; index < points.length; index++) {
  24857. positions.push(points[index].x, points[index].y, points[index].z);
  24858. if (index > 0) {
  24859. indices.push(idx - 1);
  24860. indices.push(idx);
  24861. }
  24862. idx++;
  24863. }
  24864. }
  24865. var vertexData = new VertexData();
  24866. vertexData.indices = indices;
  24867. vertexData.positions = positions;
  24868. return vertexData;
  24869. };
  24870. /**
  24871. * Create the VertexData of the DashedLines.
  24872. */
  24873. VertexData.CreateDashedLines = function (options) {
  24874. var dashSize = options.dashSize || 3;
  24875. var gapSize = options.gapSize || 1;
  24876. var dashNb = options.dashNb || 200;
  24877. var points = options.points;
  24878. var positions = new Array();
  24879. var indices = new Array();
  24880. var curvect = BABYLON.Vector3.Zero();
  24881. var lg = 0;
  24882. var nb = 0;
  24883. var shft = 0;
  24884. var dashshft = 0;
  24885. var curshft = 0;
  24886. var idx = 0;
  24887. var i = 0;
  24888. for (i = 0; i < points.length - 1; i++) {
  24889. points[i + 1].subtractToRef(points[i], curvect);
  24890. lg += curvect.length();
  24891. }
  24892. shft = lg / dashNb;
  24893. dashshft = dashSize * shft / (dashSize + gapSize);
  24894. for (i = 0; i < points.length - 1; i++) {
  24895. points[i + 1].subtractToRef(points[i], curvect);
  24896. nb = Math.floor(curvect.length() / shft);
  24897. curvect.normalize();
  24898. for (var j = 0; j < nb; j++) {
  24899. curshft = shft * j;
  24900. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  24901. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  24902. indices.push(idx, idx + 1);
  24903. idx += 2;
  24904. }
  24905. }
  24906. // Result
  24907. var vertexData = new VertexData();
  24908. vertexData.positions = positions;
  24909. vertexData.indices = indices;
  24910. return vertexData;
  24911. };
  24912. /**
  24913. * Creates the VertexData of the Ground.
  24914. */
  24915. VertexData.CreateGround = function (options) {
  24916. var indices = [];
  24917. var positions = [];
  24918. var normals = [];
  24919. var uvs = [];
  24920. var row, col;
  24921. var width = options.width || 1;
  24922. var height = options.height || 1;
  24923. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  24924. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  24925. for (row = 0; row <= subdivisionsY; row++) {
  24926. for (col = 0; col <= subdivisionsX; col++) {
  24927. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  24928. var normal = new BABYLON.Vector3(0, 1.0, 0);
  24929. positions.push(position.x, position.y, position.z);
  24930. normals.push(normal.x, normal.y, normal.z);
  24931. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  24932. }
  24933. }
  24934. for (row = 0; row < subdivisionsY; row++) {
  24935. for (col = 0; col < subdivisionsX; col++) {
  24936. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  24937. indices.push(col + 1 + row * (subdivisionsX + 1));
  24938. indices.push(col + row * (subdivisionsX + 1));
  24939. indices.push(col + (row + 1) * (subdivisionsX + 1));
  24940. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  24941. indices.push(col + row * (subdivisionsX + 1));
  24942. }
  24943. }
  24944. // Result
  24945. var vertexData = new VertexData();
  24946. vertexData.indices = indices;
  24947. vertexData.positions = positions;
  24948. vertexData.normals = normals;
  24949. vertexData.uvs = uvs;
  24950. return vertexData;
  24951. };
  24952. /**
  24953. * Creates the VertexData of the TiledGround.
  24954. */
  24955. VertexData.CreateTiledGround = function (options) {
  24956. var xmin = options.xmin || -1.0;
  24957. var zmin = options.zmin || -1.0;
  24958. var xmax = options.xmax || 1.0;
  24959. var zmax = options.zmax || 1.0;
  24960. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  24961. var precision = options.precision || { w: 1, h: 1 };
  24962. var indices = [];
  24963. var positions = [];
  24964. var normals = [];
  24965. var uvs = [];
  24966. var row, col, tileRow, tileCol;
  24967. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  24968. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  24969. precision.w = (precision.w < 1) ? 1 : precision.w;
  24970. precision.h = (precision.h < 1) ? 1 : precision.h;
  24971. var tileSize = {
  24972. 'w': (xmax - xmin) / subdivisions.w,
  24973. 'h': (zmax - zmin) / subdivisions.h
  24974. };
  24975. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  24976. // Indices
  24977. var base = positions.length / 3;
  24978. var rowLength = precision.w + 1;
  24979. for (row = 0; row < precision.h; row++) {
  24980. for (col = 0; col < precision.w; col++) {
  24981. var square = [
  24982. base + col + row * rowLength,
  24983. base + (col + 1) + row * rowLength,
  24984. base + (col + 1) + (row + 1) * rowLength,
  24985. base + col + (row + 1) * rowLength
  24986. ];
  24987. indices.push(square[1]);
  24988. indices.push(square[2]);
  24989. indices.push(square[3]);
  24990. indices.push(square[0]);
  24991. indices.push(square[1]);
  24992. indices.push(square[3]);
  24993. }
  24994. }
  24995. // Position, normals and uvs
  24996. var position = BABYLON.Vector3.Zero();
  24997. var normal = new BABYLON.Vector3(0, 1.0, 0);
  24998. for (row = 0; row <= precision.h; row++) {
  24999. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  25000. for (col = 0; col <= precision.w; col++) {
  25001. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  25002. position.y = 0;
  25003. positions.push(position.x, position.y, position.z);
  25004. normals.push(normal.x, normal.y, normal.z);
  25005. uvs.push(col / precision.w, row / precision.h);
  25006. }
  25007. }
  25008. }
  25009. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  25010. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  25011. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  25012. }
  25013. }
  25014. // Result
  25015. var vertexData = new VertexData();
  25016. vertexData.indices = indices;
  25017. vertexData.positions = positions;
  25018. vertexData.normals = normals;
  25019. vertexData.uvs = uvs;
  25020. return vertexData;
  25021. };
  25022. /**
  25023. * Creates the VertexData of the Ground designed from a heightmap.
  25024. */
  25025. VertexData.CreateGroundFromHeightMap = function (options) {
  25026. var indices = [];
  25027. var positions = [];
  25028. var normals = [];
  25029. var uvs = [];
  25030. var row, col;
  25031. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  25032. // Vertices
  25033. for (row = 0; row <= options.subdivisions; row++) {
  25034. for (col = 0; col <= options.subdivisions; col++) {
  25035. 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));
  25036. // Compute height
  25037. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  25038. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  25039. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  25040. var r = options.buffer[pos] / 255.0;
  25041. var g = options.buffer[pos + 1] / 255.0;
  25042. var b = options.buffer[pos + 2] / 255.0;
  25043. var gradient = r * filter.r + g * filter.g + b * filter.b;
  25044. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  25045. // Add vertex
  25046. positions.push(position.x, position.y, position.z);
  25047. normals.push(0, 0, 0);
  25048. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  25049. }
  25050. }
  25051. // Indices
  25052. for (row = 0; row < options.subdivisions; row++) {
  25053. for (col = 0; col < options.subdivisions; col++) {
  25054. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  25055. indices.push(col + 1 + row * (options.subdivisions + 1));
  25056. indices.push(col + row * (options.subdivisions + 1));
  25057. indices.push(col + (row + 1) * (options.subdivisions + 1));
  25058. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  25059. indices.push(col + row * (options.subdivisions + 1));
  25060. }
  25061. }
  25062. // Normals
  25063. VertexData.ComputeNormals(positions, indices, normals);
  25064. // Result
  25065. var vertexData = new VertexData();
  25066. vertexData.indices = indices;
  25067. vertexData.positions = positions;
  25068. vertexData.normals = normals;
  25069. vertexData.uvs = uvs;
  25070. return vertexData;
  25071. };
  25072. /**
  25073. * Creates the VertexData of the Plane.
  25074. */
  25075. VertexData.CreatePlane = function (options) {
  25076. var indices = [];
  25077. var positions = [];
  25078. var normals = [];
  25079. var uvs = [];
  25080. var width = options.width || options.size || 1;
  25081. var height = options.height || options.size || 1;
  25082. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25083. // Vertices
  25084. var halfWidth = width / 2.0;
  25085. var halfHeight = height / 2.0;
  25086. positions.push(-halfWidth, -halfHeight, 0);
  25087. normals.push(0, 0, -1.0);
  25088. uvs.push(0.0, 0.0);
  25089. positions.push(halfWidth, -halfHeight, 0);
  25090. normals.push(0, 0, -1.0);
  25091. uvs.push(1.0, 0.0);
  25092. positions.push(halfWidth, halfHeight, 0);
  25093. normals.push(0, 0, -1.0);
  25094. uvs.push(1.0, 1.0);
  25095. positions.push(-halfWidth, halfHeight, 0);
  25096. normals.push(0, 0, -1.0);
  25097. uvs.push(0.0, 1.0);
  25098. // Indices
  25099. indices.push(0);
  25100. indices.push(1);
  25101. indices.push(2);
  25102. indices.push(0);
  25103. indices.push(2);
  25104. indices.push(3);
  25105. // Sides
  25106. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25107. // Result
  25108. var vertexData = new VertexData();
  25109. vertexData.indices = indices;
  25110. vertexData.positions = positions;
  25111. vertexData.normals = normals;
  25112. vertexData.uvs = uvs;
  25113. return vertexData;
  25114. };
  25115. /**
  25116. * Creates the VertexData of the Disc or regular Polygon.
  25117. */
  25118. VertexData.CreateDisc = function (options) {
  25119. var positions = [];
  25120. var indices = [];
  25121. var normals = [];
  25122. var uvs = [];
  25123. var radius = options.radius || 0.5;
  25124. var tessellation = options.tessellation || 64;
  25125. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  25126. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25127. // positions and uvs
  25128. positions.push(0, 0, 0); // disc center first
  25129. uvs.push(0.5, 0.5);
  25130. var theta = Math.PI * 2 * arc;
  25131. var step = theta / tessellation;
  25132. for (var a = 0; a < theta; a += step) {
  25133. var x = Math.cos(a);
  25134. var y = Math.sin(a);
  25135. var u = (x + 1) / 2;
  25136. var v = (1 - y) / 2;
  25137. positions.push(radius * x, radius * y, 0);
  25138. uvs.push(u, v);
  25139. }
  25140. if (arc === 1) {
  25141. positions.push(positions[3], positions[4], positions[5]); // close the circle
  25142. uvs.push(uvs[2], uvs[3]);
  25143. }
  25144. //indices
  25145. var vertexNb = positions.length / 3;
  25146. for (var i = 1; i < vertexNb - 1; i++) {
  25147. indices.push(i + 1, 0, i);
  25148. }
  25149. // result
  25150. VertexData.ComputeNormals(positions, indices, normals);
  25151. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25152. var vertexData = new VertexData();
  25153. vertexData.indices = indices;
  25154. vertexData.positions = positions;
  25155. vertexData.normals = normals;
  25156. vertexData.uvs = uvs;
  25157. return vertexData;
  25158. };
  25159. /**
  25160. * Creates the VertexData of the IcoSphere.
  25161. */
  25162. VertexData.CreateIcoSphere = function (options) {
  25163. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25164. var radius = options.radius || 1;
  25165. var flat = (options.flat === undefined) ? true : options.flat;
  25166. var subdivisions = options.subdivisions || 4;
  25167. var radiusX = options.radiusX || radius;
  25168. var radiusY = options.radiusY || radius;
  25169. var radiusZ = options.radiusZ || radius;
  25170. var t = (1 + Math.sqrt(5)) / 2;
  25171. // 12 vertex x,y,z
  25172. var ico_vertices = [
  25173. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  25174. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  25175. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  25176. ];
  25177. // index of 3 vertex makes a face of icopshere
  25178. var ico_indices = [
  25179. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  25180. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  25181. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  25182. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  25183. ];
  25184. // vertex for uv have aliased position, not for UV
  25185. var vertices_unalias_id = [
  25186. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  25187. // vertex alias
  25188. 0,
  25189. 2,
  25190. 3,
  25191. 3,
  25192. 3,
  25193. 4,
  25194. 7,
  25195. 8,
  25196. 9,
  25197. 9,
  25198. 10,
  25199. 11 // 23: B + 12
  25200. ];
  25201. // uv as integer step (not pixels !)
  25202. var ico_vertexuv = [
  25203. 5, 1, 3, 1, 6, 4, 0, 0,
  25204. 5, 3, 4, 2, 2, 2, 4, 0,
  25205. 2, 0, 1, 1, 6, 0, 6, 2,
  25206. // vertex alias (for same vertex on different faces)
  25207. 0, 4,
  25208. 3, 3,
  25209. 4, 4,
  25210. 3, 1,
  25211. 4, 2,
  25212. 4, 4,
  25213. 0, 2,
  25214. 1, 1,
  25215. 2, 2,
  25216. 3, 3,
  25217. 1, 3,
  25218. 2, 4 // 23: B + 12
  25219. ];
  25220. // Vertices[0, 1, ...9, A, B] : position on UV plane
  25221. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  25222. // First island of uv mapping
  25223. // v = 4h 3+ 2
  25224. // v = 3h 9+ 4
  25225. // v = 2h 9+ 5 B
  25226. // v = 1h 9 1 0
  25227. // v = 0h 3 8 7 A
  25228. // u = 0 1 2 3 4 5 6 *a
  25229. // Second island of uv mapping
  25230. // v = 4h 0+ B+ 4+
  25231. // v = 3h A+ 2+
  25232. // v = 2h 7+ 6 3+
  25233. // v = 1h 8+ 3+
  25234. // v = 0h
  25235. // u = 0 1 2 3 4 5 6 *a
  25236. // Face layout on texture UV mapping
  25237. // ============
  25238. // \ 4 /\ 16 / ======
  25239. // \ / \ / /\ 11 /
  25240. // \/ 7 \/ / \ /
  25241. // ======= / 10 \/
  25242. // /\ 17 /\ =======
  25243. // / \ / \ \ 15 /\
  25244. // / 8 \/ 12 \ \ / \
  25245. // ============ \/ 6 \
  25246. // \ 18 /\ ============
  25247. // \ / \ \ 5 /\ 0 /
  25248. // \/ 13 \ \ / \ /
  25249. // ======= \/ 1 \/
  25250. // =============
  25251. // /\ 19 /\ 2 /\
  25252. // / \ / \ / \
  25253. // / 14 \/ 9 \/ 3 \
  25254. // ===================
  25255. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  25256. var ustep = 138 / 1024;
  25257. var vstep = 239 / 1024;
  25258. var uoffset = 60 / 1024;
  25259. var voffset = 26 / 1024;
  25260. // Second island should have margin, not to touch the first island
  25261. // avoid any borderline artefact in pixel rounding
  25262. var island_u_offset = -40 / 1024;
  25263. var island_v_offset = +20 / 1024;
  25264. // face is either island 0 or 1 :
  25265. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  25266. var island = [
  25267. 0, 0, 0, 0, 1,
  25268. 0, 0, 1, 1, 0,
  25269. 0, 0, 1, 1, 0,
  25270. 0, 1, 1, 1, 0 // 15 - 19
  25271. ];
  25272. var indices = [];
  25273. var positions = [];
  25274. var normals = [];
  25275. var uvs = [];
  25276. var current_indice = 0;
  25277. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  25278. var face_vertex_pos = new Array(3);
  25279. var face_vertex_uv = new Array(3);
  25280. var v012;
  25281. for (v012 = 0; v012 < 3; v012++) {
  25282. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  25283. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  25284. }
  25285. // create all with normals
  25286. for (var face = 0; face < 20; face++) {
  25287. // 3 vertex per face
  25288. for (v012 = 0; v012 < 3; v012++) {
  25289. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  25290. var v_id = ico_indices[3 * face + v012];
  25291. // vertex have 3D position (x,y,z)
  25292. 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]);
  25293. // Normalize to get normal, then scale to radius
  25294. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  25295. // uv Coordinates from vertex ID
  25296. 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);
  25297. }
  25298. // Subdivide the face (interpolate pos, norm, uv)
  25299. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  25300. // - norm is linear interpolation of vertex corner normal
  25301. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  25302. // - uv is linear interpolation
  25303. //
  25304. // Topology is as below for sub-divide by 2
  25305. // vertex shown as v0,v1,v2
  25306. // interp index is i1 to progress in range [v0,v1[
  25307. // interp index is i2 to progress in range [v0,v2[
  25308. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  25309. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  25310. //
  25311. //
  25312. // i2 v2
  25313. // ^ ^
  25314. // / / \
  25315. // / / \
  25316. // / / \
  25317. // / / (0,1) \
  25318. // / #---------\
  25319. // / / \ (0,0)'/ \
  25320. // / / \ / \
  25321. // / / \ / \
  25322. // / / (0,0) \ / (1,0) \
  25323. // / #---------#---------\
  25324. // v0 v1
  25325. //
  25326. // --------------------> i1
  25327. //
  25328. // interp of (i1,i2):
  25329. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  25330. // along i1 : lerp(x0,x1, i1/(S-i2))
  25331. //
  25332. // centroid of triangle is needed to get help normal computation
  25333. // (c1,c2) are used for centroid location
  25334. var interp_vertex = function (i1, i2, c1, c2) {
  25335. // vertex is interpolated from
  25336. // - face_vertex_pos[0..2]
  25337. // - face_vertex_uv[0..2]
  25338. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  25339. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  25340. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  25341. pos_interp.normalize();
  25342. var vertex_normal;
  25343. if (flat) {
  25344. // in flat mode, recalculate normal as face centroid normal
  25345. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  25346. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  25347. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  25348. }
  25349. else {
  25350. // in smooth mode, recalculate normal from each single vertex position
  25351. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  25352. }
  25353. // Vertex normal need correction due to X,Y,Z radius scaling
  25354. vertex_normal.x /= radiusX;
  25355. vertex_normal.y /= radiusY;
  25356. vertex_normal.z /= radiusZ;
  25357. vertex_normal.normalize();
  25358. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  25359. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  25360. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  25361. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  25362. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  25363. uvs.push(uv_interp.x, uv_interp.y);
  25364. // push each vertex has member of a face
  25365. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  25366. indices.push(current_indice);
  25367. current_indice++;
  25368. };
  25369. for (var i2 = 0; i2 < subdivisions; i2++) {
  25370. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  25371. // face : (i1,i2) for /\ :
  25372. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  25373. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  25374. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  25375. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  25376. if (i1 + i2 + 1 < subdivisions) {
  25377. // face : (i1,i2)' for \/ :
  25378. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  25379. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  25380. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  25381. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  25382. }
  25383. }
  25384. }
  25385. }
  25386. // Sides
  25387. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25388. // Result
  25389. var vertexData = new VertexData();
  25390. vertexData.indices = indices;
  25391. vertexData.positions = positions;
  25392. vertexData.normals = normals;
  25393. vertexData.uvs = uvs;
  25394. return vertexData;
  25395. };
  25396. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  25397. /**
  25398. * Creates the VertexData of the Polyhedron.
  25399. */
  25400. VertexData.CreatePolyhedron = function (options) {
  25401. // provided polyhedron types :
  25402. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  25403. // 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)
  25404. var polyhedra = [];
  25405. 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]] };
  25406. 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]] };
  25407. polyhedra[2] = {
  25408. 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]],
  25409. 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]]
  25410. };
  25411. polyhedra[3] = {
  25412. 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]],
  25413. 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]]
  25414. };
  25415. polyhedra[4] = {
  25416. 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]],
  25417. 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]]
  25418. };
  25419. 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]] };
  25420. 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]] };
  25421. 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]] };
  25422. 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]] };
  25423. 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]] };
  25424. 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]] };
  25425. 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]] };
  25426. 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]] };
  25427. 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]] };
  25428. polyhedra[14] = {
  25429. 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]],
  25430. 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]]
  25431. };
  25432. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  25433. var size = options.size;
  25434. var sizeX = options.sizeX || size || 1;
  25435. var sizeY = options.sizeY || size || 1;
  25436. var sizeZ = options.sizeZ || size || 1;
  25437. var data = options.custom || polyhedra[type];
  25438. var nbfaces = data.face.length;
  25439. var faceUV = options.faceUV || new Array(nbfaces);
  25440. var faceColors = options.faceColors;
  25441. var flat = (options.flat === undefined) ? true : options.flat;
  25442. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25443. var positions = [];
  25444. var indices = [];
  25445. var normals = [];
  25446. var uvs = [];
  25447. var colors = [];
  25448. var index = 0;
  25449. var faceIdx = 0; // face cursor in the array "indexes"
  25450. var indexes = [];
  25451. var i = 0;
  25452. var f = 0;
  25453. var u, v, ang, x, y, tmp;
  25454. // default face colors and UV if undefined
  25455. if (flat) {
  25456. for (f = 0; f < nbfaces; f++) {
  25457. if (faceColors && faceColors[f] === undefined) {
  25458. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  25459. }
  25460. if (faceUV && faceUV[f] === undefined) {
  25461. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  25462. }
  25463. }
  25464. }
  25465. if (!flat) {
  25466. for (i = 0; i < data.vertex.length; i++) {
  25467. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  25468. uvs.push(0, 0);
  25469. }
  25470. for (f = 0; f < nbfaces; f++) {
  25471. for (i = 0; i < data.face[f].length - 2; i++) {
  25472. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  25473. }
  25474. }
  25475. }
  25476. else {
  25477. for (f = 0; f < nbfaces; f++) {
  25478. var fl = data.face[f].length; // number of vertices of the current face
  25479. ang = 2 * Math.PI / fl;
  25480. x = 0.5 * Math.tan(ang / 2);
  25481. y = 0.5;
  25482. // positions, uvs, colors
  25483. for (i = 0; i < fl; i++) {
  25484. // positions
  25485. 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);
  25486. indexes.push(index);
  25487. index++;
  25488. // uvs
  25489. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  25490. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  25491. uvs.push(u, v);
  25492. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  25493. y = x * Math.sin(ang) + y * Math.cos(ang);
  25494. x = tmp;
  25495. // colors
  25496. if (faceColors) {
  25497. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  25498. }
  25499. }
  25500. // indices from indexes
  25501. for (i = 0; i < fl - 2; i++) {
  25502. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  25503. }
  25504. faceIdx += fl;
  25505. }
  25506. }
  25507. VertexData.ComputeNormals(positions, indices, normals);
  25508. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25509. var vertexData = new VertexData();
  25510. vertexData.positions = positions;
  25511. vertexData.indices = indices;
  25512. vertexData.normals = normals;
  25513. vertexData.uvs = uvs;
  25514. if (faceColors && flat) {
  25515. vertexData.colors = colors;
  25516. }
  25517. return vertexData;
  25518. };
  25519. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  25520. /**
  25521. * Creates the VertexData of the Torus Knot.
  25522. */
  25523. VertexData.CreateTorusKnot = function (options) {
  25524. var indices = [];
  25525. var positions = [];
  25526. var normals = [];
  25527. var uvs = [];
  25528. var radius = options.radius || 2;
  25529. var tube = options.tube || 0.5;
  25530. var radialSegments = options.radialSegments || 32;
  25531. var tubularSegments = options.tubularSegments || 32;
  25532. var p = options.p || 2;
  25533. var q = options.q || 3;
  25534. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25535. // Helper
  25536. var getPos = function (angle) {
  25537. var cu = Math.cos(angle);
  25538. var su = Math.sin(angle);
  25539. var quOverP = q / p * angle;
  25540. var cs = Math.cos(quOverP);
  25541. var tx = radius * (2 + cs) * 0.5 * cu;
  25542. var ty = radius * (2 + cs) * su * 0.5;
  25543. var tz = radius * Math.sin(quOverP) * 0.5;
  25544. return new BABYLON.Vector3(tx, ty, tz);
  25545. };
  25546. // Vertices
  25547. var i;
  25548. var j;
  25549. for (i = 0; i <= radialSegments; i++) {
  25550. var modI = i % radialSegments;
  25551. var u = modI / radialSegments * 2 * p * Math.PI;
  25552. var p1 = getPos(u);
  25553. var p2 = getPos(u + 0.01);
  25554. var tang = p2.subtract(p1);
  25555. var n = p2.add(p1);
  25556. var bitan = BABYLON.Vector3.Cross(tang, n);
  25557. n = BABYLON.Vector3.Cross(bitan, tang);
  25558. bitan.normalize();
  25559. n.normalize();
  25560. for (j = 0; j < tubularSegments; j++) {
  25561. var modJ = j % tubularSegments;
  25562. var v = modJ / tubularSegments * 2 * Math.PI;
  25563. var cx = -tube * Math.cos(v);
  25564. var cy = tube * Math.sin(v);
  25565. positions.push(p1.x + cx * n.x + cy * bitan.x);
  25566. positions.push(p1.y + cx * n.y + cy * bitan.y);
  25567. positions.push(p1.z + cx * n.z + cy * bitan.z);
  25568. uvs.push(i / radialSegments);
  25569. uvs.push(j / tubularSegments);
  25570. }
  25571. }
  25572. for (i = 0; i < radialSegments; i++) {
  25573. for (j = 0; j < tubularSegments; j++) {
  25574. var jNext = (j + 1) % tubularSegments;
  25575. var a = i * tubularSegments + j;
  25576. var b = (i + 1) * tubularSegments + j;
  25577. var c = (i + 1) * tubularSegments + jNext;
  25578. var d = i * tubularSegments + jNext;
  25579. indices.push(d);
  25580. indices.push(b);
  25581. indices.push(a);
  25582. indices.push(d);
  25583. indices.push(c);
  25584. indices.push(b);
  25585. }
  25586. }
  25587. // Normals
  25588. VertexData.ComputeNormals(positions, indices, normals);
  25589. // Sides
  25590. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25591. // Result
  25592. var vertexData = new VertexData();
  25593. vertexData.indices = indices;
  25594. vertexData.positions = positions;
  25595. vertexData.normals = normals;
  25596. vertexData.uvs = uvs;
  25597. return vertexData;
  25598. };
  25599. // Tools
  25600. /**
  25601. * @param {any} - positions (number[] or Float32Array)
  25602. * @param {any} - indices (number[] or Uint16Array)
  25603. * @param {any} - normals (number[] or Float32Array)
  25604. * options (optional) :
  25605. * facetPositions : optional array of facet positions (vector3)
  25606. * facetNormals : optional array of facet normals (vector3)
  25607. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  25608. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  25609. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  25610. * bbSize : optional bounding box size data, required for facetPartitioning computation
  25611. * bInfo : optional bounding info, required for facetPartitioning computation
  25612. */
  25613. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  25614. // temporary scalar variables
  25615. var index = 0; // facet index
  25616. var p1p2x = 0.0; // p1p2 vector x coordinate
  25617. var p1p2y = 0.0; // p1p2 vector y coordinate
  25618. var p1p2z = 0.0; // p1p2 vector z coordinate
  25619. var p3p2x = 0.0; // p3p2 vector x coordinate
  25620. var p3p2y = 0.0; // p3p2 vector y coordinate
  25621. var p3p2z = 0.0; // p3p2 vector z coordinate
  25622. var faceNormalx = 0.0; // facet normal x coordinate
  25623. var faceNormaly = 0.0; // facet normal y coordinate
  25624. var faceNormalz = 0.0; // facet normal z coordinate
  25625. var length = 0.0; // facet normal length before normalization
  25626. var v1x = 0; // vector1 x index in the positions array
  25627. var v1y = 0; // vector1 y index in the positions array
  25628. var v1z = 0; // vector1 z index in the positions array
  25629. var v2x = 0; // vector2 x index in the positions array
  25630. var v2y = 0; // vector2 y index in the positions array
  25631. var v2z = 0; // vector2 z index in the positions array
  25632. var v3x = 0; // vector3 x index in the positions array
  25633. var v3y = 0; // vector3 y index in the positions array
  25634. var v3z = 0; // vector3 z index in the positions array
  25635. var computeFacetNormals = false;
  25636. var computeFacetPositions = false;
  25637. var computeFacetPartitioning = false;
  25638. var faceNormalSign = 1;
  25639. if (options) {
  25640. computeFacetNormals = (options.facetNormals) ? true : false;
  25641. computeFacetPositions = (options.facetPositions) ? true : false;
  25642. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  25643. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  25644. }
  25645. // facetPartitioning reinit if needed
  25646. if (computeFacetPartitioning) {
  25647. var ox = 0; // X partitioning index for facet position
  25648. var oy = 0; // Y partinioning index for facet position
  25649. var oz = 0; // Z partinioning index for facet position
  25650. var b1x = 0; // X partitioning index for facet v1 vertex
  25651. var b1y = 0; // Y partitioning index for facet v1 vertex
  25652. var b1z = 0; // z partitioning index for facet v1 vertex
  25653. var b2x = 0; // X partitioning index for facet v2 vertex
  25654. var b2y = 0; // Y partitioning index for facet v2 vertex
  25655. var b2z = 0; // Z partitioning index for facet v2 vertex
  25656. var b3x = 0; // X partitioning index for facet v3 vertex
  25657. var b3y = 0; // Y partitioning index for facet v3 vertex
  25658. var b3z = 0; // Z partitioning index for facet v3 vertex
  25659. var block_idx_o = 0; // facet barycenter block index
  25660. var block_idx_v1 = 0; // v1 vertex block index
  25661. var block_idx_v2 = 0; // v2 vertex block index
  25662. var block_idx_v3 = 0; // v3 vertex block index
  25663. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  25664. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  25665. var xSubRatio = options.subDiv.X * options.ratio / options.bbSize.x;
  25666. var ySubRatio = options.subDiv.Y * options.ratio / options.bbSize.y;
  25667. var zSubRatio = options.subDiv.Z * options.ratio / options.bbSize.z;
  25668. var subSq = options.subDiv.max * options.subDiv.max;
  25669. options.facetPartitioning.length = 0;
  25670. }
  25671. // reset the normals
  25672. for (index = 0; index < positions.length; index++) {
  25673. normals[index] = 0.0;
  25674. }
  25675. // Loop : 1 indice triplet = 1 facet
  25676. var nbFaces = indices.length / 3;
  25677. for (index = 0; index < nbFaces; index++) {
  25678. // get the indexes of the coordinates of each vertex of the facet
  25679. v1x = indices[index * 3] * 3;
  25680. v1y = v1x + 1;
  25681. v1z = v1x + 2;
  25682. v2x = indices[index * 3 + 1] * 3;
  25683. v2y = v2x + 1;
  25684. v2z = v2x + 2;
  25685. v3x = indices[index * 3 + 2] * 3;
  25686. v3y = v3x + 1;
  25687. v3z = v3x + 2;
  25688. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  25689. p1p2y = positions[v1y] - positions[v2y];
  25690. p1p2z = positions[v1z] - positions[v2z];
  25691. p3p2x = positions[v3x] - positions[v2x];
  25692. p3p2y = positions[v3y] - positions[v2y];
  25693. p3p2z = positions[v3z] - positions[v2z];
  25694. // compute the face normal with the cross product
  25695. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  25696. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  25697. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  25698. // normalize this normal and store it in the array facetData
  25699. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  25700. length = (length === 0) ? 1.0 : length;
  25701. faceNormalx /= length;
  25702. faceNormaly /= length;
  25703. faceNormalz /= length;
  25704. if (computeFacetNormals) {
  25705. options.facetNormals[index].x = faceNormalx;
  25706. options.facetNormals[index].y = faceNormaly;
  25707. options.facetNormals[index].z = faceNormalz;
  25708. }
  25709. if (computeFacetPositions) {
  25710. // compute and the facet barycenter coordinates in the array facetPositions
  25711. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  25712. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  25713. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  25714. }
  25715. if (computeFacetPartitioning) {
  25716. // store the facet indexes in arrays in the main facetPartitioning array :
  25717. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  25718. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  25719. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  25720. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  25721. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  25722. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  25723. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  25724. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  25725. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  25726. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  25727. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  25728. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  25729. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  25730. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  25731. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  25732. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  25733. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  25734. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  25735. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  25736. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  25737. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  25738. // push each facet index in each block containing the vertex
  25739. options.facetPartitioning[block_idx_v1].push(index);
  25740. if (block_idx_v2 != block_idx_v1) {
  25741. options.facetPartitioning[block_idx_v2].push(index);
  25742. }
  25743. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  25744. options.facetPartitioning[block_idx_v3].push(index);
  25745. }
  25746. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  25747. options.facetPartitioning[block_idx_o].push(index);
  25748. }
  25749. }
  25750. // compute the normals anyway
  25751. normals[v1x] += faceNormalx; // accumulate all the normals per face
  25752. normals[v1y] += faceNormaly;
  25753. normals[v1z] += faceNormalz;
  25754. normals[v2x] += faceNormalx;
  25755. normals[v2y] += faceNormaly;
  25756. normals[v2z] += faceNormalz;
  25757. normals[v3x] += faceNormalx;
  25758. normals[v3y] += faceNormaly;
  25759. normals[v3z] += faceNormalz;
  25760. }
  25761. // last normalization of each normal
  25762. for (index = 0; index < normals.length / 3; index++) {
  25763. faceNormalx = normals[index * 3];
  25764. faceNormaly = normals[index * 3 + 1];
  25765. faceNormalz = normals[index * 3 + 2];
  25766. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  25767. length = (length === 0) ? 1.0 : length;
  25768. faceNormalx /= length;
  25769. faceNormaly /= length;
  25770. faceNormalz /= length;
  25771. normals[index * 3] = faceNormalx;
  25772. normals[index * 3 + 1] = faceNormaly;
  25773. normals[index * 3 + 2] = faceNormalz;
  25774. }
  25775. };
  25776. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  25777. var li = indices.length;
  25778. var ln = normals.length;
  25779. var i;
  25780. var n;
  25781. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25782. switch (sideOrientation) {
  25783. case BABYLON.Mesh.FRONTSIDE:
  25784. // nothing changed
  25785. break;
  25786. case BABYLON.Mesh.BACKSIDE:
  25787. var tmp;
  25788. // indices
  25789. for (i = 0; i < li; i += 3) {
  25790. tmp = indices[i];
  25791. indices[i] = indices[i + 2];
  25792. indices[i + 2] = tmp;
  25793. }
  25794. // normals
  25795. for (n = 0; n < ln; n++) {
  25796. normals[n] = -normals[n];
  25797. }
  25798. break;
  25799. case BABYLON.Mesh.DOUBLESIDE:
  25800. // positions
  25801. var lp = positions.length;
  25802. var l = lp / 3;
  25803. for (var p = 0; p < lp; p++) {
  25804. positions[lp + p] = positions[p];
  25805. }
  25806. // indices
  25807. for (i = 0; i < li; i += 3) {
  25808. indices[i + li] = indices[i + 2] + l;
  25809. indices[i + 1 + li] = indices[i + 1] + l;
  25810. indices[i + 2 + li] = indices[i] + l;
  25811. }
  25812. // normals
  25813. for (n = 0; n < ln; n++) {
  25814. normals[ln + n] = -normals[n];
  25815. }
  25816. // uvs
  25817. var lu = uvs.length;
  25818. for (var u = 0; u < lu; u++) {
  25819. uvs[u + lu] = uvs[u];
  25820. }
  25821. break;
  25822. }
  25823. };
  25824. /**
  25825. * Creates a new VertexData from the imported parameters.
  25826. */
  25827. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  25828. var vertexData = new VertexData();
  25829. // positions
  25830. var positions = parsedVertexData.positions;
  25831. if (positions) {
  25832. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  25833. }
  25834. // normals
  25835. var normals = parsedVertexData.normals;
  25836. if (normals) {
  25837. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  25838. }
  25839. // tangents
  25840. var tangents = parsedVertexData.tangents;
  25841. if (tangents) {
  25842. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  25843. }
  25844. // uvs
  25845. var uvs = parsedVertexData.uvs;
  25846. if (uvs) {
  25847. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  25848. }
  25849. // uv2s
  25850. var uv2s = parsedVertexData.uv2s;
  25851. if (uv2s) {
  25852. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  25853. }
  25854. // uv3s
  25855. var uv3s = parsedVertexData.uv3s;
  25856. if (uv3s) {
  25857. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  25858. }
  25859. // uv4s
  25860. var uv4s = parsedVertexData.uv4s;
  25861. if (uv4s) {
  25862. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  25863. }
  25864. // uv5s
  25865. var uv5s = parsedVertexData.uv5s;
  25866. if (uv5s) {
  25867. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  25868. }
  25869. // uv6s
  25870. var uv6s = parsedVertexData.uv6s;
  25871. if (uv6s) {
  25872. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  25873. }
  25874. // colors
  25875. var colors = parsedVertexData.colors;
  25876. if (colors) {
  25877. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  25878. }
  25879. // matricesIndices
  25880. var matricesIndices = parsedVertexData.matricesIndices;
  25881. if (matricesIndices) {
  25882. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  25883. }
  25884. // matricesWeights
  25885. var matricesWeights = parsedVertexData.matricesWeights;
  25886. if (matricesWeights) {
  25887. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  25888. }
  25889. // indices
  25890. var indices = parsedVertexData.indices;
  25891. if (indices) {
  25892. vertexData.indices = indices;
  25893. }
  25894. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  25895. };
  25896. return VertexData;
  25897. }());
  25898. BABYLON.VertexData = VertexData;
  25899. })(BABYLON || (BABYLON = {}));
  25900. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  25901. var BABYLON;
  25902. (function (BABYLON) {
  25903. var Geometry = (function () {
  25904. function Geometry(id, scene, vertexData, updatable, mesh) {
  25905. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  25906. this._totalVertices = 0;
  25907. this._isDisposed = false;
  25908. this.id = id;
  25909. this._engine = scene.getEngine();
  25910. this._meshes = [];
  25911. this._scene = scene;
  25912. //Init vertex buffer cache
  25913. this._vertexBuffers = {};
  25914. this._indices = [];
  25915. // vertexData
  25916. if (vertexData) {
  25917. this.setAllVerticesData(vertexData, updatable);
  25918. }
  25919. else {
  25920. this._totalVertices = 0;
  25921. this._indices = [];
  25922. }
  25923. if (this._engine.getCaps().vertexArrayObject) {
  25924. this._vertexArrayObjects = {};
  25925. }
  25926. // applyToMesh
  25927. if (mesh) {
  25928. if (mesh.getClassName() === "LinesMesh") {
  25929. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  25930. this.updateExtend();
  25931. }
  25932. this.applyToMesh(mesh);
  25933. mesh.computeWorldMatrix(true);
  25934. }
  25935. }
  25936. Object.defineProperty(Geometry.prototype, "boundingBias", {
  25937. /**
  25938. * 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
  25939. * @returns The Bias Vector
  25940. */
  25941. get: function () {
  25942. return this._boundingBias;
  25943. },
  25944. set: function (value) {
  25945. if (this._boundingBias && this._boundingBias.equals(value)) {
  25946. return;
  25947. }
  25948. this._boundingBias = value.clone();
  25949. this.updateBoundingInfo(true, null);
  25950. },
  25951. enumerable: true,
  25952. configurable: true
  25953. });
  25954. Object.defineProperty(Geometry.prototype, "extend", {
  25955. get: function () {
  25956. return this._extend;
  25957. },
  25958. enumerable: true,
  25959. configurable: true
  25960. });
  25961. Geometry.prototype.getScene = function () {
  25962. return this._scene;
  25963. };
  25964. Geometry.prototype.getEngine = function () {
  25965. return this._engine;
  25966. };
  25967. Geometry.prototype.isReady = function () {
  25968. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  25969. };
  25970. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  25971. get: function () {
  25972. for (var index = 0; index < this._meshes.length; index++) {
  25973. if (!this._meshes[index].doNotSerialize) {
  25974. return false;
  25975. }
  25976. }
  25977. return true;
  25978. },
  25979. enumerable: true,
  25980. configurable: true
  25981. });
  25982. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  25983. vertexData.applyToGeometry(this, updatable);
  25984. this.notifyUpdate();
  25985. };
  25986. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  25987. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  25988. this.setVerticesBuffer(buffer);
  25989. };
  25990. Geometry.prototype.removeVerticesData = function (kind) {
  25991. if (this._vertexBuffers[kind]) {
  25992. this._vertexBuffers[kind].dispose();
  25993. delete this._vertexBuffers[kind];
  25994. }
  25995. };
  25996. Geometry.prototype.setVerticesBuffer = function (buffer) {
  25997. var kind = buffer.getKind();
  25998. if (this._vertexBuffers[kind]) {
  25999. this._vertexBuffers[kind].dispose();
  26000. }
  26001. this._vertexBuffers[kind] = buffer;
  26002. if (kind === BABYLON.VertexBuffer.PositionKind) {
  26003. var data = buffer.getData();
  26004. var stride = buffer.getStrideSize();
  26005. this._totalVertices = data.length / stride;
  26006. this.updateExtend(data, stride);
  26007. var meshes = this._meshes;
  26008. var numOfMeshes = meshes.length;
  26009. for (var index = 0; index < numOfMeshes; index++) {
  26010. var mesh = meshes[index];
  26011. mesh._resetPointsArrayCache();
  26012. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  26013. mesh._createGlobalSubMesh();
  26014. mesh.computeWorldMatrix(true);
  26015. }
  26016. }
  26017. this.notifyUpdate(kind);
  26018. if (this._vertexArrayObjects) {
  26019. this._disposeVertexArrayObjects();
  26020. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  26021. }
  26022. };
  26023. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  26024. var vertexBuffer = this.getVertexBuffer(kind);
  26025. if (!vertexBuffer) {
  26026. return;
  26027. }
  26028. vertexBuffer.updateDirectly(data, offset);
  26029. this.notifyUpdate(kind);
  26030. };
  26031. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  26032. var vertexBuffer = this.getVertexBuffer(kind);
  26033. if (!vertexBuffer) {
  26034. return;
  26035. }
  26036. vertexBuffer.update(data);
  26037. if (kind === BABYLON.VertexBuffer.PositionKind) {
  26038. var stride = vertexBuffer.getStrideSize();
  26039. this._totalVertices = data.length / stride;
  26040. this.updateBoundingInfo(updateExtends, data);
  26041. }
  26042. this.notifyUpdate(kind);
  26043. };
  26044. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  26045. if (updateExtends) {
  26046. this.updateExtend(data);
  26047. }
  26048. var meshes = this._meshes;
  26049. var numOfMeshes = meshes.length;
  26050. for (var index = 0; index < numOfMeshes; index++) {
  26051. var mesh = meshes[index];
  26052. mesh._resetPointsArrayCache();
  26053. if (updateExtends) {
  26054. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  26055. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  26056. var subMesh = mesh.subMeshes[subIndex];
  26057. subMesh.refreshBoundingInfo();
  26058. }
  26059. }
  26060. }
  26061. };
  26062. Geometry.prototype._bind = function (effect, indexToBind) {
  26063. if (indexToBind === void 0) { indexToBind = undefined; }
  26064. if (indexToBind === undefined) {
  26065. indexToBind = this._indexBuffer;
  26066. }
  26067. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  26068. this._engine.bindBuffers(this.getVertexBuffers(), indexToBind, effect);
  26069. return;
  26070. }
  26071. // Using VAO
  26072. if (!this._vertexArrayObjects[effect.key]) {
  26073. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(this.getVertexBuffers(), indexToBind, effect);
  26074. }
  26075. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  26076. };
  26077. Geometry.prototype.getTotalVertices = function () {
  26078. if (!this.isReady()) {
  26079. return 0;
  26080. }
  26081. return this._totalVertices;
  26082. };
  26083. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  26084. var vertexBuffer = this.getVertexBuffer(kind);
  26085. if (!vertexBuffer) {
  26086. return null;
  26087. }
  26088. var orig = vertexBuffer.getData();
  26089. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  26090. return orig;
  26091. }
  26092. else {
  26093. var len = orig.length;
  26094. var copy = [];
  26095. for (var i = 0; i < len; i++) {
  26096. copy.push(orig[i]);
  26097. }
  26098. return copy;
  26099. }
  26100. };
  26101. Geometry.prototype.getVertexBuffer = function (kind) {
  26102. if (!this.isReady()) {
  26103. return null;
  26104. }
  26105. return this._vertexBuffers[kind];
  26106. };
  26107. Geometry.prototype.getVertexBuffers = function () {
  26108. if (!this.isReady()) {
  26109. return null;
  26110. }
  26111. return this._vertexBuffers;
  26112. };
  26113. Geometry.prototype.isVerticesDataPresent = function (kind) {
  26114. if (!this._vertexBuffers) {
  26115. if (this._delayInfo) {
  26116. return this._delayInfo.indexOf(kind) !== -1;
  26117. }
  26118. return false;
  26119. }
  26120. return this._vertexBuffers[kind] !== undefined;
  26121. };
  26122. Geometry.prototype.getVerticesDataKinds = function () {
  26123. var result = [];
  26124. var kind;
  26125. if (!this._vertexBuffers && this._delayInfo) {
  26126. for (kind in this._delayInfo) {
  26127. result.push(kind);
  26128. }
  26129. }
  26130. else {
  26131. for (kind in this._vertexBuffers) {
  26132. result.push(kind);
  26133. }
  26134. }
  26135. return result;
  26136. };
  26137. Geometry.prototype.setIndices = function (indices, totalVertices) {
  26138. if (this._indexBuffer) {
  26139. this._engine._releaseBuffer(this._indexBuffer);
  26140. }
  26141. this._disposeVertexArrayObjects();
  26142. this._indices = indices;
  26143. if (this._meshes.length !== 0 && this._indices) {
  26144. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  26145. }
  26146. if (totalVertices !== undefined) {
  26147. this._totalVertices = totalVertices;
  26148. }
  26149. var meshes = this._meshes;
  26150. var numOfMeshes = meshes.length;
  26151. for (var index = 0; index < numOfMeshes; index++) {
  26152. meshes[index]._createGlobalSubMesh();
  26153. }
  26154. this.notifyUpdate();
  26155. };
  26156. Geometry.prototype.getTotalIndices = function () {
  26157. if (!this.isReady()) {
  26158. return 0;
  26159. }
  26160. return this._indices.length;
  26161. };
  26162. Geometry.prototype.getIndices = function (copyWhenShared) {
  26163. if (!this.isReady()) {
  26164. return null;
  26165. }
  26166. var orig = this._indices;
  26167. if (!copyWhenShared || this._meshes.length === 1) {
  26168. return orig;
  26169. }
  26170. else {
  26171. var len = orig.length;
  26172. var copy = [];
  26173. for (var i = 0; i < len; i++) {
  26174. copy.push(orig[i]);
  26175. }
  26176. return copy;
  26177. }
  26178. };
  26179. Geometry.prototype.getIndexBuffer = function () {
  26180. if (!this.isReady()) {
  26181. return null;
  26182. }
  26183. return this._indexBuffer;
  26184. };
  26185. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  26186. if (!effect || !this._vertexArrayObjects) {
  26187. return;
  26188. }
  26189. if (this._vertexArrayObjects[effect.key]) {
  26190. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  26191. delete this._vertexArrayObjects[effect.key];
  26192. }
  26193. };
  26194. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  26195. var meshes = this._meshes;
  26196. var index = meshes.indexOf(mesh);
  26197. if (index === -1) {
  26198. return;
  26199. }
  26200. meshes.splice(index, 1);
  26201. mesh._geometry = null;
  26202. if (meshes.length === 0 && shouldDispose) {
  26203. this.dispose();
  26204. }
  26205. };
  26206. Geometry.prototype.applyToMesh = function (mesh) {
  26207. if (mesh._geometry === this) {
  26208. return;
  26209. }
  26210. var previousGeometry = mesh._geometry;
  26211. if (previousGeometry) {
  26212. previousGeometry.releaseForMesh(mesh);
  26213. }
  26214. var meshes = this._meshes;
  26215. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  26216. mesh._geometry = this;
  26217. this._scene.pushGeometry(this);
  26218. meshes.push(mesh);
  26219. if (this.isReady()) {
  26220. this._applyToMesh(mesh);
  26221. }
  26222. else {
  26223. mesh._boundingInfo = this._boundingInfo;
  26224. }
  26225. };
  26226. Geometry.prototype.updateExtend = function (data, stride) {
  26227. if (data === void 0) { data = null; }
  26228. if (!data) {
  26229. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  26230. }
  26231. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  26232. };
  26233. Geometry.prototype._applyToMesh = function (mesh) {
  26234. var numOfMeshes = this._meshes.length;
  26235. // vertexBuffers
  26236. for (var kind in this._vertexBuffers) {
  26237. if (numOfMeshes === 1) {
  26238. this._vertexBuffers[kind].create();
  26239. }
  26240. var buffer = this._vertexBuffers[kind].getBuffer();
  26241. if (buffer)
  26242. buffer.references = numOfMeshes;
  26243. if (kind === BABYLON.VertexBuffer.PositionKind) {
  26244. mesh._resetPointsArrayCache();
  26245. if (!this._extend) {
  26246. this.updateExtend(this._vertexBuffers[kind].getData());
  26247. }
  26248. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  26249. mesh._createGlobalSubMesh();
  26250. //bounding info was just created again, world matrix should be applied again.
  26251. mesh._updateBoundingInfo();
  26252. }
  26253. }
  26254. // indexBuffer
  26255. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  26256. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  26257. }
  26258. if (this._indexBuffer) {
  26259. this._indexBuffer.references = numOfMeshes;
  26260. }
  26261. };
  26262. Geometry.prototype.notifyUpdate = function (kind) {
  26263. if (this.onGeometryUpdated) {
  26264. this.onGeometryUpdated(this, kind);
  26265. }
  26266. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  26267. var mesh = _a[_i];
  26268. mesh._markSubMeshesAsAttributesDirty();
  26269. }
  26270. };
  26271. Geometry.prototype.load = function (scene, onLoaded) {
  26272. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  26273. return;
  26274. }
  26275. if (this.isReady()) {
  26276. if (onLoaded) {
  26277. onLoaded();
  26278. }
  26279. return;
  26280. }
  26281. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  26282. this._queueLoad(scene, onLoaded);
  26283. };
  26284. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  26285. var _this = this;
  26286. scene._addPendingData(this);
  26287. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  26288. _this._delayLoadingFunction(JSON.parse(data), _this);
  26289. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  26290. _this._delayInfo = [];
  26291. scene._removePendingData(_this);
  26292. var meshes = _this._meshes;
  26293. var numOfMeshes = meshes.length;
  26294. for (var index = 0; index < numOfMeshes; index++) {
  26295. _this._applyToMesh(meshes[index]);
  26296. }
  26297. if (onLoaded) {
  26298. onLoaded();
  26299. }
  26300. }, function () { }, scene.database);
  26301. };
  26302. /**
  26303. * Invert the geometry to move from a right handed system to a left handed one.
  26304. */
  26305. Geometry.prototype.toLeftHanded = function () {
  26306. // Flip faces
  26307. var tIndices = this.getIndices(false);
  26308. if (tIndices != null && tIndices.length > 0) {
  26309. for (var i = 0; i < tIndices.length; i += 3) {
  26310. var tTemp = tIndices[i + 0];
  26311. tIndices[i + 0] = tIndices[i + 2];
  26312. tIndices[i + 2] = tTemp;
  26313. }
  26314. this.setIndices(tIndices);
  26315. }
  26316. // Negate position.z
  26317. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  26318. if (tPositions != null && tPositions.length > 0) {
  26319. for (var i = 0; i < tPositions.length; i += 3) {
  26320. tPositions[i + 2] = -tPositions[i + 2];
  26321. }
  26322. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  26323. }
  26324. // Negate normal.z
  26325. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  26326. if (tNormals != null && tNormals.length > 0) {
  26327. for (var i = 0; i < tNormals.length; i += 3) {
  26328. tNormals[i + 2] = -tNormals[i + 2];
  26329. }
  26330. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  26331. }
  26332. };
  26333. Geometry.prototype.isDisposed = function () {
  26334. return this._isDisposed;
  26335. };
  26336. Geometry.prototype._disposeVertexArrayObjects = function () {
  26337. if (this._vertexArrayObjects) {
  26338. for (var kind in this._vertexArrayObjects) {
  26339. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  26340. }
  26341. this._vertexArrayObjects = {};
  26342. }
  26343. };
  26344. Geometry.prototype.dispose = function () {
  26345. var meshes = this._meshes;
  26346. var numOfMeshes = meshes.length;
  26347. var index;
  26348. for (index = 0; index < numOfMeshes; index++) {
  26349. this.releaseForMesh(meshes[index]);
  26350. }
  26351. this._meshes = [];
  26352. this._disposeVertexArrayObjects();
  26353. for (var kind in this._vertexBuffers) {
  26354. this._vertexBuffers[kind].dispose();
  26355. }
  26356. this._vertexBuffers = {};
  26357. this._totalVertices = 0;
  26358. if (this._indexBuffer) {
  26359. this._engine._releaseBuffer(this._indexBuffer);
  26360. }
  26361. this._indexBuffer = null;
  26362. this._indices = [];
  26363. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26364. this.delayLoadingFile = null;
  26365. this._delayLoadingFunction = null;
  26366. this._delayInfo = [];
  26367. this._boundingInfo = null;
  26368. this._scene.removeGeometry(this);
  26369. this._isDisposed = true;
  26370. };
  26371. Geometry.prototype.copy = function (id) {
  26372. var vertexData = new BABYLON.VertexData();
  26373. vertexData.indices = [];
  26374. var indices = this.getIndices();
  26375. for (var index = 0; index < indices.length; index++) {
  26376. vertexData.indices.push(indices[index]);
  26377. }
  26378. var updatable = false;
  26379. var stopChecking = false;
  26380. var kind;
  26381. for (kind in this._vertexBuffers) {
  26382. // using slice() to make a copy of the array and not just reference it
  26383. var data = this.getVerticesData(kind);
  26384. if (data instanceof Float32Array) {
  26385. vertexData.set(new Float32Array(data), kind);
  26386. }
  26387. else {
  26388. vertexData.set(data.slice(0), kind);
  26389. }
  26390. if (!stopChecking) {
  26391. updatable = this.getVertexBuffer(kind).isUpdatable();
  26392. stopChecking = !updatable;
  26393. }
  26394. }
  26395. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  26396. geometry.delayLoadState = this.delayLoadState;
  26397. geometry.delayLoadingFile = this.delayLoadingFile;
  26398. geometry._delayLoadingFunction = this._delayLoadingFunction;
  26399. for (kind in this._delayInfo) {
  26400. geometry._delayInfo = geometry._delayInfo || [];
  26401. geometry._delayInfo.push(kind);
  26402. }
  26403. // Bounding info
  26404. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  26405. return geometry;
  26406. };
  26407. Geometry.prototype.serialize = function () {
  26408. var serializationObject = {};
  26409. serializationObject.id = this.id;
  26410. if (BABYLON.Tags.HasTags(this)) {
  26411. serializationObject.tags = BABYLON.Tags.GetTags(this);
  26412. }
  26413. return serializationObject;
  26414. };
  26415. Geometry.prototype.toNumberArray = function (origin) {
  26416. if (Array.isArray(origin)) {
  26417. return origin;
  26418. }
  26419. else {
  26420. return Array.prototype.slice.call(origin);
  26421. }
  26422. };
  26423. Geometry.prototype.serializeVerticeData = function () {
  26424. var serializationObject = this.serialize();
  26425. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  26426. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  26427. if (this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable) {
  26428. serializationObject.positions._updatable = true;
  26429. }
  26430. }
  26431. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  26432. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  26433. if (this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable) {
  26434. serializationObject.normals._updatable = true;
  26435. }
  26436. }
  26437. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  26438. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  26439. if (this.getVertexBuffer(BABYLON.VertexBuffer.UVKind).isUpdatable) {
  26440. serializationObject.uvs._updatable = true;
  26441. }
  26442. }
  26443. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  26444. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  26445. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV2Kind).isUpdatable) {
  26446. serializationObject.uv2s._updatable = true;
  26447. }
  26448. }
  26449. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  26450. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  26451. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV3Kind).isUpdatable) {
  26452. serializationObject.uv3s._updatable = true;
  26453. }
  26454. }
  26455. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  26456. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  26457. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV4Kind).isUpdatable) {
  26458. serializationObject.uv4s._updatable = true;
  26459. }
  26460. }
  26461. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  26462. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  26463. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV5Kind).isUpdatable) {
  26464. serializationObject.uv5s._updatable = true;
  26465. }
  26466. }
  26467. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  26468. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  26469. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV6Kind).isUpdatable) {
  26470. serializationObject.uv6s._updatable = true;
  26471. }
  26472. }
  26473. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  26474. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  26475. if (this.getVertexBuffer(BABYLON.VertexBuffer.ColorKind).isUpdatable) {
  26476. serializationObject.colors._updatable = true;
  26477. }
  26478. }
  26479. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  26480. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  26481. serializationObject.matricesIndices._isExpanded = true;
  26482. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesIndicesKind).isUpdatable) {
  26483. serializationObject.matricesIndices._updatable = true;
  26484. }
  26485. }
  26486. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  26487. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  26488. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesWeightsKind).isUpdatable) {
  26489. serializationObject.matricesWeights._updatable = true;
  26490. }
  26491. }
  26492. serializationObject.indices = this.toNumberArray(this.getIndices());
  26493. return serializationObject;
  26494. };
  26495. // Statics
  26496. Geometry.ExtractFromMesh = function (mesh, id) {
  26497. var geometry = mesh._geometry;
  26498. if (!geometry) {
  26499. return null;
  26500. }
  26501. return geometry.copy(id);
  26502. };
  26503. /**
  26504. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  26505. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  26506. * Be aware Math.random() could cause collisions, but:
  26507. * "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"
  26508. */
  26509. Geometry.RandomId = function () {
  26510. return BABYLON.Tools.RandomId();
  26511. };
  26512. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  26513. var scene = mesh.getScene();
  26514. // Geometry
  26515. var geometryId = parsedGeometry.geometryId;
  26516. if (geometryId) {
  26517. var geometry = scene.getGeometryByID(geometryId);
  26518. if (geometry) {
  26519. geometry.applyToMesh(mesh);
  26520. }
  26521. }
  26522. else if (parsedGeometry instanceof ArrayBuffer) {
  26523. var binaryInfo = mesh._binaryInfo;
  26524. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  26525. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  26526. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  26527. }
  26528. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  26529. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  26530. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  26531. }
  26532. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  26533. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  26534. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  26535. }
  26536. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  26537. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  26538. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  26539. }
  26540. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  26541. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  26542. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  26543. }
  26544. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  26545. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  26546. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  26547. }
  26548. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  26549. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  26550. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  26551. }
  26552. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  26553. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  26554. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  26555. }
  26556. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  26557. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  26558. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  26559. }
  26560. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  26561. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  26562. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  26563. }
  26564. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  26565. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  26566. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  26567. }
  26568. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  26569. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  26570. mesh.setIndices(indicesData);
  26571. }
  26572. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  26573. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  26574. mesh.subMeshes = [];
  26575. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  26576. var materialIndex = subMeshesData[(i * 5) + 0];
  26577. var verticesStart = subMeshesData[(i * 5) + 1];
  26578. var verticesCount = subMeshesData[(i * 5) + 2];
  26579. var indexStart = subMeshesData[(i * 5) + 3];
  26580. var indexCount = subMeshesData[(i * 5) + 4];
  26581. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  26582. }
  26583. }
  26584. }
  26585. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  26586. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  26587. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  26588. if (parsedGeometry.uvs) {
  26589. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  26590. }
  26591. if (parsedGeometry.uvs2) {
  26592. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  26593. }
  26594. if (parsedGeometry.uvs3) {
  26595. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  26596. }
  26597. if (parsedGeometry.uvs4) {
  26598. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  26599. }
  26600. if (parsedGeometry.uvs5) {
  26601. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  26602. }
  26603. if (parsedGeometry.uvs6) {
  26604. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  26605. }
  26606. if (parsedGeometry.colors) {
  26607. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  26608. }
  26609. if (parsedGeometry.matricesIndices) {
  26610. if (!parsedGeometry.matricesIndices._isExpanded) {
  26611. var floatIndices = [];
  26612. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  26613. var matricesIndex = parsedGeometry.matricesIndices[i];
  26614. floatIndices.push(matricesIndex & 0x000000FF);
  26615. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  26616. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  26617. floatIndices.push(matricesIndex >> 24);
  26618. }
  26619. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  26620. }
  26621. else {
  26622. delete parsedGeometry.matricesIndices._isExpanded;
  26623. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  26624. }
  26625. }
  26626. if (parsedGeometry.matricesIndicesExtra) {
  26627. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  26628. var floatIndices = [];
  26629. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  26630. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  26631. floatIndices.push(matricesIndex & 0x000000FF);
  26632. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  26633. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  26634. floatIndices.push(matricesIndex >> 24);
  26635. }
  26636. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  26637. }
  26638. else {
  26639. delete parsedGeometry.matricesIndices._isExpanded;
  26640. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  26641. }
  26642. }
  26643. if (parsedGeometry.matricesWeights) {
  26644. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  26645. }
  26646. if (parsedGeometry.matricesWeightsExtra) {
  26647. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  26648. }
  26649. mesh.setIndices(parsedGeometry.indices);
  26650. }
  26651. // SubMeshes
  26652. if (parsedGeometry.subMeshes) {
  26653. mesh.subMeshes = [];
  26654. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  26655. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  26656. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  26657. }
  26658. }
  26659. // Flat shading
  26660. if (mesh._shouldGenerateFlatShading) {
  26661. mesh.convertToFlatShadedMesh();
  26662. delete mesh._shouldGenerateFlatShading;
  26663. }
  26664. // Update
  26665. mesh.computeWorldMatrix(true);
  26666. // Octree
  26667. if (scene['_selectionOctree']) {
  26668. scene['_selectionOctree'].addMesh(mesh);
  26669. }
  26670. };
  26671. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  26672. if (scene.getGeometryByID(parsedVertexData.id)) {
  26673. return null; // null since geometry could be something else than a box...
  26674. }
  26675. var geometry = new Geometry(parsedVertexData.id, scene);
  26676. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  26677. if (parsedVertexData.delayLoadingFile) {
  26678. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26679. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  26680. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  26681. geometry._delayInfo = [];
  26682. if (parsedVertexData.hasUVs) {
  26683. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  26684. }
  26685. if (parsedVertexData.hasUVs2) {
  26686. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  26687. }
  26688. if (parsedVertexData.hasUVs3) {
  26689. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  26690. }
  26691. if (parsedVertexData.hasUVs4) {
  26692. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  26693. }
  26694. if (parsedVertexData.hasUVs5) {
  26695. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  26696. }
  26697. if (parsedVertexData.hasUVs6) {
  26698. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  26699. }
  26700. if (parsedVertexData.hasColors) {
  26701. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  26702. }
  26703. if (parsedVertexData.hasMatricesIndices) {
  26704. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  26705. }
  26706. if (parsedVertexData.hasMatricesWeights) {
  26707. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  26708. }
  26709. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  26710. }
  26711. else {
  26712. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  26713. }
  26714. scene.pushGeometry(geometry, true);
  26715. return geometry;
  26716. };
  26717. return Geometry;
  26718. }());
  26719. BABYLON.Geometry = Geometry;
  26720. /////// Primitives //////////////////////////////////////////////
  26721. (function (Geometry) {
  26722. var Primitives;
  26723. (function (Primitives) {
  26724. /// Abstract class
  26725. var _Primitive = (function (_super) {
  26726. __extends(_Primitive, _super);
  26727. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  26728. var _this = _super.call(this, id, scene, null, false, mesh) || this;
  26729. _this._canBeRegenerated = _canBeRegenerated;
  26730. _this._beingRegenerated = true;
  26731. _this.regenerate();
  26732. _this._beingRegenerated = false;
  26733. return _this;
  26734. }
  26735. _Primitive.prototype.canBeRegenerated = function () {
  26736. return this._canBeRegenerated;
  26737. };
  26738. _Primitive.prototype.regenerate = function () {
  26739. if (!this._canBeRegenerated) {
  26740. return;
  26741. }
  26742. this._beingRegenerated = true;
  26743. this.setAllVerticesData(this._regenerateVertexData(), false);
  26744. this._beingRegenerated = false;
  26745. };
  26746. _Primitive.prototype.asNewGeometry = function (id) {
  26747. return _super.prototype.copy.call(this, id);
  26748. };
  26749. // overrides
  26750. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  26751. if (!this._beingRegenerated) {
  26752. return;
  26753. }
  26754. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  26755. };
  26756. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  26757. if (!this._beingRegenerated) {
  26758. return;
  26759. }
  26760. _super.prototype.setVerticesData.call(this, kind, data, false);
  26761. };
  26762. // to override
  26763. // protected
  26764. _Primitive.prototype._regenerateVertexData = function () {
  26765. throw new Error("Abstract method");
  26766. };
  26767. _Primitive.prototype.copy = function (id) {
  26768. throw new Error("Must be overriden in sub-classes.");
  26769. };
  26770. _Primitive.prototype.serialize = function () {
  26771. var serializationObject = _super.prototype.serialize.call(this);
  26772. serializationObject.canBeRegenerated = this.canBeRegenerated();
  26773. return serializationObject;
  26774. };
  26775. return _Primitive;
  26776. }(Geometry));
  26777. Primitives._Primitive = _Primitive;
  26778. var Ribbon = (function (_super) {
  26779. __extends(Ribbon, _super);
  26780. // Members
  26781. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  26782. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26783. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  26784. _this.pathArray = pathArray;
  26785. _this.closeArray = closeArray;
  26786. _this.closePath = closePath;
  26787. _this.offset = offset;
  26788. _this.side = side;
  26789. return _this;
  26790. }
  26791. Ribbon.prototype._regenerateVertexData = function () {
  26792. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  26793. };
  26794. Ribbon.prototype.copy = function (id) {
  26795. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  26796. };
  26797. return Ribbon;
  26798. }(_Primitive));
  26799. Primitives.Ribbon = Ribbon;
  26800. var Box = (function (_super) {
  26801. __extends(Box, _super);
  26802. // Members
  26803. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  26804. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26805. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  26806. _this.size = size;
  26807. _this.side = side;
  26808. return _this;
  26809. }
  26810. Box.prototype._regenerateVertexData = function () {
  26811. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  26812. };
  26813. Box.prototype.copy = function (id) {
  26814. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  26815. };
  26816. Box.prototype.serialize = function () {
  26817. var serializationObject = _super.prototype.serialize.call(this);
  26818. serializationObject.size = this.size;
  26819. return serializationObject;
  26820. };
  26821. Box.Parse = function (parsedBox, scene) {
  26822. if (scene.getGeometryByID(parsedBox.id)) {
  26823. return null; // null since geometry could be something else than a box...
  26824. }
  26825. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  26826. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  26827. scene.pushGeometry(box, true);
  26828. return box;
  26829. };
  26830. return Box;
  26831. }(_Primitive));
  26832. Primitives.Box = Box;
  26833. var Sphere = (function (_super) {
  26834. __extends(Sphere, _super);
  26835. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  26836. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26837. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  26838. _this.segments = segments;
  26839. _this.diameter = diameter;
  26840. _this.side = side;
  26841. return _this;
  26842. }
  26843. Sphere.prototype._regenerateVertexData = function () {
  26844. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  26845. };
  26846. Sphere.prototype.copy = function (id) {
  26847. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  26848. };
  26849. Sphere.prototype.serialize = function () {
  26850. var serializationObject = _super.prototype.serialize.call(this);
  26851. serializationObject.segments = this.segments;
  26852. serializationObject.diameter = this.diameter;
  26853. return serializationObject;
  26854. };
  26855. Sphere.Parse = function (parsedSphere, scene) {
  26856. if (scene.getGeometryByID(parsedSphere.id)) {
  26857. return null; // null since geometry could be something else than a sphere...
  26858. }
  26859. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  26860. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  26861. scene.pushGeometry(sphere, true);
  26862. return sphere;
  26863. };
  26864. return Sphere;
  26865. }(_Primitive));
  26866. Primitives.Sphere = Sphere;
  26867. var Disc = (function (_super) {
  26868. __extends(Disc, _super);
  26869. // Members
  26870. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  26871. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26872. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  26873. _this.radius = radius;
  26874. _this.tessellation = tessellation;
  26875. _this.side = side;
  26876. return _this;
  26877. }
  26878. Disc.prototype._regenerateVertexData = function () {
  26879. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  26880. };
  26881. Disc.prototype.copy = function (id) {
  26882. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  26883. };
  26884. return Disc;
  26885. }(_Primitive));
  26886. Primitives.Disc = Disc;
  26887. var Cylinder = (function (_super) {
  26888. __extends(Cylinder, _super);
  26889. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  26890. if (subdivisions === void 0) { subdivisions = 1; }
  26891. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26892. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  26893. _this.height = height;
  26894. _this.diameterTop = diameterTop;
  26895. _this.diameterBottom = diameterBottom;
  26896. _this.tessellation = tessellation;
  26897. _this.subdivisions = subdivisions;
  26898. _this.side = side;
  26899. return _this;
  26900. }
  26901. Cylinder.prototype._regenerateVertexData = function () {
  26902. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  26903. };
  26904. Cylinder.prototype.copy = function (id) {
  26905. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  26906. };
  26907. Cylinder.prototype.serialize = function () {
  26908. var serializationObject = _super.prototype.serialize.call(this);
  26909. serializationObject.height = this.height;
  26910. serializationObject.diameterTop = this.diameterTop;
  26911. serializationObject.diameterBottom = this.diameterBottom;
  26912. serializationObject.tessellation = this.tessellation;
  26913. return serializationObject;
  26914. };
  26915. Cylinder.Parse = function (parsedCylinder, scene) {
  26916. if (scene.getGeometryByID(parsedCylinder.id)) {
  26917. return null; // null since geometry could be something else than a cylinder...
  26918. }
  26919. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  26920. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  26921. scene.pushGeometry(cylinder, true);
  26922. return cylinder;
  26923. };
  26924. return Cylinder;
  26925. }(_Primitive));
  26926. Primitives.Cylinder = Cylinder;
  26927. var Torus = (function (_super) {
  26928. __extends(Torus, _super);
  26929. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  26930. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26931. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  26932. _this.diameter = diameter;
  26933. _this.thickness = thickness;
  26934. _this.tessellation = tessellation;
  26935. _this.side = side;
  26936. return _this;
  26937. }
  26938. Torus.prototype._regenerateVertexData = function () {
  26939. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  26940. };
  26941. Torus.prototype.copy = function (id) {
  26942. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  26943. };
  26944. Torus.prototype.serialize = function () {
  26945. var serializationObject = _super.prototype.serialize.call(this);
  26946. serializationObject.diameter = this.diameter;
  26947. serializationObject.thickness = this.thickness;
  26948. serializationObject.tessellation = this.tessellation;
  26949. return serializationObject;
  26950. };
  26951. Torus.Parse = function (parsedTorus, scene) {
  26952. if (scene.getGeometryByID(parsedTorus.id)) {
  26953. return null; // null since geometry could be something else than a torus...
  26954. }
  26955. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  26956. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  26957. scene.pushGeometry(torus, true);
  26958. return torus;
  26959. };
  26960. return Torus;
  26961. }(_Primitive));
  26962. Primitives.Torus = Torus;
  26963. var Ground = (function (_super) {
  26964. __extends(Ground, _super);
  26965. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  26966. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  26967. _this.width = width;
  26968. _this.height = height;
  26969. _this.subdivisions = subdivisions;
  26970. return _this;
  26971. }
  26972. Ground.prototype._regenerateVertexData = function () {
  26973. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  26974. };
  26975. Ground.prototype.copy = function (id) {
  26976. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  26977. };
  26978. Ground.prototype.serialize = function () {
  26979. var serializationObject = _super.prototype.serialize.call(this);
  26980. serializationObject.width = this.width;
  26981. serializationObject.height = this.height;
  26982. serializationObject.subdivisions = this.subdivisions;
  26983. return serializationObject;
  26984. };
  26985. Ground.Parse = function (parsedGround, scene) {
  26986. if (scene.getGeometryByID(parsedGround.id)) {
  26987. return null; // null since geometry could be something else than a ground...
  26988. }
  26989. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  26990. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  26991. scene.pushGeometry(ground, true);
  26992. return ground;
  26993. };
  26994. return Ground;
  26995. }(_Primitive));
  26996. Primitives.Ground = Ground;
  26997. var TiledGround = (function (_super) {
  26998. __extends(TiledGround, _super);
  26999. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  27000. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  27001. _this.xmin = xmin;
  27002. _this.zmin = zmin;
  27003. _this.xmax = xmax;
  27004. _this.zmax = zmax;
  27005. _this.subdivisions = subdivisions;
  27006. _this.precision = precision;
  27007. return _this;
  27008. }
  27009. TiledGround.prototype._regenerateVertexData = function () {
  27010. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  27011. };
  27012. TiledGround.prototype.copy = function (id) {
  27013. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  27014. };
  27015. return TiledGround;
  27016. }(_Primitive));
  27017. Primitives.TiledGround = TiledGround;
  27018. var Plane = (function (_super) {
  27019. __extends(Plane, _super);
  27020. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  27021. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27022. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  27023. _this.size = size;
  27024. _this.side = side;
  27025. return _this;
  27026. }
  27027. Plane.prototype._regenerateVertexData = function () {
  27028. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  27029. };
  27030. Plane.prototype.copy = function (id) {
  27031. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  27032. };
  27033. Plane.prototype.serialize = function () {
  27034. var serializationObject = _super.prototype.serialize.call(this);
  27035. serializationObject.size = this.size;
  27036. return serializationObject;
  27037. };
  27038. Plane.Parse = function (parsedPlane, scene) {
  27039. if (scene.getGeometryByID(parsedPlane.id)) {
  27040. return null; // null since geometry could be something else than a ground...
  27041. }
  27042. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  27043. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  27044. scene.pushGeometry(plane, true);
  27045. return plane;
  27046. };
  27047. return Plane;
  27048. }(_Primitive));
  27049. Primitives.Plane = Plane;
  27050. var TorusKnot = (function (_super) {
  27051. __extends(TorusKnot, _super);
  27052. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  27053. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27054. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  27055. _this.radius = radius;
  27056. _this.tube = tube;
  27057. _this.radialSegments = radialSegments;
  27058. _this.tubularSegments = tubularSegments;
  27059. _this.p = p;
  27060. _this.q = q;
  27061. _this.side = side;
  27062. return _this;
  27063. }
  27064. TorusKnot.prototype._regenerateVertexData = function () {
  27065. 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 });
  27066. };
  27067. TorusKnot.prototype.copy = function (id) {
  27068. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  27069. };
  27070. TorusKnot.prototype.serialize = function () {
  27071. var serializationObject = _super.prototype.serialize.call(this);
  27072. serializationObject.radius = this.radius;
  27073. serializationObject.tube = this.tube;
  27074. serializationObject.radialSegments = this.radialSegments;
  27075. serializationObject.tubularSegments = this.tubularSegments;
  27076. serializationObject.p = this.p;
  27077. serializationObject.q = this.q;
  27078. return serializationObject;
  27079. };
  27080. ;
  27081. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  27082. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  27083. return null; // null since geometry could be something else than a ground...
  27084. }
  27085. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  27086. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  27087. scene.pushGeometry(torusKnot, true);
  27088. return torusKnot;
  27089. };
  27090. return TorusKnot;
  27091. }(_Primitive));
  27092. Primitives.TorusKnot = TorusKnot;
  27093. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  27094. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  27095. })(BABYLON || (BABYLON = {}));
  27096. //# sourceMappingURL=babylon.geometry.js.map
  27097. var BABYLON;
  27098. (function (BABYLON) {
  27099. var PostProcessManager = (function () {
  27100. function PostProcessManager(scene) {
  27101. this._vertexBuffers = {};
  27102. this._scene = scene;
  27103. }
  27104. PostProcessManager.prototype._prepareBuffers = function () {
  27105. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  27106. return;
  27107. }
  27108. // VBO
  27109. var vertices = [];
  27110. vertices.push(1, 1);
  27111. vertices.push(-1, 1);
  27112. vertices.push(-1, -1);
  27113. vertices.push(1, -1);
  27114. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  27115. // Indices
  27116. var indices = [];
  27117. indices.push(0);
  27118. indices.push(1);
  27119. indices.push(2);
  27120. indices.push(0);
  27121. indices.push(2);
  27122. indices.push(3);
  27123. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  27124. };
  27125. // Methods
  27126. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  27127. var postProcesses = this._scene.activeCamera._postProcesses;
  27128. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  27129. return false;
  27130. }
  27131. postProcesses[0].activate(this._scene.activeCamera, sourceTexture);
  27132. return true;
  27133. };
  27134. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  27135. var engine = this._scene.getEngine();
  27136. for (var index = 0; index < postProcesses.length; index++) {
  27137. if (index < postProcesses.length - 1) {
  27138. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  27139. }
  27140. else {
  27141. if (targetTexture) {
  27142. engine.bindFramebuffer(targetTexture);
  27143. }
  27144. else {
  27145. engine.restoreDefaultFramebuffer();
  27146. }
  27147. }
  27148. var pp = postProcesses[index];
  27149. var effect = pp.apply();
  27150. if (effect) {
  27151. pp.onBeforeRenderObservable.notifyObservers(effect);
  27152. // VBOs
  27153. this._prepareBuffers();
  27154. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  27155. // Draw order
  27156. engine.draw(true, 0, 6);
  27157. pp.onAfterRenderObservable.notifyObservers(effect);
  27158. }
  27159. }
  27160. // Restore depth buffer
  27161. engine.setDepthBuffer(true);
  27162. engine.setDepthWrite(true);
  27163. };
  27164. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  27165. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  27166. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  27167. return;
  27168. }
  27169. var engine = this._scene.getEngine();
  27170. for (var index = 0, len = postProcesses.length; index < len; index++) {
  27171. if (index < len - 1) {
  27172. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  27173. }
  27174. else {
  27175. if (targetTexture) {
  27176. engine.bindFramebuffer(targetTexture, faceIndex);
  27177. }
  27178. else {
  27179. engine.restoreDefaultFramebuffer();
  27180. }
  27181. }
  27182. if (doNotPresent) {
  27183. break;
  27184. }
  27185. var pp = postProcesses[index];
  27186. var effect = pp.apply();
  27187. if (effect) {
  27188. pp.onBeforeRenderObservable.notifyObservers(effect);
  27189. // VBOs
  27190. this._prepareBuffers();
  27191. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  27192. // Draw order
  27193. engine.draw(true, 0, 6);
  27194. pp.onAfterRenderObservable.notifyObservers(effect);
  27195. }
  27196. }
  27197. // Restore depth buffer
  27198. engine.setDepthBuffer(true);
  27199. engine.setDepthWrite(true);
  27200. };
  27201. PostProcessManager.prototype.dispose = function () {
  27202. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  27203. if (buffer) {
  27204. buffer.dispose();
  27205. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  27206. }
  27207. if (this._indexBuffer) {
  27208. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  27209. this._indexBuffer = null;
  27210. }
  27211. };
  27212. return PostProcessManager;
  27213. }());
  27214. BABYLON.PostProcessManager = PostProcessManager;
  27215. })(BABYLON || (BABYLON = {}));
  27216. //# sourceMappingURL=babylon.postProcessManager.js.map
  27217. var BABYLON;
  27218. (function (BABYLON) {
  27219. var StandardMaterialDefines = (function (_super) {
  27220. __extends(StandardMaterialDefines, _super);
  27221. function StandardMaterialDefines() {
  27222. var _this = _super.call(this) || this;
  27223. _this.DIFFUSE = false;
  27224. _this.AMBIENT = false;
  27225. _this.OPACITY = false;
  27226. _this.OPACITYRGB = false;
  27227. _this.REFLECTION = false;
  27228. _this.EMISSIVE = false;
  27229. _this.SPECULAR = false;
  27230. _this.BUMP = false;
  27231. _this.PARALLAX = false;
  27232. _this.PARALLAXOCCLUSION = false;
  27233. _this.SPECULAROVERALPHA = false;
  27234. _this.CLIPPLANE = false;
  27235. _this.ALPHATEST = false;
  27236. _this.ALPHAFROMDIFFUSE = false;
  27237. _this.POINTSIZE = false;
  27238. _this.FOG = false;
  27239. _this.SPECULARTERM = false;
  27240. _this.DIFFUSEFRESNEL = false;
  27241. _this.OPACITYFRESNEL = false;
  27242. _this.REFLECTIONFRESNEL = false;
  27243. _this.REFRACTIONFRESNEL = false;
  27244. _this.EMISSIVEFRESNEL = false;
  27245. _this.FRESNEL = false;
  27246. _this.NORMAL = false;
  27247. _this.UV1 = false;
  27248. _this.UV2 = false;
  27249. _this.VERTEXCOLOR = false;
  27250. _this.VERTEXALPHA = false;
  27251. _this.NUM_BONE_INFLUENCERS = 0;
  27252. _this.BonesPerMesh = 0;
  27253. _this.INSTANCES = false;
  27254. _this.GLOSSINESS = false;
  27255. _this.ROUGHNESS = false;
  27256. _this.EMISSIVEASILLUMINATION = false;
  27257. _this.LINKEMISSIVEWITHDIFFUSE = false;
  27258. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  27259. _this.LIGHTMAP = false;
  27260. _this.USELIGHTMAPASSHADOWMAP = false;
  27261. _this.REFLECTIONMAP_3D = false;
  27262. _this.REFLECTIONMAP_SPHERICAL = false;
  27263. _this.REFLECTIONMAP_PLANAR = false;
  27264. _this.REFLECTIONMAP_CUBIC = false;
  27265. _this.REFLECTIONMAP_PROJECTION = false;
  27266. _this.REFLECTIONMAP_SKYBOX = false;
  27267. _this.REFLECTIONMAP_EXPLICIT = false;
  27268. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  27269. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  27270. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  27271. _this.INVERTCUBICMAP = false;
  27272. _this.LOGARITHMICDEPTH = false;
  27273. _this.REFRACTION = false;
  27274. _this.REFRACTIONMAP_3D = false;
  27275. _this.REFLECTIONOVERALPHA = false;
  27276. _this.INVERTNORMALMAPX = false;
  27277. _this.INVERTNORMALMAPY = false;
  27278. _this.TWOSIDEDLIGHTING = false;
  27279. _this.SHADOWFULLFLOAT = false;
  27280. _this.CAMERACOLORGRADING = false;
  27281. _this.CAMERACOLORCURVES = false;
  27282. _this.MORPHTARGETS = false;
  27283. _this.MORPHTARGETS_NORMAL = false;
  27284. _this.MORPHTARGETS_TANGENT = false;
  27285. _this.NUM_MORPH_INFLUENCERS = 0;
  27286. _this.rebuild();
  27287. return _this;
  27288. }
  27289. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  27290. var modes = [
  27291. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  27292. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  27293. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  27294. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  27295. ];
  27296. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  27297. var mode = modes_1[_i];
  27298. this[mode] = (mode === modeToEnable);
  27299. }
  27300. };
  27301. return StandardMaterialDefines;
  27302. }(BABYLON.MaterialDefines));
  27303. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  27304. var StandardMaterial = (function (_super) {
  27305. __extends(StandardMaterial, _super);
  27306. function StandardMaterial(name, scene) {
  27307. var _this = _super.call(this, name, scene) || this;
  27308. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  27309. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  27310. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  27311. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  27312. _this.specularPower = 64;
  27313. _this._useAlphaFromDiffuseTexture = false;
  27314. _this._useEmissiveAsIllumination = false;
  27315. _this._linkEmissiveWithDiffuse = false;
  27316. _this._useSpecularOverAlpha = false;
  27317. _this._useReflectionOverAlpha = false;
  27318. _this._disableLighting = false;
  27319. _this._useParallax = false;
  27320. _this._useParallaxOcclusion = false;
  27321. _this.parallaxScaleBias = 0.05;
  27322. _this._roughness = 0;
  27323. _this.indexOfRefraction = 0.98;
  27324. _this.invertRefractionY = true;
  27325. _this._useLightmapAsShadowmap = false;
  27326. _this._useReflectionFresnelFromSpecular = false;
  27327. _this._useGlossinessFromSpecularMapAlpha = false;
  27328. _this._maxSimultaneousLights = 4;
  27329. /**
  27330. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  27331. */
  27332. _this._invertNormalMapX = false;
  27333. /**
  27334. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  27335. */
  27336. _this._invertNormalMapY = false;
  27337. /**
  27338. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  27339. */
  27340. _this._twoSidedLighting = false;
  27341. /**
  27342. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  27343. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  27344. * 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;
  27345. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  27346. */
  27347. _this._cameraColorCurves = null;
  27348. _this._renderTargets = new BABYLON.SmartArray(16);
  27349. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  27350. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  27351. _this.getRenderTargetTextures = function () {
  27352. _this._renderTargets.reset();
  27353. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  27354. _this._renderTargets.push(_this._reflectionTexture);
  27355. }
  27356. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  27357. _this._renderTargets.push(_this._refractionTexture);
  27358. }
  27359. return _this._renderTargets;
  27360. };
  27361. return _this;
  27362. }
  27363. StandardMaterial.prototype.getClassName = function () {
  27364. return "StandardMaterial";
  27365. };
  27366. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  27367. get: function () {
  27368. return this._useLogarithmicDepth;
  27369. },
  27370. set: function (value) {
  27371. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  27372. this._markAllSubMeshesAsMiscDirty();
  27373. },
  27374. enumerable: true,
  27375. configurable: true
  27376. });
  27377. StandardMaterial.prototype.needAlphaBlending = function () {
  27378. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  27379. };
  27380. StandardMaterial.prototype.needAlphaTesting = function () {
  27381. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  27382. };
  27383. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  27384. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  27385. };
  27386. StandardMaterial.prototype.getAlphaTestTexture = function () {
  27387. return this._diffuseTexture;
  27388. };
  27389. /**
  27390. * Child classes can use it to update shaders
  27391. */
  27392. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  27393. if (this.isFrozen) {
  27394. if (this._wasPreviouslyReady && subMesh.effect) {
  27395. return true;
  27396. }
  27397. }
  27398. if (!subMesh._materialDefines) {
  27399. subMesh._materialDefines = new StandardMaterialDefines();
  27400. }
  27401. var scene = this.getScene();
  27402. var defines = subMesh._materialDefines;
  27403. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  27404. if (defines._renderId === scene.getRenderId()) {
  27405. return true;
  27406. }
  27407. }
  27408. var engine = scene.getEngine();
  27409. // Lights
  27410. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  27411. // Textures
  27412. if (defines._areTexturesDirty) {
  27413. defines._needUVs = false;
  27414. if (scene.texturesEnabled) {
  27415. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  27416. if (!this._diffuseTexture.isReady()) {
  27417. return false;
  27418. }
  27419. else {
  27420. defines._needUVs = true;
  27421. defines.DIFFUSE = true;
  27422. }
  27423. }
  27424. else {
  27425. defines.DIFFUSE = false;
  27426. }
  27427. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  27428. if (!this._ambientTexture.isReady()) {
  27429. return false;
  27430. }
  27431. else {
  27432. defines._needUVs = true;
  27433. defines.AMBIENT = true;
  27434. }
  27435. }
  27436. else {
  27437. defines.AMBIENT = false;
  27438. }
  27439. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  27440. if (!this._opacityTexture.isReady()) {
  27441. return false;
  27442. }
  27443. else {
  27444. defines._needUVs = true;
  27445. defines.OPACITY = true;
  27446. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  27447. }
  27448. }
  27449. else {
  27450. defines.OPACITY = false;
  27451. }
  27452. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  27453. if (!this._reflectionTexture.isReady()) {
  27454. return false;
  27455. }
  27456. else {
  27457. defines._needNormals = true;
  27458. defines.REFLECTION = true;
  27459. defines.ROUGHNESS = (this._roughness > 0);
  27460. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  27461. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  27462. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  27463. switch (this._reflectionTexture.coordinatesMode) {
  27464. case BABYLON.Texture.CUBIC_MODE:
  27465. case BABYLON.Texture.INVCUBIC_MODE:
  27466. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  27467. break;
  27468. case BABYLON.Texture.EXPLICIT_MODE:
  27469. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  27470. break;
  27471. case BABYLON.Texture.PLANAR_MODE:
  27472. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  27473. break;
  27474. case BABYLON.Texture.PROJECTION_MODE:
  27475. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  27476. break;
  27477. case BABYLON.Texture.SKYBOX_MODE:
  27478. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  27479. break;
  27480. case BABYLON.Texture.SPHERICAL_MODE:
  27481. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  27482. break;
  27483. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  27484. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  27485. break;
  27486. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  27487. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  27488. break;
  27489. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  27490. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  27491. break;
  27492. }
  27493. }
  27494. }
  27495. else {
  27496. defines.REFLECTION = false;
  27497. }
  27498. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  27499. if (!this._emissiveTexture.isReady()) {
  27500. return false;
  27501. }
  27502. else {
  27503. defines._needUVs = true;
  27504. defines.EMISSIVE = true;
  27505. }
  27506. }
  27507. else {
  27508. defines.EMISSIVE = false;
  27509. }
  27510. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  27511. if (!this._lightmapTexture.isReady()) {
  27512. return false;
  27513. }
  27514. else {
  27515. defines._needUVs = true;
  27516. defines.LIGHTMAP = true;
  27517. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  27518. }
  27519. }
  27520. else {
  27521. defines.LIGHTMAP = false;
  27522. }
  27523. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  27524. if (!this._specularTexture.isReady()) {
  27525. return false;
  27526. }
  27527. else {
  27528. defines._needUVs = true;
  27529. defines.SPECULAR = true;
  27530. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  27531. }
  27532. }
  27533. else {
  27534. defines.SPECULAR = false;
  27535. }
  27536. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  27537. if (!this._bumpTexture.isReady()) {
  27538. return false;
  27539. }
  27540. else {
  27541. defines._needUVs = true;
  27542. defines.BUMP = true;
  27543. defines.INVERTNORMALMAPX = this.invertNormalMapX;
  27544. defines.INVERTNORMALMAPY = this.invertNormalMapY;
  27545. defines.PARALLAX = this._useParallax;
  27546. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  27547. }
  27548. }
  27549. else {
  27550. defines.BUMP = false;
  27551. }
  27552. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  27553. if (!this._refractionTexture.isReady()) {
  27554. return false;
  27555. }
  27556. else {
  27557. defines._needUVs = true;
  27558. defines.REFRACTION = true;
  27559. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  27560. }
  27561. }
  27562. else {
  27563. defines.REFRACTION = false;
  27564. }
  27565. if (this._cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  27566. if (!this._cameraColorGradingTexture.isReady()) {
  27567. return false;
  27568. }
  27569. else {
  27570. defines.CAMERACOLORGRADING = true;
  27571. }
  27572. }
  27573. else {
  27574. defines.CAMERACOLORGRADING = false;
  27575. }
  27576. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  27577. }
  27578. else {
  27579. defines.DIFFUSE = false;
  27580. defines.AMBIENT = false;
  27581. defines.OPACITY = false;
  27582. defines.REFLECTION = false;
  27583. defines.EMISSIVE = false;
  27584. defines.LIGHTMAP = false;
  27585. defines.BUMP = false;
  27586. defines.REFRACTION = false;
  27587. defines.CAMERACOLORGRADING = false;
  27588. }
  27589. defines.CAMERACOLORCURVES = (this._cameraColorCurves !== undefined && this._cameraColorCurves !== null);
  27590. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  27591. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  27592. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  27593. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  27594. }
  27595. if (defines._areFresnelDirty) {
  27596. if (StandardMaterial.FresnelEnabled) {
  27597. // Fresnel
  27598. if (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled ||
  27599. this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled ||
  27600. this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled ||
  27601. this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled ||
  27602. this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled) {
  27603. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  27604. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  27605. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  27606. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  27607. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  27608. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  27609. defines._needNormals = true;
  27610. defines.FRESNEL = true;
  27611. }
  27612. }
  27613. else {
  27614. defines.FRESNEL = false;
  27615. }
  27616. }
  27617. // Misc.
  27618. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  27619. // Attribs
  27620. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  27621. // Values that need to be evaluated on every frame
  27622. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  27623. if (scene._mirroredCameraPosition && defines.BUMP) {
  27624. defines.INVERTNORMALMAPX = !this.invertNormalMapX;
  27625. defines.INVERTNORMALMAPY = !this.invertNormalMapY;
  27626. defines.markAsUnprocessed();
  27627. }
  27628. // Get correct effect
  27629. if (defines.isDirty) {
  27630. defines.markAsProcessed();
  27631. scene.resetCachedMaterial();
  27632. // Fallbacks
  27633. var fallbacks = new BABYLON.EffectFallbacks();
  27634. if (defines.REFLECTION) {
  27635. fallbacks.addFallback(0, "REFLECTION");
  27636. }
  27637. if (defines.SPECULAR) {
  27638. fallbacks.addFallback(0, "SPECULAR");
  27639. }
  27640. if (defines.BUMP) {
  27641. fallbacks.addFallback(0, "BUMP");
  27642. }
  27643. if (defines.PARALLAX) {
  27644. fallbacks.addFallback(1, "PARALLAX");
  27645. }
  27646. if (defines.PARALLAXOCCLUSION) {
  27647. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  27648. }
  27649. if (defines.SPECULAROVERALPHA) {
  27650. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  27651. }
  27652. if (defines.FOG) {
  27653. fallbacks.addFallback(1, "FOG");
  27654. }
  27655. if (defines.POINTSIZE) {
  27656. fallbacks.addFallback(0, "POINTSIZE");
  27657. }
  27658. if (defines.LOGARITHMICDEPTH) {
  27659. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  27660. }
  27661. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  27662. if (defines.SPECULARTERM) {
  27663. fallbacks.addFallback(0, "SPECULARTERM");
  27664. }
  27665. if (defines.DIFFUSEFRESNEL) {
  27666. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  27667. }
  27668. if (defines.OPACITYFRESNEL) {
  27669. fallbacks.addFallback(2, "OPACITYFRESNEL");
  27670. }
  27671. if (defines.REFLECTIONFRESNEL) {
  27672. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  27673. }
  27674. if (defines.EMISSIVEFRESNEL) {
  27675. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  27676. }
  27677. if (defines.FRESNEL) {
  27678. fallbacks.addFallback(4, "FRESNEL");
  27679. }
  27680. //Attributes
  27681. var attribs = [BABYLON.VertexBuffer.PositionKind];
  27682. if (defines.NORMAL) {
  27683. attribs.push(BABYLON.VertexBuffer.NormalKind);
  27684. }
  27685. if (defines.UV1) {
  27686. attribs.push(BABYLON.VertexBuffer.UVKind);
  27687. }
  27688. if (defines.UV2) {
  27689. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  27690. }
  27691. if (defines.VERTEXCOLOR) {
  27692. attribs.push(BABYLON.VertexBuffer.ColorKind);
  27693. }
  27694. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  27695. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  27696. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  27697. var shaderName = "default";
  27698. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  27699. "vFogInfos", "vFogColor", "pointSize",
  27700. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  27701. "mBones",
  27702. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  27703. "depthValues",
  27704. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  27705. "logarithmicDepthConstant"
  27706. ];
  27707. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  27708. var uniformBuffers = ["Material", "Scene"];
  27709. if (defines.CAMERACOLORCURVES) {
  27710. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  27711. }
  27712. if (defines.CAMERACOLORGRADING) {
  27713. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  27714. }
  27715. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  27716. uniformsNames: uniforms,
  27717. uniformBuffersNames: uniformBuffers,
  27718. samplers: samplers,
  27719. defines: defines,
  27720. maxSimultaneousLights: this._maxSimultaneousLights
  27721. });
  27722. if (this.customShaderNameResolve) {
  27723. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  27724. }
  27725. var join = defines.toString();
  27726. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  27727. attributes: attribs,
  27728. uniformsNames: uniforms,
  27729. uniformBuffersNames: uniformBuffers,
  27730. samplers: samplers,
  27731. defines: join,
  27732. fallbacks: fallbacks,
  27733. onCompiled: this.onCompiled,
  27734. onError: this.onError,
  27735. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  27736. }, engine), defines);
  27737. this.buildUniformLayout();
  27738. }
  27739. if (!subMesh.effect.isReady()) {
  27740. return false;
  27741. }
  27742. defines._renderId = scene.getRenderId();
  27743. this._wasPreviouslyReady = true;
  27744. return true;
  27745. };
  27746. StandardMaterial.prototype.buildUniformLayout = function () {
  27747. // Order is important !
  27748. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  27749. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  27750. this._uniformBuffer.addUniform("opacityParts", 4);
  27751. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  27752. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  27753. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  27754. this._uniformBuffer.addUniform("refractionRightColor", 4);
  27755. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  27756. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  27757. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  27758. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  27759. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  27760. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  27761. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  27762. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  27763. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  27764. this._uniformBuffer.addUniform("vBumpInfos", 3);
  27765. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  27766. this._uniformBuffer.addUniform("ambientMatrix", 16);
  27767. this._uniformBuffer.addUniform("opacityMatrix", 16);
  27768. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  27769. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  27770. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  27771. this._uniformBuffer.addUniform("specularMatrix", 16);
  27772. this._uniformBuffer.addUniform("bumpMatrix", 16);
  27773. this._uniformBuffer.addUniform("refractionMatrix", 16);
  27774. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  27775. this._uniformBuffer.addUniform("vSpecularColor", 4);
  27776. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  27777. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  27778. this._uniformBuffer.addUniform("pointSize", 1);
  27779. this._uniformBuffer.create();
  27780. };
  27781. StandardMaterial.prototype.unbind = function () {
  27782. if (this._activeEffect) {
  27783. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  27784. this._activeEffect.setTexture("reflection2DSampler", null);
  27785. }
  27786. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  27787. this._activeEffect.setTexture("refraction2DSampler", null);
  27788. }
  27789. }
  27790. _super.prototype.unbind.call(this);
  27791. };
  27792. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  27793. var scene = this.getScene();
  27794. var defines = subMesh._materialDefines;
  27795. if (!defines) {
  27796. return;
  27797. }
  27798. var effect = subMesh.effect;
  27799. this._activeEffect = effect;
  27800. // Matrices
  27801. this.bindOnlyWorldMatrix(world);
  27802. // Bones
  27803. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  27804. if (this._mustRebind(scene, effect, mesh.visibility)) {
  27805. this._uniformBuffer.bindToEffect(effect, "Material");
  27806. this.bindViewProjection(effect);
  27807. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  27808. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  27809. // Fresnel
  27810. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  27811. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  27812. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  27813. }
  27814. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  27815. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  27816. }
  27817. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  27818. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  27819. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  27820. }
  27821. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  27822. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  27823. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  27824. }
  27825. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  27826. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  27827. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  27828. }
  27829. }
  27830. // Textures
  27831. if (scene.texturesEnabled) {
  27832. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  27833. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  27834. this._uniformBuffer.updateMatrix("diffuseMatrix", this._diffuseTexture.getTextureMatrix());
  27835. }
  27836. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  27837. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  27838. this._uniformBuffer.updateMatrix("ambientMatrix", this._ambientTexture.getTextureMatrix());
  27839. }
  27840. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  27841. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  27842. this._uniformBuffer.updateMatrix("opacityMatrix", this._opacityTexture.getTextureMatrix());
  27843. }
  27844. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  27845. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  27846. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  27847. }
  27848. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  27849. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  27850. this._uniformBuffer.updateMatrix("emissiveMatrix", this._emissiveTexture.getTextureMatrix());
  27851. }
  27852. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  27853. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  27854. this._uniformBuffer.updateMatrix("lightmapMatrix", this._lightmapTexture.getTextureMatrix());
  27855. }
  27856. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  27857. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  27858. this._uniformBuffer.updateMatrix("specularMatrix", this._specularTexture.getTextureMatrix());
  27859. }
  27860. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  27861. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  27862. this._uniformBuffer.updateMatrix("bumpMatrix", this._bumpTexture.getTextureMatrix());
  27863. }
  27864. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  27865. var depth = 1.0;
  27866. if (!this._refractionTexture.isCube) {
  27867. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  27868. if (this._refractionTexture.depth) {
  27869. depth = this._refractionTexture.depth;
  27870. }
  27871. }
  27872. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  27873. }
  27874. }
  27875. // Point size
  27876. if (this.pointsCloud) {
  27877. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  27878. }
  27879. if (defines.SPECULARTERM) {
  27880. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  27881. }
  27882. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  27883. // Diffuse
  27884. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  27885. }
  27886. // Textures
  27887. if (scene.texturesEnabled) {
  27888. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  27889. effect.setTexture("diffuseSampler", this._diffuseTexture);
  27890. }
  27891. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  27892. effect.setTexture("ambientSampler", this._ambientTexture);
  27893. }
  27894. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  27895. effect.setTexture("opacitySampler", this._opacityTexture);
  27896. }
  27897. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  27898. if (this._reflectionTexture.isCube) {
  27899. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  27900. }
  27901. else {
  27902. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  27903. }
  27904. }
  27905. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  27906. effect.setTexture("emissiveSampler", this._emissiveTexture);
  27907. }
  27908. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  27909. effect.setTexture("lightmapSampler", this._lightmapTexture);
  27910. }
  27911. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  27912. effect.setTexture("specularSampler", this._specularTexture);
  27913. }
  27914. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  27915. effect.setTexture("bumpSampler", this._bumpTexture);
  27916. }
  27917. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  27918. var depth = 1.0;
  27919. if (this._refractionTexture.isCube) {
  27920. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  27921. }
  27922. else {
  27923. effect.setTexture("refraction2DSampler", this._refractionTexture);
  27924. }
  27925. }
  27926. if (this._cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  27927. BABYLON.ColorGradingTexture.Bind(this._cameraColorGradingTexture, effect);
  27928. }
  27929. }
  27930. // Clip plane
  27931. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  27932. // Colors
  27933. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  27934. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  27935. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  27936. }
  27937. if (this._mustRebind(scene, effect) || !this.isFrozen) {
  27938. // Lights
  27939. if (scene.lightsEnabled && !this._disableLighting) {
  27940. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  27941. }
  27942. // View
  27943. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  27944. this.bindView(effect);
  27945. }
  27946. // Fog
  27947. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  27948. // Morph targets
  27949. if (defines.NUM_MORPH_INFLUENCERS) {
  27950. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  27951. }
  27952. // Log. depth
  27953. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  27954. // Color Curves
  27955. if (this._cameraColorCurves) {
  27956. BABYLON.ColorCurves.Bind(this._cameraColorCurves, effect);
  27957. }
  27958. }
  27959. this._uniformBuffer.update();
  27960. this._afterBind(mesh, this._activeEffect);
  27961. };
  27962. StandardMaterial.prototype.getAnimatables = function () {
  27963. var results = [];
  27964. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  27965. results.push(this._diffuseTexture);
  27966. }
  27967. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  27968. results.push(this._ambientTexture);
  27969. }
  27970. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  27971. results.push(this._opacityTexture);
  27972. }
  27973. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  27974. results.push(this._reflectionTexture);
  27975. }
  27976. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  27977. results.push(this._emissiveTexture);
  27978. }
  27979. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  27980. results.push(this._specularTexture);
  27981. }
  27982. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  27983. results.push(this._bumpTexture);
  27984. }
  27985. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  27986. results.push(this._lightmapTexture);
  27987. }
  27988. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  27989. results.push(this._refractionTexture);
  27990. }
  27991. if (this._cameraColorGradingTexture && this._cameraColorGradingTexture.animations && this._cameraColorGradingTexture.animations.length > 0) {
  27992. results.push(this._cameraColorGradingTexture);
  27993. }
  27994. return results;
  27995. };
  27996. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  27997. if (forceDisposeTextures) {
  27998. if (this._diffuseTexture) {
  27999. this._diffuseTexture.dispose();
  28000. }
  28001. if (this._ambientTexture) {
  28002. this._ambientTexture.dispose();
  28003. }
  28004. if (this._opacityTexture) {
  28005. this._opacityTexture.dispose();
  28006. }
  28007. if (this._reflectionTexture) {
  28008. this._reflectionTexture.dispose();
  28009. }
  28010. if (this._emissiveTexture) {
  28011. this._emissiveTexture.dispose();
  28012. }
  28013. if (this._specularTexture) {
  28014. this._specularTexture.dispose();
  28015. }
  28016. if (this._bumpTexture) {
  28017. this._bumpTexture.dispose();
  28018. }
  28019. if (this._lightmapTexture) {
  28020. this._lightmapTexture.dispose();
  28021. }
  28022. if (this._refractionTexture) {
  28023. this._refractionTexture.dispose();
  28024. }
  28025. if (this._cameraColorGradingTexture) {
  28026. this._cameraColorGradingTexture.dispose();
  28027. }
  28028. }
  28029. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  28030. };
  28031. StandardMaterial.prototype.clone = function (name) {
  28032. var _this = this;
  28033. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  28034. result.name = name;
  28035. result.id = name;
  28036. return result;
  28037. };
  28038. StandardMaterial.prototype.serialize = function () {
  28039. return BABYLON.SerializationHelper.Serialize(this);
  28040. };
  28041. // Statics
  28042. StandardMaterial.Parse = function (source, scene, rootUrl) {
  28043. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  28044. };
  28045. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  28046. get: function () {
  28047. return StandardMaterial._DiffuseTextureEnabled;
  28048. },
  28049. set: function (value) {
  28050. if (StandardMaterial._DiffuseTextureEnabled === value) {
  28051. return;
  28052. }
  28053. StandardMaterial._DiffuseTextureEnabled = value;
  28054. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28055. },
  28056. enumerable: true,
  28057. configurable: true
  28058. });
  28059. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  28060. get: function () {
  28061. return StandardMaterial._AmbientTextureEnabled;
  28062. },
  28063. set: function (value) {
  28064. if (StandardMaterial._AmbientTextureEnabled === value) {
  28065. return;
  28066. }
  28067. StandardMaterial._AmbientTextureEnabled = value;
  28068. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28069. },
  28070. enumerable: true,
  28071. configurable: true
  28072. });
  28073. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  28074. get: function () {
  28075. return StandardMaterial._OpacityTextureEnabled;
  28076. },
  28077. set: function (value) {
  28078. if (StandardMaterial._OpacityTextureEnabled === value) {
  28079. return;
  28080. }
  28081. StandardMaterial._OpacityTextureEnabled = value;
  28082. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28083. },
  28084. enumerable: true,
  28085. configurable: true
  28086. });
  28087. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  28088. get: function () {
  28089. return StandardMaterial._ReflectionTextureEnabled;
  28090. },
  28091. set: function (value) {
  28092. if (StandardMaterial._ReflectionTextureEnabled === value) {
  28093. return;
  28094. }
  28095. StandardMaterial._ReflectionTextureEnabled = value;
  28096. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28097. },
  28098. enumerable: true,
  28099. configurable: true
  28100. });
  28101. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  28102. get: function () {
  28103. return StandardMaterial._EmissiveTextureEnabled;
  28104. },
  28105. set: function (value) {
  28106. if (StandardMaterial._EmissiveTextureEnabled === value) {
  28107. return;
  28108. }
  28109. StandardMaterial._EmissiveTextureEnabled = value;
  28110. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28111. },
  28112. enumerable: true,
  28113. configurable: true
  28114. });
  28115. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  28116. get: function () {
  28117. return StandardMaterial._SpecularTextureEnabled;
  28118. },
  28119. set: function (value) {
  28120. if (StandardMaterial._SpecularTextureEnabled === value) {
  28121. return;
  28122. }
  28123. StandardMaterial._SpecularTextureEnabled = value;
  28124. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28125. },
  28126. enumerable: true,
  28127. configurable: true
  28128. });
  28129. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  28130. get: function () {
  28131. return StandardMaterial._BumpTextureEnabled;
  28132. },
  28133. set: function (value) {
  28134. if (StandardMaterial._BumpTextureEnabled === value) {
  28135. return;
  28136. }
  28137. StandardMaterial._BumpTextureEnabled = value;
  28138. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28139. },
  28140. enumerable: true,
  28141. configurable: true
  28142. });
  28143. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  28144. get: function () {
  28145. return StandardMaterial._LightmapTextureEnabled;
  28146. },
  28147. set: function (value) {
  28148. if (StandardMaterial._LightmapTextureEnabled === value) {
  28149. return;
  28150. }
  28151. StandardMaterial._LightmapTextureEnabled = value;
  28152. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28153. },
  28154. enumerable: true,
  28155. configurable: true
  28156. });
  28157. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  28158. get: function () {
  28159. return StandardMaterial._RefractionTextureEnabled;
  28160. },
  28161. set: function (value) {
  28162. if (StandardMaterial._RefractionTextureEnabled === value) {
  28163. return;
  28164. }
  28165. StandardMaterial._RefractionTextureEnabled = value;
  28166. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28167. },
  28168. enumerable: true,
  28169. configurable: true
  28170. });
  28171. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  28172. get: function () {
  28173. return StandardMaterial._ColorGradingTextureEnabled;
  28174. },
  28175. set: function (value) {
  28176. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  28177. return;
  28178. }
  28179. StandardMaterial._ColorGradingTextureEnabled = value;
  28180. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28181. },
  28182. enumerable: true,
  28183. configurable: true
  28184. });
  28185. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  28186. get: function () {
  28187. return StandardMaterial._FresnelEnabled;
  28188. },
  28189. set: function (value) {
  28190. if (StandardMaterial._FresnelEnabled === value) {
  28191. return;
  28192. }
  28193. StandardMaterial._FresnelEnabled = value;
  28194. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  28195. },
  28196. enumerable: true,
  28197. configurable: true
  28198. });
  28199. return StandardMaterial;
  28200. }(BABYLON.PushMaterial));
  28201. // Flags used to enable or disable a type of texture for all Standard Materials
  28202. StandardMaterial._DiffuseTextureEnabled = true;
  28203. StandardMaterial._AmbientTextureEnabled = true;
  28204. StandardMaterial._OpacityTextureEnabled = true;
  28205. StandardMaterial._ReflectionTextureEnabled = true;
  28206. StandardMaterial._EmissiveTextureEnabled = true;
  28207. StandardMaterial._SpecularTextureEnabled = true;
  28208. StandardMaterial._BumpTextureEnabled = true;
  28209. StandardMaterial._LightmapTextureEnabled = true;
  28210. StandardMaterial._RefractionTextureEnabled = true;
  28211. StandardMaterial._ColorGradingTextureEnabled = true;
  28212. StandardMaterial._FresnelEnabled = true;
  28213. __decorate([
  28214. BABYLON.serializeAsTexture("diffuseTexture")
  28215. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  28216. __decorate([
  28217. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28218. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  28219. __decorate([
  28220. BABYLON.serializeAsTexture("ambientTexture")
  28221. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  28222. __decorate([
  28223. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28224. ], StandardMaterial.prototype, "ambientTexture", void 0);
  28225. __decorate([
  28226. BABYLON.serializeAsTexture("opacityTexture")
  28227. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  28228. __decorate([
  28229. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28230. ], StandardMaterial.prototype, "opacityTexture", void 0);
  28231. __decorate([
  28232. BABYLON.serializeAsTexture("reflectionTexture")
  28233. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  28234. __decorate([
  28235. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28236. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  28237. __decorate([
  28238. BABYLON.serializeAsTexture("emissiveTexture")
  28239. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  28240. __decorate([
  28241. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28242. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  28243. __decorate([
  28244. BABYLON.serializeAsTexture("specularTexture")
  28245. ], StandardMaterial.prototype, "_specularTexture", void 0);
  28246. __decorate([
  28247. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28248. ], StandardMaterial.prototype, "specularTexture", void 0);
  28249. __decorate([
  28250. BABYLON.serializeAsTexture("bumpTexture")
  28251. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  28252. __decorate([
  28253. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28254. ], StandardMaterial.prototype, "bumpTexture", void 0);
  28255. __decorate([
  28256. BABYLON.serializeAsTexture("lightmapTexture")
  28257. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  28258. __decorate([
  28259. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28260. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  28261. __decorate([
  28262. BABYLON.serializeAsTexture("refractionTexture")
  28263. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  28264. __decorate([
  28265. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28266. ], StandardMaterial.prototype, "refractionTexture", void 0);
  28267. __decorate([
  28268. BABYLON.serializeAsColor3("ambient")
  28269. ], StandardMaterial.prototype, "ambientColor", void 0);
  28270. __decorate([
  28271. BABYLON.serializeAsColor3("diffuse")
  28272. ], StandardMaterial.prototype, "diffuseColor", void 0);
  28273. __decorate([
  28274. BABYLON.serializeAsColor3("specular")
  28275. ], StandardMaterial.prototype, "specularColor", void 0);
  28276. __decorate([
  28277. BABYLON.serializeAsColor3("emissive")
  28278. ], StandardMaterial.prototype, "emissiveColor", void 0);
  28279. __decorate([
  28280. BABYLON.serialize()
  28281. ], StandardMaterial.prototype, "specularPower", void 0);
  28282. __decorate([
  28283. BABYLON.serialize("useAlphaFromDiffuseTexture")
  28284. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  28285. __decorate([
  28286. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28287. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  28288. __decorate([
  28289. BABYLON.serialize("useEmissiveAsIllumination")
  28290. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  28291. __decorate([
  28292. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28293. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  28294. __decorate([
  28295. BABYLON.serialize("linkEmissiveWithDiffuse")
  28296. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  28297. __decorate([
  28298. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28299. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  28300. __decorate([
  28301. BABYLON.serialize("useSpecularOverAlpha")
  28302. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  28303. __decorate([
  28304. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28305. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  28306. __decorate([
  28307. BABYLON.serialize("useReflectionOverAlpha")
  28308. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  28309. __decorate([
  28310. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28311. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  28312. __decorate([
  28313. BABYLON.serialize("disableLighting")
  28314. ], StandardMaterial.prototype, "_disableLighting", void 0);
  28315. __decorate([
  28316. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  28317. ], StandardMaterial.prototype, "disableLighting", void 0);
  28318. __decorate([
  28319. BABYLON.serialize("useParallax")
  28320. ], StandardMaterial.prototype, "_useParallax", void 0);
  28321. __decorate([
  28322. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28323. ], StandardMaterial.prototype, "useParallax", void 0);
  28324. __decorate([
  28325. BABYLON.serialize("useParallaxOcclusion")
  28326. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  28327. __decorate([
  28328. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28329. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  28330. __decorate([
  28331. BABYLON.serialize()
  28332. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  28333. __decorate([
  28334. BABYLON.serialize("roughness")
  28335. ], StandardMaterial.prototype, "_roughness", void 0);
  28336. __decorate([
  28337. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28338. ], StandardMaterial.prototype, "roughness", void 0);
  28339. __decorate([
  28340. BABYLON.serialize()
  28341. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  28342. __decorate([
  28343. BABYLON.serialize()
  28344. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  28345. __decorate([
  28346. BABYLON.serialize("useLightmapAsShadowmap")
  28347. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  28348. __decorate([
  28349. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28350. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  28351. __decorate([
  28352. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  28353. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  28354. __decorate([
  28355. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  28356. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  28357. __decorate([
  28358. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  28359. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  28360. __decorate([
  28361. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  28362. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  28363. __decorate([
  28364. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  28365. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  28366. __decorate([
  28367. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  28368. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  28369. __decorate([
  28370. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  28371. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  28372. __decorate([
  28373. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  28374. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  28375. __decorate([
  28376. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  28377. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  28378. __decorate([
  28379. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  28380. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  28381. __decorate([
  28382. BABYLON.serialize("useReflectionFresnelFromSpecular")
  28383. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  28384. __decorate([
  28385. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  28386. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  28387. __decorate([
  28388. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  28389. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  28390. __decorate([
  28391. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28392. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  28393. __decorate([
  28394. BABYLON.serialize("maxSimultaneousLights")
  28395. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  28396. __decorate([
  28397. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  28398. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  28399. __decorate([
  28400. BABYLON.serialize("invertNormalMapX")
  28401. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  28402. __decorate([
  28403. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28404. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  28405. __decorate([
  28406. BABYLON.serialize("invertNormalMapY")
  28407. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  28408. __decorate([
  28409. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28410. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  28411. __decorate([
  28412. BABYLON.serialize("twoSidedLighting")
  28413. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  28414. __decorate([
  28415. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28416. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  28417. __decorate([
  28418. BABYLON.serializeAsTexture("cameraColorGradingTexture")
  28419. ], StandardMaterial.prototype, "_cameraColorGradingTexture", void 0);
  28420. __decorate([
  28421. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28422. ], StandardMaterial.prototype, "cameraColorGradingTexture", void 0);
  28423. __decorate([
  28424. BABYLON.serializeAsColorCurves("cameraColorCurves")
  28425. ], StandardMaterial.prototype, "_cameraColorCurves", void 0);
  28426. __decorate([
  28427. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28428. ], StandardMaterial.prototype, "cameraColorCurves", void 0);
  28429. __decorate([
  28430. BABYLON.serialize()
  28431. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  28432. BABYLON.StandardMaterial = StandardMaterial;
  28433. })(BABYLON || (BABYLON = {}));
  28434. //# sourceMappingURL=babylon.standardMaterial.js.map
  28435. var BABYLON;
  28436. (function (BABYLON) {
  28437. var PBRMaterialDefines = (function (_super) {
  28438. __extends(PBRMaterialDefines, _super);
  28439. function PBRMaterialDefines() {
  28440. var _this = _super.call(this) || this;
  28441. _this.ALBEDO = false;
  28442. _this.AMBIENT = false;
  28443. _this.AMBIENTINGRAYSCALE = false;
  28444. _this.OPACITY = false;
  28445. _this.OPACITYRGB = false;
  28446. _this.REFLECTION = false;
  28447. _this.EMISSIVE = false;
  28448. _this.REFLECTIVITY = false;
  28449. _this.BUMP = false;
  28450. _this.PARALLAX = false;
  28451. _this.PARALLAXOCCLUSION = false;
  28452. _this.SPECULAROVERALPHA = false;
  28453. _this.CLIPPLANE = false;
  28454. _this.ALPHATEST = false;
  28455. _this.ALPHAFROMALBEDO = false;
  28456. _this.POINTSIZE = false;
  28457. _this.FOG = false;
  28458. _this.SPECULARTERM = false;
  28459. _this.OPACITYFRESNEL = false;
  28460. _this.EMISSIVEFRESNEL = false;
  28461. _this.FRESNEL = false;
  28462. _this.NORMAL = false;
  28463. _this.TANGENT = false;
  28464. _this.UV1 = false;
  28465. _this.UV2 = false;
  28466. _this.VERTEXCOLOR = false;
  28467. _this.VERTEXALPHA = false;
  28468. _this.NUM_BONE_INFLUENCERS = 0;
  28469. _this.BonesPerMesh = 0;
  28470. _this.INSTANCES = false;
  28471. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  28472. _this.MICROSURFACEAUTOMATIC = false;
  28473. _this.EMISSIVEASILLUMINATION = false;
  28474. _this.LINKEMISSIVEWITHALBEDO = false;
  28475. _this.LIGHTMAP = false;
  28476. _this.USELIGHTMAPASSHADOWMAP = false;
  28477. _this.REFLECTIONMAP_3D = false;
  28478. _this.REFLECTIONMAP_SPHERICAL = false;
  28479. _this.REFLECTIONMAP_PLANAR = false;
  28480. _this.REFLECTIONMAP_CUBIC = false;
  28481. _this.REFLECTIONMAP_PROJECTION = false;
  28482. _this.REFLECTIONMAP_SKYBOX = false;
  28483. _this.REFLECTIONMAP_EXPLICIT = false;
  28484. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  28485. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  28486. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  28487. _this.INVERTCUBICMAP = false;
  28488. _this.LOGARITHMICDEPTH = false;
  28489. _this.CAMERATONEMAP = false;
  28490. _this.CAMERACONTRAST = false;
  28491. _this.CAMERACOLORGRADING = false;
  28492. _this.CAMERACOLORCURVES = false;
  28493. _this.OVERLOADEDVALUES = false;
  28494. _this.OVERLOADEDSHADOWVALUES = false;
  28495. _this.USESPHERICALFROMREFLECTIONMAP = false;
  28496. _this.REFRACTION = false;
  28497. _this.REFRACTIONMAP_3D = false;
  28498. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  28499. _this.REFRACTIONMAPINLINEARSPACE = false;
  28500. _this.LODBASEDMICROSFURACE = false;
  28501. _this.USEPHYSICALLIGHTFALLOFF = false;
  28502. _this.RADIANCEOVERALPHA = false;
  28503. _this.USEPMREMREFLECTION = false;
  28504. _this.USEPMREMREFRACTION = false;
  28505. _this.INVERTNORMALMAPX = false;
  28506. _this.INVERTNORMALMAPY = false;
  28507. _this.TWOSIDEDLIGHTING = false;
  28508. _this.SHADOWFULLFLOAT = false;
  28509. _this.METALLICWORKFLOW = false;
  28510. _this.METALLICMAP = false;
  28511. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  28512. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  28513. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  28514. _this.AOSTOREINMETALMAPRED = false;
  28515. _this.MICROSURFACEMAP = false;
  28516. _this.MORPHTARGETS = false;
  28517. _this.MORPHTARGETS_NORMAL = false;
  28518. _this.MORPHTARGETS_TANGENT = false;
  28519. _this.NUM_MORPH_INFLUENCERS = 0;
  28520. _this.rebuild();
  28521. return _this;
  28522. }
  28523. return PBRMaterialDefines;
  28524. }(BABYLON.MaterialDefines));
  28525. /**
  28526. * The Physically based material of BJS.
  28527. *
  28528. * This offers the main features of a standard PBR material.
  28529. * For more information, please refer to the documentation :
  28530. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  28531. */
  28532. var PBRMaterial = (function (_super) {
  28533. __extends(PBRMaterial, _super);
  28534. /**
  28535. * Instantiates a new PBRMaterial instance.
  28536. *
  28537. * @param name The material name
  28538. * @param scene The scene the material will be use in.
  28539. */
  28540. function PBRMaterial(name, scene) {
  28541. var _this = _super.call(this, name, scene) || this;
  28542. /**
  28543. * Intensity of the direct lights e.g. the four lights available in your scene.
  28544. * This impacts both the direct diffuse and specular highlights.
  28545. */
  28546. _this.directIntensity = 1.0;
  28547. /**
  28548. * Intensity of the emissive part of the material.
  28549. * This helps controlling the emissive effect without modifying the emissive color.
  28550. */
  28551. _this.emissiveIntensity = 1.0;
  28552. /**
  28553. * Intensity of the environment e.g. how much the environment will light the object
  28554. * either through harmonics for rough material or through the refelction for shiny ones.
  28555. */
  28556. _this.environmentIntensity = 1.0;
  28557. /**
  28558. * This is a special control allowing the reduction of the specular highlights coming from the
  28559. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  28560. */
  28561. _this.specularIntensity = 1.0;
  28562. _this._lightingInfos = new BABYLON.Vector4(_this.directIntensity, _this.emissiveIntensity, _this.environmentIntensity, _this.specularIntensity);
  28563. /**
  28564. * Debug Control allowing disabling the bump map on this material.
  28565. */
  28566. _this.disableBumpMap = false;
  28567. /**
  28568. * Debug Control helping enforcing or dropping the darkness of shadows.
  28569. * 1.0 means the shadows have their normal darkness, 0.0 means the shadows are not visible.
  28570. */
  28571. _this.overloadedShadowIntensity = 1.0;
  28572. /**
  28573. * Debug Control helping dropping the shading effect coming from the diffuse lighting.
  28574. * 1.0 means the shade have their normal impact, 0.0 means no shading at all.
  28575. */
  28576. _this.overloadedShadeIntensity = 1.0;
  28577. _this._overloadedShadowInfos = new BABYLON.Vector4(_this.overloadedShadowIntensity, _this.overloadedShadeIntensity, 0.0, 0.0);
  28578. /**
  28579. * The camera exposure used on this material.
  28580. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  28581. * This corresponds to a photographic exposure.
  28582. */
  28583. _this.cameraExposure = 1.0;
  28584. /**
  28585. * The camera contrast used on this material.
  28586. * This property is here and not in the camera to allow controlling contrast without full screen post process.
  28587. */
  28588. _this.cameraContrast = 1.0;
  28589. /**
  28590. * Color Grading 2D Lookup Texture.
  28591. * This allows special effects like sepia, black and white to sixties rendering style.
  28592. */
  28593. _this.cameraColorGradingTexture = null;
  28594. /**
  28595. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  28596. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  28597. * 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;
  28598. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  28599. */
  28600. _this.cameraColorCurves = null;
  28601. _this._cameraInfos = new BABYLON.Vector4(1.0, 1.0, 0.0, 0.0);
  28602. _this._microsurfaceTextureLods = new BABYLON.Vector2(0.0, 0.0);
  28603. /**
  28604. * Debug Control allowing to overload the ambient color.
  28605. * This as to be use with the overloadedAmbientIntensity parameter.
  28606. */
  28607. _this.overloadedAmbient = BABYLON.Color3.White();
  28608. /**
  28609. * Debug Control indicating how much the overloaded ambient color is used against the default one.
  28610. */
  28611. _this.overloadedAmbientIntensity = 0.0;
  28612. /**
  28613. * Debug Control allowing to overload the albedo color.
  28614. * This as to be use with the overloadedAlbedoIntensity parameter.
  28615. */
  28616. _this.overloadedAlbedo = BABYLON.Color3.White();
  28617. /**
  28618. * Debug Control indicating how much the overloaded albedo color is used against the default one.
  28619. */
  28620. _this.overloadedAlbedoIntensity = 0.0;
  28621. /**
  28622. * Debug Control allowing to overload the reflectivity color.
  28623. * This as to be use with the overloadedReflectivityIntensity parameter.
  28624. */
  28625. _this.overloadedReflectivity = new BABYLON.Color3(0.0, 0.0, 0.0);
  28626. /**
  28627. * Debug Control indicating how much the overloaded reflectivity color is used against the default one.
  28628. */
  28629. _this.overloadedReflectivityIntensity = 0.0;
  28630. /**
  28631. * Debug Control allowing to overload the emissive color.
  28632. * This as to be use with the overloadedEmissiveIntensity parameter.
  28633. */
  28634. _this.overloadedEmissive = BABYLON.Color3.White();
  28635. /**
  28636. * Debug Control indicating how much the overloaded emissive color is used against the default one.
  28637. */
  28638. _this.overloadedEmissiveIntensity = 0.0;
  28639. _this._overloadedIntensity = new BABYLON.Vector4(_this.overloadedAmbientIntensity, _this.overloadedAlbedoIntensity, _this.overloadedReflectivityIntensity, _this.overloadedEmissiveIntensity);
  28640. /**
  28641. * Debug Control allowing to overload the reflection color.
  28642. * This as to be use with the overloadedReflectionIntensity parameter.
  28643. */
  28644. _this.overloadedReflection = BABYLON.Color3.White();
  28645. /**
  28646. * Debug Control indicating how much the overloaded reflection color is used against the default one.
  28647. */
  28648. _this.overloadedReflectionIntensity = 0.0;
  28649. /**
  28650. * Debug Control allowing to overload the microsurface.
  28651. * This as to be use with the overloadedMicroSurfaceIntensity parameter.
  28652. */
  28653. _this.overloadedMicroSurface = 0.0;
  28654. /**
  28655. * Debug Control indicating how much the overloaded microsurface is used against the default one.
  28656. */
  28657. _this.overloadedMicroSurfaceIntensity = 0.0;
  28658. _this._overloadedMicroSurface = new BABYLON.Vector3(_this.overloadedMicroSurface, _this.overloadedMicroSurfaceIntensity, _this.overloadedReflectionIntensity);
  28659. /**
  28660. * AKA Occlusion Texture Intensity in other nomenclature.
  28661. */
  28662. _this.ambientTextureStrength = 1.0;
  28663. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  28664. /**
  28665. * AKA Diffuse Color in other nomenclature.
  28666. */
  28667. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  28668. /**
  28669. * AKA Specular Color in other nomenclature.
  28670. */
  28671. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  28672. _this.reflectionColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  28673. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  28674. /**
  28675. * AKA Glossiness in other nomenclature.
  28676. */
  28677. _this.microSurface = 0.9;
  28678. /**
  28679. * source material index of refraction (IOR)' / 'destination material IOR.
  28680. */
  28681. _this.indexOfRefraction = 0.66;
  28682. /**
  28683. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  28684. */
  28685. _this.invertRefractionY = false;
  28686. /**
  28687. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  28688. * Materials half opaque for instance using refraction could benefit from this control.
  28689. */
  28690. _this.linkRefractionWithTransparency = false;
  28691. /**
  28692. * The emissive and albedo are linked to never be more than one (Energy conservation).
  28693. */
  28694. _this.linkEmissiveWithAlbedo = false;
  28695. _this.useLightmapAsShadowmap = false;
  28696. /**
  28697. * In this mode, the emissive informtaion will always be added to the lighting once.
  28698. * A light for instance can be thought as emissive.
  28699. */
  28700. _this.useEmissiveAsIllumination = false;
  28701. /**
  28702. * Secifies that the alpha is coming form the albedo channel alpha channel.
  28703. */
  28704. _this.useAlphaFromAlbedoTexture = false;
  28705. /**
  28706. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  28707. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  28708. */
  28709. _this.useSpecularOverAlpha = true;
  28710. /**
  28711. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  28712. */
  28713. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  28714. /**
  28715. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  28716. */
  28717. _this.useRoughnessFromMetallicTextureAlpha = true;
  28718. /**
  28719. * Specifies if the metallic texture contains the roughness information in its green channel.
  28720. */
  28721. _this.useRoughnessFromMetallicTextureGreen = false;
  28722. /**
  28723. * Specifies if the metallic texture contains the metallness information in its blue channel.
  28724. */
  28725. _this.useMetallnessFromMetallicTextureBlue = false;
  28726. /**
  28727. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  28728. */
  28729. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  28730. /**
  28731. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  28732. */
  28733. _this.useAmbientInGrayScale = false;
  28734. /**
  28735. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  28736. * The material will try to infer what glossiness each pixel should be.
  28737. */
  28738. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  28739. /**
  28740. * Allows to work with scalar in linear mode. This is definitely a matter of preferences and tools used during
  28741. * the creation of the material.
  28742. */
  28743. _this.useScalarInLinearSpace = false;
  28744. /**
  28745. * BJS is using an harcoded light falloff based on a manually sets up range.
  28746. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  28747. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  28748. */
  28749. _this.usePhysicalLightFalloff = true;
  28750. /**
  28751. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  28752. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  28753. */
  28754. _this.useRadianceOverAlpha = true;
  28755. /**
  28756. * Allows using the bump map in parallax mode.
  28757. */
  28758. _this.useParallax = false;
  28759. /**
  28760. * Allows using the bump map in parallax occlusion mode.
  28761. */
  28762. _this.useParallaxOcclusion = false;
  28763. /**
  28764. * Controls the scale bias of the parallax mode.
  28765. */
  28766. _this.parallaxScaleBias = 0.05;
  28767. /**
  28768. * If sets to true, disables all the lights affecting the material.
  28769. */
  28770. _this.disableLighting = false;
  28771. /**
  28772. * Number of Simultaneous lights allowed on the material.
  28773. */
  28774. _this.maxSimultaneousLights = 4;
  28775. /**
  28776. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  28777. */
  28778. _this.invertNormalMapX = false;
  28779. /**
  28780. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  28781. */
  28782. _this.invertNormalMapY = false;
  28783. /**
  28784. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  28785. */
  28786. _this.twoSidedLighting = false;
  28787. _this._renderTargets = new BABYLON.SmartArray(16);
  28788. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  28789. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  28790. _this._tempColor = new BABYLON.Color3();
  28791. _this._defines = new PBRMaterialDefines();
  28792. _this._cachedDefines = new PBRMaterialDefines();
  28793. _this._myScene = null;
  28794. _this._myShadowGenerator = null;
  28795. _this._cachedDefines.BonesPerMesh = -1;
  28796. _this.getRenderTargetTextures = function () {
  28797. _this._renderTargets.reset();
  28798. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  28799. _this._renderTargets.push(_this.reflectionTexture);
  28800. }
  28801. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  28802. _this._renderTargets.push(_this.refractionTexture);
  28803. }
  28804. return _this._renderTargets;
  28805. };
  28806. return _this;
  28807. }
  28808. PBRMaterial.prototype.getClassName = function () {
  28809. return "PBRMaterial";
  28810. };
  28811. Object.defineProperty(PBRMaterial.prototype, "useLogarithmicDepth", {
  28812. get: function () {
  28813. return this._useLogarithmicDepth;
  28814. },
  28815. set: function (value) {
  28816. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  28817. },
  28818. enumerable: true,
  28819. configurable: true
  28820. });
  28821. PBRMaterial.prototype.needAlphaBlending = function () {
  28822. if (this.linkRefractionWithTransparency) {
  28823. return false;
  28824. }
  28825. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  28826. };
  28827. PBRMaterial.prototype.needAlphaTesting = function () {
  28828. if (this.linkRefractionWithTransparency) {
  28829. return false;
  28830. }
  28831. return this.albedoTexture != null && this.albedoTexture.hasAlpha;
  28832. };
  28833. PBRMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  28834. return this.albedoTexture != null && this.albedoTexture.hasAlpha && this.useAlphaFromAlbedoTexture;
  28835. };
  28836. PBRMaterial.prototype.getAlphaTestTexture = function () {
  28837. return this.albedoTexture;
  28838. };
  28839. PBRMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  28840. if (!mesh) {
  28841. return true;
  28842. }
  28843. if (this._defines.INSTANCES !== useInstances) {
  28844. return false;
  28845. }
  28846. return false;
  28847. };
  28848. PBRMaterial.prototype.convertColorToLinearSpaceToRef = function (color, ref) {
  28849. PBRMaterial.convertColorToLinearSpaceToRef(color, ref, this.useScalarInLinearSpace);
  28850. };
  28851. PBRMaterial.convertColorToLinearSpaceToRef = function (color, ref, useScalarInLinear) {
  28852. if (!useScalarInLinear) {
  28853. color.toLinearSpaceToRef(ref);
  28854. }
  28855. else {
  28856. ref.r = color.r;
  28857. ref.g = color.g;
  28858. ref.b = color.b;
  28859. }
  28860. };
  28861. PBRMaterial.BindLights = function (scene, mesh, effect, defines, useScalarInLinearSpace, maxSimultaneousLights, usePhysicalLightFalloff) {
  28862. var lightIndex = 0;
  28863. var depthValuesAlreadySet = false;
  28864. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  28865. var light = _a[_i];
  28866. var useUbo = light._uniformBuffer.useUbo;
  28867. light._uniformBuffer.bindToEffect(effect, "Light" + lightIndex);
  28868. BABYLON.MaterialHelper.BindLightProperties(light, effect, lightIndex);
  28869. // GAMMA CORRECTION.
  28870. this.convertColorToLinearSpaceToRef(light.diffuse, PBRMaterial._scaledAlbedo, useScalarInLinearSpace);
  28871. PBRMaterial._scaledAlbedo.scaleToRef(light.intensity, PBRMaterial._scaledAlbedo);
  28872. light._uniformBuffer.updateColor4(useUbo ? "vLightDiffuse" : "vLightDiffuse" + lightIndex, PBRMaterial._scaledAlbedo, usePhysicalLightFalloff ? light.radius : light.range);
  28873. if (defines["SPECULARTERM"]) {
  28874. this.convertColorToLinearSpaceToRef(light.specular, PBRMaterial._scaledReflectivity, useScalarInLinearSpace);
  28875. PBRMaterial._scaledReflectivity.scaleToRef(light.intensity, PBRMaterial._scaledReflectivity);
  28876. light._uniformBuffer.updateColor3(useUbo ? "vLightSpecular" : "vLightSpecular" + lightIndex, PBRMaterial._scaledReflectivity);
  28877. }
  28878. // Shadows
  28879. if (scene.shadowsEnabled) {
  28880. depthValuesAlreadySet = BABYLON.MaterialHelper.BindLightShadow(light, scene, mesh, lightIndex + "", effect, depthValuesAlreadySet);
  28881. }
  28882. light._uniformBuffer.update();
  28883. lightIndex++;
  28884. if (lightIndex === maxSimultaneousLights)
  28885. break;
  28886. }
  28887. };
  28888. PBRMaterial.prototype.isReady = function (mesh, useInstances) {
  28889. if (this.isFrozen) {
  28890. if (this._wasPreviouslyReady) {
  28891. return true;
  28892. }
  28893. }
  28894. var scene = this.getScene();
  28895. var engine = scene.getEngine();
  28896. var needUVs = false;
  28897. this._defines.reset();
  28898. if (scene.lightsEnabled && !this.disableLighting) {
  28899. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, true, this.maxSimultaneousLights);
  28900. }
  28901. if (!this.checkReadyOnEveryCall) {
  28902. if (this._renderId === scene.getRenderId()) {
  28903. if (this._checkCache(scene, mesh, useInstances)) {
  28904. return true;
  28905. }
  28906. }
  28907. }
  28908. if (scene.texturesEnabled) {
  28909. if (scene.getEngine().getCaps().textureLOD) {
  28910. this._defines.LODBASEDMICROSFURACE = true;
  28911. }
  28912. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  28913. if (!this.albedoTexture.isReady()) {
  28914. return false;
  28915. }
  28916. needUVs = true;
  28917. this._defines.ALBEDO = true;
  28918. }
  28919. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  28920. if (!this.ambientTexture.isReady()) {
  28921. return false;
  28922. }
  28923. needUVs = true;
  28924. this._defines.AMBIENT = true;
  28925. this._defines.AMBIENTINGRAYSCALE = this.useAmbientInGrayScale;
  28926. }
  28927. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  28928. if (!this.opacityTexture.isReady()) {
  28929. return false;
  28930. }
  28931. needUVs = true;
  28932. this._defines.OPACITY = true;
  28933. if (this.opacityTexture.getAlphaFromRGB) {
  28934. this._defines.OPACITYRGB = true;
  28935. }
  28936. }
  28937. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  28938. if (!this.reflectionTexture.isReady()) {
  28939. return false;
  28940. }
  28941. this._defines.REFLECTION = true;
  28942. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  28943. this._defines.INVERTCUBICMAP = true;
  28944. }
  28945. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  28946. switch (this.reflectionTexture.coordinatesMode) {
  28947. case BABYLON.Texture.CUBIC_MODE:
  28948. case BABYLON.Texture.INVCUBIC_MODE:
  28949. this._defines.REFLECTIONMAP_CUBIC = true;
  28950. break;
  28951. case BABYLON.Texture.EXPLICIT_MODE:
  28952. this._defines.REFLECTIONMAP_EXPLICIT = true;
  28953. break;
  28954. case BABYLON.Texture.PLANAR_MODE:
  28955. this._defines.REFLECTIONMAP_PLANAR = true;
  28956. break;
  28957. case BABYLON.Texture.PROJECTION_MODE:
  28958. this._defines.REFLECTIONMAP_PROJECTION = true;
  28959. break;
  28960. case BABYLON.Texture.SKYBOX_MODE:
  28961. this._defines.REFLECTIONMAP_SKYBOX = true;
  28962. break;
  28963. case BABYLON.Texture.SPHERICAL_MODE:
  28964. this._defines.REFLECTIONMAP_SPHERICAL = true;
  28965. break;
  28966. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  28967. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  28968. break;
  28969. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  28970. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  28971. break;
  28972. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  28973. this._defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  28974. break;
  28975. }
  28976. if (this.reflectionTexture instanceof BABYLON.HDRCubeTexture && this.reflectionTexture) {
  28977. this._defines.USESPHERICALFROMREFLECTIONMAP = true;
  28978. if (this.reflectionTexture.isPMREM) {
  28979. this._defines.USEPMREMREFLECTION = true;
  28980. }
  28981. }
  28982. }
  28983. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  28984. if (!this.lightmapTexture.isReady()) {
  28985. return false;
  28986. }
  28987. needUVs = true;
  28988. this._defines.LIGHTMAP = true;
  28989. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  28990. }
  28991. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  28992. if (!this.emissiveTexture.isReady()) {
  28993. return false;
  28994. }
  28995. needUVs = true;
  28996. this._defines.EMISSIVE = true;
  28997. }
  28998. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  28999. if (this.metallicTexture) {
  29000. if (!this.metallicTexture.isReady()) {
  29001. return false;
  29002. }
  29003. needUVs = true;
  29004. this._defines.METALLICWORKFLOW = true;
  29005. this._defines.METALLICMAP = true;
  29006. this._defines.ROUGHNESSSTOREINMETALMAPALPHA = this.useRoughnessFromMetallicTextureAlpha;
  29007. this._defines.ROUGHNESSSTOREINMETALMAPGREEN = !this.useRoughnessFromMetallicTextureAlpha && this.useRoughnessFromMetallicTextureGreen;
  29008. this._defines.METALLNESSSTOREINMETALMAPBLUE = this.useMetallnessFromMetallicTextureBlue;
  29009. this._defines.AOSTOREINMETALMAPRED = this.useAmbientOcclusionFromMetallicTextureRed;
  29010. }
  29011. else if (this.reflectivityTexture) {
  29012. if (!this.reflectivityTexture.isReady()) {
  29013. return false;
  29014. }
  29015. needUVs = true;
  29016. this._defines.REFLECTIVITY = true;
  29017. this._defines.MICROSURFACEFROMREFLECTIVITYMAP = this.useMicroSurfaceFromReflectivityMapAlpha;
  29018. this._defines.MICROSURFACEAUTOMATIC = this.useAutoMicroSurfaceFromReflectivityMap;
  29019. }
  29020. if (this.microSurfaceTexture) {
  29021. if (!this.microSurfaceTexture.isReady()) {
  29022. return false;
  29023. }
  29024. needUVs = true;
  29025. this._defines.MICROSURFACEMAP = true;
  29026. }
  29027. }
  29028. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  29029. if (!this.bumpTexture.isReady()) {
  29030. return false;
  29031. }
  29032. needUVs = true;
  29033. this._defines.BUMP = true;
  29034. if (this.useParallax && this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  29035. this._defines.PARALLAX = true;
  29036. if (this.useParallaxOcclusion) {
  29037. this._defines.PARALLAXOCCLUSION = true;
  29038. }
  29039. }
  29040. if (this.invertNormalMapX) {
  29041. this._defines.INVERTNORMALMAPX = true;
  29042. }
  29043. if (this.invertNormalMapY) {
  29044. this._defines.INVERTNORMALMAPY = true;
  29045. }
  29046. if (scene._mirroredCameraPosition) {
  29047. this._defines.INVERTNORMALMAPX = !this._defines.INVERTNORMALMAPX;
  29048. this._defines.INVERTNORMALMAPY = !this._defines.INVERTNORMALMAPY;
  29049. }
  29050. }
  29051. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  29052. if (!this.refractionTexture.isReady()) {
  29053. return false;
  29054. }
  29055. needUVs = true;
  29056. this._defines.REFRACTION = true;
  29057. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  29058. if (this.linkRefractionWithTransparency) {
  29059. this._defines.LINKREFRACTIONTOTRANSPARENCY = true;
  29060. }
  29061. if (this.refractionTexture instanceof BABYLON.HDRCubeTexture) {
  29062. this._defines.REFRACTIONMAPINLINEARSPACE = true;
  29063. if (this.refractionTexture.isPMREM) {
  29064. this._defines.USEPMREMREFRACTION = true;
  29065. }
  29066. }
  29067. }
  29068. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  29069. if (!this.cameraColorGradingTexture.isReady()) {
  29070. return false;
  29071. }
  29072. this._defines.CAMERACOLORGRADING = true;
  29073. }
  29074. if (!this.backFaceCulling && this.twoSidedLighting) {
  29075. this._defines.TWOSIDEDLIGHTING = true;
  29076. }
  29077. }
  29078. // Effect
  29079. if (scene.clipPlane) {
  29080. this._defines.CLIPPLANE = true;
  29081. }
  29082. if (engine.getAlphaTesting()) {
  29083. this._defines.ALPHATEST = true;
  29084. }
  29085. if (this._shouldUseAlphaFromAlbedoTexture()) {
  29086. this._defines.ALPHAFROMALBEDO = true;
  29087. }
  29088. if (this.useEmissiveAsIllumination) {
  29089. this._defines.EMISSIVEASILLUMINATION = true;
  29090. }
  29091. if (this.linkEmissiveWithAlbedo) {
  29092. this._defines.LINKEMISSIVEWITHALBEDO = true;
  29093. }
  29094. if (this.useLogarithmicDepth) {
  29095. this._defines.LOGARITHMICDEPTH = true;
  29096. }
  29097. if (this.cameraContrast != 1) {
  29098. this._defines.CAMERACONTRAST = true;
  29099. }
  29100. if (this.cameraExposure != 1) {
  29101. this._defines.CAMERATONEMAP = true;
  29102. }
  29103. if (this.cameraColorCurves) {
  29104. this._defines.CAMERACOLORCURVES = true;
  29105. }
  29106. if (this.overloadedShadeIntensity != 1 ||
  29107. this.overloadedShadowIntensity != 1) {
  29108. this._defines.OVERLOADEDSHADOWVALUES = true;
  29109. }
  29110. if (this.overloadedMicroSurfaceIntensity > 0 ||
  29111. this.overloadedEmissiveIntensity > 0 ||
  29112. this.overloadedReflectivityIntensity > 0 ||
  29113. this.overloadedAlbedoIntensity > 0 ||
  29114. this.overloadedAmbientIntensity > 0 ||
  29115. this.overloadedReflectionIntensity > 0) {
  29116. this._defines.OVERLOADEDVALUES = true;
  29117. }
  29118. // Point size
  29119. if (this.pointsCloud || scene.forcePointsCloud) {
  29120. this._defines.POINTSIZE = true;
  29121. }
  29122. // Fog
  29123. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  29124. this._defines.FOG = true;
  29125. }
  29126. if (BABYLON.StandardMaterial.FresnelEnabled) {
  29127. // Fresnel
  29128. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  29129. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  29130. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  29131. this._defines.OPACITYFRESNEL = true;
  29132. }
  29133. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  29134. this._defines.EMISSIVEFRESNEL = true;
  29135. }
  29136. this._defines.FRESNEL = true;
  29137. }
  29138. }
  29139. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  29140. this._defines.SPECULAROVERALPHA = true;
  29141. }
  29142. if (this.usePhysicalLightFalloff) {
  29143. this._defines.USEPHYSICALLIGHTFALLOFF = true;
  29144. }
  29145. if (this.useRadianceOverAlpha) {
  29146. this._defines.RADIANCEOVERALPHA = true;
  29147. }
  29148. if ((this.metallic !== undefined && this.metallic !== null) || (this.roughness !== undefined && this.roughness !== null)) {
  29149. this._defines.METALLICWORKFLOW = true;
  29150. }
  29151. // Attribs
  29152. if (mesh) {
  29153. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29154. mesh.createNormals(true);
  29155. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  29156. }
  29157. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29158. this._defines.NORMAL = true;
  29159. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  29160. this._defines.TANGENT = true;
  29161. }
  29162. }
  29163. if (needUVs) {
  29164. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29165. this._defines.UV1 = true;
  29166. }
  29167. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29168. this._defines.UV2 = true;
  29169. }
  29170. }
  29171. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  29172. this._defines.VERTEXCOLOR = true;
  29173. if (mesh.hasVertexAlpha) {
  29174. this._defines.VERTEXALPHA = true;
  29175. }
  29176. }
  29177. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  29178. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  29179. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  29180. }
  29181. // Instances
  29182. if (useInstances) {
  29183. this._defines.INSTANCES = true;
  29184. }
  29185. if (mesh.morphTargetManager) {
  29186. var manager = mesh.morphTargetManager;
  29187. this._defines.MORPHTARGETS_TANGENT = manager.supportsTangents && this._defines.TANGENT;
  29188. this._defines.MORPHTARGETS_NORMAL = manager.supportsNormals && this._defines.NORMAL;
  29189. this._defines.MORPHTARGETS = (manager.numInfluencers > 0);
  29190. this._defines.NUM_MORPH_INFLUENCERS = manager.numInfluencers;
  29191. }
  29192. }
  29193. // Get correct effect
  29194. if (!this._defines.isEqual(this._cachedDefines)) {
  29195. this._defines.cloneTo(this._cachedDefines);
  29196. scene.resetCachedMaterial();
  29197. // Fallbacks
  29198. var fallbacks = new BABYLON.EffectFallbacks();
  29199. if (this._defines.REFLECTION) {
  29200. fallbacks.addFallback(0, "REFLECTION");
  29201. }
  29202. if (this._defines.REFRACTION) {
  29203. fallbacks.addFallback(0, "REFRACTION");
  29204. }
  29205. if (this._defines.REFLECTIVITY) {
  29206. fallbacks.addFallback(0, "REFLECTIVITY");
  29207. }
  29208. if (this._defines.BUMP) {
  29209. fallbacks.addFallback(0, "BUMP");
  29210. }
  29211. if (this._defines.PARALLAX) {
  29212. fallbacks.addFallback(1, "PARALLAX");
  29213. }
  29214. if (this._defines.PARALLAXOCCLUSION) {
  29215. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  29216. }
  29217. if (this._defines.SPECULAROVERALPHA) {
  29218. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  29219. }
  29220. if (this._defines.FOG) {
  29221. fallbacks.addFallback(1, "FOG");
  29222. }
  29223. if (this._defines.POINTSIZE) {
  29224. fallbacks.addFallback(0, "POINTSIZE");
  29225. }
  29226. if (this._defines.LOGARITHMICDEPTH) {
  29227. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  29228. }
  29229. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  29230. if (this._defines.SPECULARTERM) {
  29231. fallbacks.addFallback(0, "SPECULARTERM");
  29232. }
  29233. if (this._defines.OPACITYFRESNEL) {
  29234. fallbacks.addFallback(1, "OPACITYFRESNEL");
  29235. }
  29236. if (this._defines.EMISSIVEFRESNEL) {
  29237. fallbacks.addFallback(2, "EMISSIVEFRESNEL");
  29238. }
  29239. if (this._defines.FRESNEL) {
  29240. fallbacks.addFallback(3, "FRESNEL");
  29241. }
  29242. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  29243. fallbacks.addCPUSkinningFallback(0, mesh);
  29244. }
  29245. //Attributes
  29246. var attribs = [BABYLON.VertexBuffer.PositionKind];
  29247. if (this._defines.NORMAL) {
  29248. attribs.push(BABYLON.VertexBuffer.NormalKind);
  29249. }
  29250. if (this._defines.TANGENT) {
  29251. attribs.push(BABYLON.VertexBuffer.TangentKind);
  29252. }
  29253. if (this._defines.UV1) {
  29254. attribs.push(BABYLON.VertexBuffer.UVKind);
  29255. }
  29256. if (this._defines.UV2) {
  29257. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  29258. }
  29259. if (this._defines.VERTEXCOLOR) {
  29260. attribs.push(BABYLON.VertexBuffer.ColorKind);
  29261. }
  29262. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  29263. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  29264. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, this._defines);
  29265. // Legacy browser patch
  29266. var join = this._defines.toString();
  29267. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  29268. "vFogInfos", "vFogColor", "pointSize",
  29269. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  29270. "mBones",
  29271. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  29272. "depthValues",
  29273. "opacityParts", "emissiveLeftColor", "emissiveRightColor",
  29274. "vLightingIntensity", "vOverloadedShadowIntensity", "vOverloadedIntensity", "vOverloadedAlbedo", "vOverloadedReflection", "vOverloadedReflectivity", "vOverloadedEmissive", "vOverloadedMicroSurface",
  29275. "logarithmicDepthConstant",
  29276. "vSphericalX", "vSphericalY", "vSphericalZ",
  29277. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  29278. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  29279. "vMicrosurfaceTextureLods",
  29280. "vCameraInfos"
  29281. ];
  29282. var samplers = ["albedoSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "reflectivitySampler", "microSurfaceSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  29283. var uniformBuffers = ["Material", "Scene"];
  29284. if (this._defines.CAMERACOLORCURVES) {
  29285. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  29286. }
  29287. if (this._defines.CAMERACOLORGRADING) {
  29288. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  29289. }
  29290. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  29291. uniformsNames: uniforms,
  29292. uniformBuffersNames: uniformBuffers,
  29293. samplers: samplers,
  29294. defines: this._defines,
  29295. maxSimultaneousLights: this.maxSimultaneousLights
  29296. });
  29297. var onCompiled = function (effect) {
  29298. if (this.onCompiled) {
  29299. this.onCompiled(effect);
  29300. }
  29301. this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  29302. }.bind(this);
  29303. this._effect = scene.getEngine().createEffect("pbr", {
  29304. attributes: attribs,
  29305. uniformsNames: uniforms,
  29306. uniformBuffersNames: uniformBuffers,
  29307. samplers: samplers,
  29308. defines: join,
  29309. fallbacks: fallbacks,
  29310. onCompiled: onCompiled,
  29311. onError: this.onError,
  29312. indexParameters: { maxSimultaneousLights: this.maxSimultaneousLights, maxSimultaneousMorphTargets: this._defines.NUM_MORPH_INFLUENCERS }
  29313. }, engine);
  29314. this.buildUniformLayout();
  29315. }
  29316. if (!this._effect.isReady()) {
  29317. return false;
  29318. }
  29319. this._renderId = scene.getRenderId();
  29320. this._wasPreviouslyReady = true;
  29321. return true;
  29322. };
  29323. PBRMaterial.prototype.buildUniformLayout = function () {
  29324. // Order is important !
  29325. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  29326. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  29327. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  29328. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  29329. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  29330. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  29331. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  29332. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  29333. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  29334. this._uniformBuffer.addUniform("vBumpInfos", 3);
  29335. this._uniformBuffer.addUniform("albedoMatrix", 16);
  29336. this._uniformBuffer.addUniform("ambientMatrix", 16);
  29337. this._uniformBuffer.addUniform("opacityMatrix", 16);
  29338. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  29339. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  29340. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  29341. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  29342. this._uniformBuffer.addUniform("bumpMatrix", 16);
  29343. this._uniformBuffer.addUniform("refractionMatrix", 16);
  29344. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  29345. this._uniformBuffer.addUniform("vReflectionColor", 3);
  29346. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  29347. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  29348. this._uniformBuffer.addUniform("vMicrosurfaceTextureLods", 2);
  29349. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  29350. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  29351. this._uniformBuffer.addUniform("opacityParts", 4);
  29352. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  29353. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  29354. this._uniformBuffer.addUniform("vOverloadedIntensity", 4);
  29355. this._uniformBuffer.addUniform("vOverloadedAmbient", 3);
  29356. this._uniformBuffer.addUniform("vOverloadedAlbedo", 3);
  29357. this._uniformBuffer.addUniform("vOverloadedReflectivity", 3);
  29358. this._uniformBuffer.addUniform("vOverloadedEmissive", 3);
  29359. this._uniformBuffer.addUniform("vOverloadedReflection", 3);
  29360. this._uniformBuffer.addUniform("vOverloadedMicroSurface", 3);
  29361. this._uniformBuffer.addUniform("vOverloadedShadowIntensity", 4);
  29362. this._uniformBuffer.addUniform("pointSize", 1);
  29363. this._uniformBuffer.create();
  29364. };
  29365. PBRMaterial.prototype.unbind = function () {
  29366. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  29367. this._uniformBuffer.setTexture("reflection2DSampler", null);
  29368. }
  29369. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  29370. this._uniformBuffer.setTexture("refraction2DSampler", null);
  29371. }
  29372. _super.prototype.unbind.call(this);
  29373. };
  29374. PBRMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  29375. this._effect.setMatrix("world", world);
  29376. };
  29377. PBRMaterial.prototype.bind = function (world, mesh) {
  29378. this._myScene = this.getScene();
  29379. var effect = this._effect;
  29380. // Matrices
  29381. this.bindOnlyWorldMatrix(world);
  29382. // Bones
  29383. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  29384. if (this._myScene.getCachedMaterial() !== this) {
  29385. this._uniformBuffer.bindToEffect(effect, "Material");
  29386. this.bindViewProjection(effect);
  29387. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  29388. // Fresnel
  29389. if (BABYLON.StandardMaterial.FresnelEnabled) {
  29390. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  29391. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  29392. }
  29393. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  29394. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  29395. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  29396. }
  29397. }
  29398. // Texture uniforms
  29399. if (this._myScene.texturesEnabled) {
  29400. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  29401. this._uniformBuffer.updateFloat2("vAlbedoInfos", this.albedoTexture.coordinatesIndex, this.albedoTexture.level);
  29402. this._uniformBuffer.updateMatrix("albedoMatrix", this.albedoTexture.getTextureMatrix());
  29403. }
  29404. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  29405. this._uniformBuffer.updateFloat3("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level, this.ambientTextureStrength);
  29406. this._uniformBuffer.updateMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  29407. }
  29408. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  29409. this._uniformBuffer.updateFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  29410. this._uniformBuffer.updateMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  29411. }
  29412. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  29413. this._microsurfaceTextureLods.x = Math.round(Math.log(this.reflectionTexture.getSize().width) * Math.LOG2E);
  29414. this._uniformBuffer.updateMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  29415. this._uniformBuffer.updateFloat2("vReflectionInfos", this.reflectionTexture.level, 0);
  29416. if (this._defines.USESPHERICALFROMREFLECTIONMAP) {
  29417. this._effect.setFloat3("vSphericalX", this.reflectionTexture.sphericalPolynomial.x.x, this.reflectionTexture.sphericalPolynomial.x.y, this.reflectionTexture.sphericalPolynomial.x.z);
  29418. this._effect.setFloat3("vSphericalY", this.reflectionTexture.sphericalPolynomial.y.x, this.reflectionTexture.sphericalPolynomial.y.y, this.reflectionTexture.sphericalPolynomial.y.z);
  29419. this._effect.setFloat3("vSphericalZ", this.reflectionTexture.sphericalPolynomial.z.x, this.reflectionTexture.sphericalPolynomial.z.y, this.reflectionTexture.sphericalPolynomial.z.z);
  29420. this._effect.setFloat3("vSphericalXX", this.reflectionTexture.sphericalPolynomial.xx.x, this.reflectionTexture.sphericalPolynomial.xx.y, this.reflectionTexture.sphericalPolynomial.xx.z);
  29421. this._effect.setFloat3("vSphericalYY", this.reflectionTexture.sphericalPolynomial.yy.x, this.reflectionTexture.sphericalPolynomial.yy.y, this.reflectionTexture.sphericalPolynomial.yy.z);
  29422. this._effect.setFloat3("vSphericalZZ", this.reflectionTexture.sphericalPolynomial.zz.x, this.reflectionTexture.sphericalPolynomial.zz.y, this.reflectionTexture.sphericalPolynomial.zz.z);
  29423. this._effect.setFloat3("vSphericalXY", this.reflectionTexture.sphericalPolynomial.xy.x, this.reflectionTexture.sphericalPolynomial.xy.y, this.reflectionTexture.sphericalPolynomial.xy.z);
  29424. this._effect.setFloat3("vSphericalYZ", this.reflectionTexture.sphericalPolynomial.yz.x, this.reflectionTexture.sphericalPolynomial.yz.y, this.reflectionTexture.sphericalPolynomial.yz.z);
  29425. this._effect.setFloat3("vSphericalZX", this.reflectionTexture.sphericalPolynomial.zx.x, this.reflectionTexture.sphericalPolynomial.zx.y, this.reflectionTexture.sphericalPolynomial.zx.z);
  29426. }
  29427. }
  29428. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  29429. this._uniformBuffer.updateFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  29430. this._uniformBuffer.updateMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  29431. }
  29432. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  29433. this._uniformBuffer.updateFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  29434. this._uniformBuffer.updateMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  29435. }
  29436. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  29437. if (this.metallicTexture) {
  29438. this._uniformBuffer.updateFloat3("vReflectivityInfos", this.metallicTexture.coordinatesIndex, this.metallicTexture.level, this.ambientTextureStrength);
  29439. this._uniformBuffer.updateMatrix("reflectivityMatrix", this.metallicTexture.getTextureMatrix());
  29440. }
  29441. else if (this.reflectivityTexture) {
  29442. this._uniformBuffer.updateFloat3("vReflectivityInfos", this.reflectivityTexture.coordinatesIndex, this.reflectivityTexture.level, 1.0);
  29443. this._uniformBuffer.updateMatrix("reflectivityMatrix", this.reflectivityTexture.getTextureMatrix());
  29444. }
  29445. if (this.microSurfaceTexture) {
  29446. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this.microSurfaceTexture.coordinatesIndex, this.microSurfaceTexture.level);
  29447. this._uniformBuffer.updateMatrix("microSurfaceSamplerMatrix", this.microSurfaceTexture.getTextureMatrix());
  29448. }
  29449. }
  29450. if (this.bumpTexture && this._myScene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  29451. this._uniformBuffer.updateFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  29452. this._uniformBuffer.updateMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  29453. }
  29454. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  29455. this._microsurfaceTextureLods.y = Math.round(Math.log(this.refractionTexture.getSize().width) * Math.LOG2E);
  29456. var depth = 1.0;
  29457. if (!this.refractionTexture.isCube) {
  29458. this._uniformBuffer.updateMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  29459. if (this.refractionTexture.depth) {
  29460. depth = this.refractionTexture.depth;
  29461. }
  29462. }
  29463. this._uniformBuffer.updateFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  29464. }
  29465. if ((this.reflectionTexture || this.refractionTexture)) {
  29466. this._uniformBuffer.updateFloat2("vMicrosurfaceTextureLods", this._microsurfaceTextureLods.x, this._microsurfaceTextureLods.y);
  29467. }
  29468. }
  29469. // Point size
  29470. if (this.pointsCloud) {
  29471. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  29472. }
  29473. // Colors
  29474. if (this._defines.METALLICWORKFLOW) {
  29475. PBRMaterial._scaledReflectivity.r = (this.metallic === undefined || this.metallic === null) ? 1 : this.metallic;
  29476. PBRMaterial._scaledReflectivity.g = (this.roughness === undefined || this.roughness === null) ? 1 : this.roughness;
  29477. this._uniformBuffer.updateColor4("vReflectivityColor", PBRMaterial._scaledReflectivity, 0);
  29478. }
  29479. else {
  29480. // GAMMA CORRECTION.
  29481. this.convertColorToLinearSpaceToRef(this.reflectivityColor, PBRMaterial._scaledReflectivity);
  29482. this._uniformBuffer.updateColor4("vReflectivityColor", PBRMaterial._scaledReflectivity, this.microSurface);
  29483. }
  29484. // GAMMA CORRECTION.
  29485. this.convertColorToLinearSpaceToRef(this.emissiveColor, PBRMaterial._scaledEmissive);
  29486. this._uniformBuffer.updateColor3("vEmissiveColor", PBRMaterial._scaledEmissive);
  29487. // GAMMA CORRECTION.
  29488. this.convertColorToLinearSpaceToRef(this.reflectionColor, PBRMaterial._scaledReflection);
  29489. this._uniformBuffer.updateColor3("vReflectionColor", PBRMaterial._scaledReflection);
  29490. // GAMMA CORRECTION.
  29491. this.convertColorToLinearSpaceToRef(this.albedoColor, PBRMaterial._scaledAlbedo);
  29492. this._uniformBuffer.updateColor4("vAlbedoColor", PBRMaterial._scaledAlbedo, this.alpha * mesh.visibility);
  29493. // Misc
  29494. this._lightingInfos.x = this.directIntensity;
  29495. this._lightingInfos.y = this.emissiveIntensity;
  29496. this._lightingInfos.z = this.environmentIntensity;
  29497. this._lightingInfos.w = this.specularIntensity;
  29498. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  29499. // Overloaded params
  29500. this._overloadedShadowInfos.x = this.overloadedShadowIntensity;
  29501. this._overloadedShadowInfos.y = this.overloadedShadeIntensity;
  29502. this._uniformBuffer.updateVector4("vOverloadedShadowIntensity", this._overloadedShadowInfos);
  29503. this._overloadedIntensity.x = this.overloadedAmbientIntensity;
  29504. this._overloadedIntensity.y = this.overloadedAlbedoIntensity;
  29505. this._overloadedIntensity.z = this.overloadedReflectivityIntensity;
  29506. this._overloadedIntensity.w = this.overloadedEmissiveIntensity;
  29507. this._uniformBuffer.updateVector4("vOverloadedIntensity", this._overloadedIntensity);
  29508. this._uniformBuffer.updateColor3("vOverloadedAmbient", this.overloadedAmbient);
  29509. this.convertColorToLinearSpaceToRef(this.overloadedAlbedo, this._tempColor);
  29510. this._uniformBuffer.updateColor3("vOverloadedAlbedo", this._tempColor);
  29511. this.convertColorToLinearSpaceToRef(this.overloadedReflectivity, this._tempColor);
  29512. this._uniformBuffer.updateColor3("vOverloadedReflectivity", this._tempColor);
  29513. this.convertColorToLinearSpaceToRef(this.overloadedEmissive, this._tempColor);
  29514. this._uniformBuffer.updateColor3("vOverloadedEmissive", this._tempColor);
  29515. this.convertColorToLinearSpaceToRef(this.overloadedReflection, this._tempColor);
  29516. this._uniformBuffer.updateColor3("vOverloadedReflection", this._tempColor);
  29517. this._overloadedMicroSurface.x = this.overloadedMicroSurface;
  29518. this._overloadedMicroSurface.y = this.overloadedMicroSurfaceIntensity;
  29519. this._overloadedMicroSurface.z = this.overloadedReflectionIntensity;
  29520. this._uniformBuffer.updateVector3("vOverloadedMicroSurface", this._overloadedMicroSurface);
  29521. }
  29522. // Textures
  29523. if (this._myScene.texturesEnabled) {
  29524. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  29525. this._uniformBuffer.setTexture("albedoSampler", this.albedoTexture);
  29526. }
  29527. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  29528. this._uniformBuffer.setTexture("ambientSampler", this.ambientTexture);
  29529. }
  29530. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  29531. this._uniformBuffer.setTexture("opacitySampler", this.opacityTexture);
  29532. }
  29533. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  29534. if (this.reflectionTexture.isCube) {
  29535. this._uniformBuffer.setTexture("reflectionCubeSampler", this.reflectionTexture);
  29536. }
  29537. else {
  29538. this._uniformBuffer.setTexture("reflection2DSampler", this.reflectionTexture);
  29539. }
  29540. }
  29541. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  29542. this._uniformBuffer.setTexture("emissiveSampler", this.emissiveTexture);
  29543. }
  29544. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  29545. this._uniformBuffer.setTexture("lightmapSampler", this.lightmapTexture);
  29546. }
  29547. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  29548. if (this.metallicTexture) {
  29549. this._uniformBuffer.setTexture("reflectivitySampler", this.metallicTexture);
  29550. }
  29551. else if (this.reflectivityTexture) {
  29552. this._uniformBuffer.setTexture("reflectivitySampler", this.reflectivityTexture);
  29553. }
  29554. if (this.microSurfaceTexture) {
  29555. this._uniformBuffer.setTexture("microSurfaceSampler", this.microSurfaceTexture);
  29556. }
  29557. }
  29558. if (this.bumpTexture && this._myScene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  29559. this._uniformBuffer.setTexture("bumpSampler", this.bumpTexture);
  29560. }
  29561. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  29562. if (this.refractionTexture.isCube) {
  29563. this._uniformBuffer.setTexture("refractionCubeSampler", this.refractionTexture);
  29564. }
  29565. else {
  29566. this._uniformBuffer.setTexture("refraction2DSampler", this.refractionTexture);
  29567. }
  29568. }
  29569. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  29570. BABYLON.ColorGradingTexture.Bind(this.cameraColorGradingTexture, this._effect);
  29571. }
  29572. }
  29573. // Clip plane
  29574. BABYLON.MaterialHelper.BindClipPlane(this._effect, this._myScene);
  29575. // Colors
  29576. this._myScene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  29577. effect.setVector3("vEyePosition", this._myScene._mirroredCameraPosition ? this._myScene._mirroredCameraPosition : this._myScene.activeCamera.position);
  29578. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  29579. }
  29580. if (this._myScene.getCachedMaterial() !== this || !this.isFrozen) {
  29581. // Lights
  29582. if (this._myScene.lightsEnabled && !this.disableLighting) {
  29583. PBRMaterial.BindLights(this._myScene, mesh, this._effect, this._defines, this.useScalarInLinearSpace, this.maxSimultaneousLights, this.usePhysicalLightFalloff);
  29584. }
  29585. // View
  29586. if (this._myScene.fogEnabled && mesh.applyFog && this._myScene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  29587. this.bindView(effect);
  29588. }
  29589. // Fog
  29590. BABYLON.MaterialHelper.BindFogParameters(this._myScene, mesh, this._effect);
  29591. // Morph targets
  29592. if (this._defines.NUM_MORPH_INFLUENCERS) {
  29593. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  29594. }
  29595. this._cameraInfos.x = this.cameraExposure;
  29596. this._cameraInfos.y = this.cameraContrast;
  29597. effect.setVector4("vCameraInfos", this._cameraInfos);
  29598. if (this.cameraColorCurves) {
  29599. BABYLON.ColorCurves.Bind(this.cameraColorCurves, this._effect);
  29600. }
  29601. // Log. depth
  29602. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, this._myScene);
  29603. }
  29604. this._uniformBuffer.update();
  29605. this._afterBind(mesh);
  29606. this._myScene = null;
  29607. };
  29608. PBRMaterial.prototype.getAnimatables = function () {
  29609. var results = [];
  29610. if (this.albedoTexture && this.albedoTexture.animations && this.albedoTexture.animations.length > 0) {
  29611. results.push(this.albedoTexture);
  29612. }
  29613. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  29614. results.push(this.ambientTexture);
  29615. }
  29616. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  29617. results.push(this.opacityTexture);
  29618. }
  29619. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  29620. results.push(this.reflectionTexture);
  29621. }
  29622. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  29623. results.push(this.emissiveTexture);
  29624. }
  29625. if (this.metallicTexture && this.metallicTexture.animations && this.metallicTexture.animations.length > 0) {
  29626. results.push(this.metallicTexture);
  29627. }
  29628. else if (this.reflectivityTexture && this.reflectivityTexture.animations && this.reflectivityTexture.animations.length > 0) {
  29629. results.push(this.reflectivityTexture);
  29630. }
  29631. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  29632. results.push(this.bumpTexture);
  29633. }
  29634. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  29635. results.push(this.lightmapTexture);
  29636. }
  29637. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  29638. results.push(this.refractionTexture);
  29639. }
  29640. if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
  29641. results.push(this.cameraColorGradingTexture);
  29642. }
  29643. return results;
  29644. };
  29645. PBRMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  29646. if (forceDisposeTextures) {
  29647. if (this.albedoTexture) {
  29648. this.albedoTexture.dispose();
  29649. }
  29650. if (this.ambientTexture) {
  29651. this.ambientTexture.dispose();
  29652. }
  29653. if (this.opacityTexture) {
  29654. this.opacityTexture.dispose();
  29655. }
  29656. if (this.reflectionTexture) {
  29657. this.reflectionTexture.dispose();
  29658. }
  29659. if (this.emissiveTexture) {
  29660. this.emissiveTexture.dispose();
  29661. }
  29662. if (this.metallicTexture) {
  29663. this.metallicTexture.dispose();
  29664. }
  29665. if (this.reflectivityTexture) {
  29666. this.reflectivityTexture.dispose();
  29667. }
  29668. if (this.bumpTexture) {
  29669. this.bumpTexture.dispose();
  29670. }
  29671. if (this.lightmapTexture) {
  29672. this.lightmapTexture.dispose();
  29673. }
  29674. if (this.refractionTexture) {
  29675. this.refractionTexture.dispose();
  29676. }
  29677. if (this.cameraColorGradingTexture) {
  29678. this.cameraColorGradingTexture.dispose();
  29679. }
  29680. }
  29681. this._renderTargets.dispose();
  29682. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  29683. };
  29684. PBRMaterial.prototype.clone = function (name) {
  29685. var _this = this;
  29686. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  29687. };
  29688. PBRMaterial.prototype.serialize = function () {
  29689. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  29690. serializationObject.customType = "BABYLON.PBRMaterial";
  29691. return serializationObject;
  29692. };
  29693. // Statics
  29694. PBRMaterial.Parse = function (source, scene, rootUrl) {
  29695. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  29696. };
  29697. return PBRMaterial;
  29698. }(BABYLON.Material));
  29699. PBRMaterial._scaledAlbedo = new BABYLON.Color3();
  29700. PBRMaterial._scaledReflectivity = new BABYLON.Color3();
  29701. PBRMaterial._scaledEmissive = new BABYLON.Color3();
  29702. PBRMaterial._scaledReflection = new BABYLON.Color3();
  29703. __decorate([
  29704. BABYLON.serialize()
  29705. ], PBRMaterial.prototype, "directIntensity", void 0);
  29706. __decorate([
  29707. BABYLON.serialize()
  29708. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  29709. __decorate([
  29710. BABYLON.serialize()
  29711. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  29712. __decorate([
  29713. BABYLON.serialize()
  29714. ], PBRMaterial.prototype, "specularIntensity", void 0);
  29715. __decorate([
  29716. BABYLON.serialize()
  29717. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  29718. __decorate([
  29719. BABYLON.serialize()
  29720. ], PBRMaterial.prototype, "overloadedShadowIntensity", void 0);
  29721. __decorate([
  29722. BABYLON.serialize()
  29723. ], PBRMaterial.prototype, "overloadedShadeIntensity", void 0);
  29724. __decorate([
  29725. BABYLON.serialize()
  29726. ], PBRMaterial.prototype, "cameraExposure", void 0);
  29727. __decorate([
  29728. BABYLON.serialize()
  29729. ], PBRMaterial.prototype, "cameraContrast", void 0);
  29730. __decorate([
  29731. BABYLON.serializeAsTexture()
  29732. ], PBRMaterial.prototype, "cameraColorGradingTexture", void 0);
  29733. __decorate([
  29734. BABYLON.serializeAsColorCurves()
  29735. ], PBRMaterial.prototype, "cameraColorCurves", void 0);
  29736. __decorate([
  29737. BABYLON.serializeAsColor3()
  29738. ], PBRMaterial.prototype, "overloadedAmbient", void 0);
  29739. __decorate([
  29740. BABYLON.serialize()
  29741. ], PBRMaterial.prototype, "overloadedAmbientIntensity", void 0);
  29742. __decorate([
  29743. BABYLON.serializeAsColor3()
  29744. ], PBRMaterial.prototype, "overloadedAlbedo", void 0);
  29745. __decorate([
  29746. BABYLON.serialize()
  29747. ], PBRMaterial.prototype, "overloadedAlbedoIntensity", void 0);
  29748. __decorate([
  29749. BABYLON.serializeAsColor3()
  29750. ], PBRMaterial.prototype, "overloadedReflectivity", void 0);
  29751. __decorate([
  29752. BABYLON.serialize()
  29753. ], PBRMaterial.prototype, "overloadedReflectivityIntensity", void 0);
  29754. __decorate([
  29755. BABYLON.serializeAsColor3()
  29756. ], PBRMaterial.prototype, "overloadedEmissive", void 0);
  29757. __decorate([
  29758. BABYLON.serialize()
  29759. ], PBRMaterial.prototype, "overloadedEmissiveIntensity", void 0);
  29760. __decorate([
  29761. BABYLON.serializeAsColor3()
  29762. ], PBRMaterial.prototype, "overloadedReflection", void 0);
  29763. __decorate([
  29764. BABYLON.serialize()
  29765. ], PBRMaterial.prototype, "overloadedReflectionIntensity", void 0);
  29766. __decorate([
  29767. BABYLON.serialize()
  29768. ], PBRMaterial.prototype, "overloadedMicroSurface", void 0);
  29769. __decorate([
  29770. BABYLON.serialize()
  29771. ], PBRMaterial.prototype, "overloadedMicroSurfaceIntensity", void 0);
  29772. __decorate([
  29773. BABYLON.serializeAsTexture()
  29774. ], PBRMaterial.prototype, "albedoTexture", void 0);
  29775. __decorate([
  29776. BABYLON.serializeAsTexture()
  29777. ], PBRMaterial.prototype, "ambientTexture", void 0);
  29778. __decorate([
  29779. BABYLON.serialize()
  29780. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  29781. __decorate([
  29782. BABYLON.serializeAsTexture()
  29783. ], PBRMaterial.prototype, "opacityTexture", void 0);
  29784. __decorate([
  29785. BABYLON.serializeAsTexture()
  29786. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  29787. __decorate([
  29788. BABYLON.serializeAsTexture()
  29789. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  29790. __decorate([
  29791. BABYLON.serializeAsTexture()
  29792. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  29793. __decorate([
  29794. BABYLON.serializeAsTexture()
  29795. ], PBRMaterial.prototype, "metallicTexture", void 0);
  29796. __decorate([
  29797. BABYLON.serialize()
  29798. ], PBRMaterial.prototype, "metallic", void 0);
  29799. __decorate([
  29800. BABYLON.serialize()
  29801. ], PBRMaterial.prototype, "roughness", void 0);
  29802. __decorate([
  29803. BABYLON.serializeAsTexture()
  29804. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  29805. __decorate([
  29806. BABYLON.serializeAsTexture()
  29807. ], PBRMaterial.prototype, "bumpTexture", void 0);
  29808. __decorate([
  29809. BABYLON.serializeAsTexture()
  29810. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  29811. __decorate([
  29812. BABYLON.serializeAsTexture()
  29813. ], PBRMaterial.prototype, "refractionTexture", void 0);
  29814. __decorate([
  29815. BABYLON.serializeAsColor3("ambient")
  29816. ], PBRMaterial.prototype, "ambientColor", void 0);
  29817. __decorate([
  29818. BABYLON.serializeAsColor3("albedo")
  29819. ], PBRMaterial.prototype, "albedoColor", void 0);
  29820. __decorate([
  29821. BABYLON.serializeAsColor3("reflectivity")
  29822. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  29823. __decorate([
  29824. BABYLON.serializeAsColor3("reflection")
  29825. ], PBRMaterial.prototype, "reflectionColor", void 0);
  29826. __decorate([
  29827. BABYLON.serializeAsColor3("emissive")
  29828. ], PBRMaterial.prototype, "emissiveColor", void 0);
  29829. __decorate([
  29830. BABYLON.serialize()
  29831. ], PBRMaterial.prototype, "microSurface", void 0);
  29832. __decorate([
  29833. BABYLON.serialize()
  29834. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  29835. __decorate([
  29836. BABYLON.serialize()
  29837. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  29838. __decorate([
  29839. BABYLON.serializeAsFresnelParameters()
  29840. ], PBRMaterial.prototype, "opacityFresnelParameters", void 0);
  29841. __decorate([
  29842. BABYLON.serializeAsFresnelParameters()
  29843. ], PBRMaterial.prototype, "emissiveFresnelParameters", void 0);
  29844. __decorate([
  29845. BABYLON.serialize()
  29846. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  29847. __decorate([
  29848. BABYLON.serialize()
  29849. ], PBRMaterial.prototype, "linkEmissiveWithAlbedo", void 0);
  29850. __decorate([
  29851. BABYLON.serialize()
  29852. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  29853. __decorate([
  29854. BABYLON.serialize()
  29855. ], PBRMaterial.prototype, "useEmissiveAsIllumination", void 0);
  29856. __decorate([
  29857. BABYLON.serialize()
  29858. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  29859. __decorate([
  29860. BABYLON.serialize()
  29861. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  29862. __decorate([
  29863. BABYLON.serialize()
  29864. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  29865. __decorate([
  29866. BABYLON.serialize()
  29867. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  29868. __decorate([
  29869. BABYLON.serialize()
  29870. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  29871. __decorate([
  29872. BABYLON.serialize()
  29873. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  29874. __decorate([
  29875. BABYLON.serialize()
  29876. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  29877. __decorate([
  29878. BABYLON.serialize()
  29879. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  29880. __decorate([
  29881. BABYLON.serialize()
  29882. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  29883. __decorate([
  29884. BABYLON.serialize()
  29885. ], PBRMaterial.prototype, "useScalarInLinearSpace", void 0);
  29886. __decorate([
  29887. BABYLON.serialize()
  29888. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  29889. __decorate([
  29890. BABYLON.serialize()
  29891. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  29892. __decorate([
  29893. BABYLON.serialize()
  29894. ], PBRMaterial.prototype, "useParallax", void 0);
  29895. __decorate([
  29896. BABYLON.serialize()
  29897. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  29898. __decorate([
  29899. BABYLON.serialize()
  29900. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  29901. __decorate([
  29902. BABYLON.serialize()
  29903. ], PBRMaterial.prototype, "disableLighting", void 0);
  29904. __decorate([
  29905. BABYLON.serialize()
  29906. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  29907. __decorate([
  29908. BABYLON.serialize()
  29909. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  29910. __decorate([
  29911. BABYLON.serialize()
  29912. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  29913. __decorate([
  29914. BABYLON.serialize()
  29915. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  29916. __decorate([
  29917. BABYLON.serialize()
  29918. ], PBRMaterial.prototype, "useLogarithmicDepth", null);
  29919. BABYLON.PBRMaterial = PBRMaterial;
  29920. })(BABYLON || (BABYLON = {}));
  29921. //# sourceMappingURL=babylon.pbrMaterial.js.map
  29922. var BABYLON;
  29923. (function (BABYLON) {
  29924. BABYLON.CameraInputTypes = {};
  29925. var CameraInputsManager = (function () {
  29926. function CameraInputsManager(camera) {
  29927. this.attached = {};
  29928. this.camera = camera;
  29929. this.checkInputs = function () { };
  29930. }
  29931. CameraInputsManager.prototype.add = function (input) {
  29932. var type = input.getSimpleName();
  29933. if (this.attached[type]) {
  29934. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  29935. return;
  29936. }
  29937. this.attached[type] = input;
  29938. input.camera = this.camera;
  29939. //for checkInputs, we are dynamically creating a function
  29940. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  29941. if (input.checkInputs) {
  29942. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  29943. }
  29944. if (this.attachedElement) {
  29945. input.attachControl(this.attachedElement);
  29946. }
  29947. };
  29948. CameraInputsManager.prototype.remove = function (inputToRemove) {
  29949. for (var cam in this.attached) {
  29950. var input = this.attached[cam];
  29951. if (input === inputToRemove) {
  29952. input.detachControl(this.attachedElement);
  29953. delete this.attached[cam];
  29954. this.rebuildInputCheck();
  29955. }
  29956. }
  29957. };
  29958. CameraInputsManager.prototype.removeByType = function (inputType) {
  29959. for (var cam in this.attached) {
  29960. var input = this.attached[cam];
  29961. if (input.getTypeName() === inputType) {
  29962. input.detachControl(this.attachedElement);
  29963. delete this.attached[cam];
  29964. this.rebuildInputCheck();
  29965. }
  29966. }
  29967. };
  29968. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  29969. var current = this.checkInputs;
  29970. return function () {
  29971. current();
  29972. fn();
  29973. };
  29974. };
  29975. CameraInputsManager.prototype.attachInput = function (input) {
  29976. input.attachControl(this.attachedElement, this.noPreventDefault);
  29977. };
  29978. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  29979. if (this.attachedElement) {
  29980. return;
  29981. }
  29982. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  29983. this.attachedElement = element;
  29984. this.noPreventDefault = noPreventDefault;
  29985. for (var cam in this.attached) {
  29986. var input = this.attached[cam];
  29987. this.attached[cam].attachControl(element, noPreventDefault);
  29988. }
  29989. };
  29990. CameraInputsManager.prototype.detachElement = function (element) {
  29991. if (this.attachedElement !== element) {
  29992. return;
  29993. }
  29994. for (var cam in this.attached) {
  29995. var input = this.attached[cam];
  29996. this.attached[cam].detachControl(element);
  29997. }
  29998. this.attachedElement = null;
  29999. };
  30000. CameraInputsManager.prototype.rebuildInputCheck = function () {
  30001. this.checkInputs = function () { };
  30002. for (var cam in this.attached) {
  30003. var input = this.attached[cam];
  30004. if (input.checkInputs) {
  30005. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  30006. }
  30007. }
  30008. };
  30009. CameraInputsManager.prototype.clear = function () {
  30010. if (this.attachedElement) {
  30011. this.detachElement(this.attachedElement);
  30012. }
  30013. this.attached = {};
  30014. this.attachedElement = null;
  30015. this.checkInputs = function () { };
  30016. };
  30017. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  30018. var inputs = {};
  30019. for (var cam in this.attached) {
  30020. var input = this.attached[cam];
  30021. var res = BABYLON.SerializationHelper.Serialize(input);
  30022. inputs[input.getTypeName()] = res;
  30023. }
  30024. serializedCamera.inputsmgr = inputs;
  30025. };
  30026. CameraInputsManager.prototype.parse = function (parsedCamera) {
  30027. var parsedInputs = parsedCamera.inputsmgr;
  30028. if (parsedInputs) {
  30029. this.clear();
  30030. for (var n in parsedInputs) {
  30031. var construct = BABYLON.CameraInputTypes[n];
  30032. if (construct) {
  30033. var parsedinput = parsedInputs[n];
  30034. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  30035. this.add(input);
  30036. }
  30037. }
  30038. }
  30039. else {
  30040. //2016-03-08 this part is for managing backward compatibility
  30041. for (var n in this.attached) {
  30042. var construct = BABYLON.CameraInputTypes[this.attached[n].getTypeName()];
  30043. if (construct) {
  30044. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  30045. this.remove(this.attached[n]);
  30046. this.add(input);
  30047. }
  30048. }
  30049. }
  30050. };
  30051. return CameraInputsManager;
  30052. }());
  30053. BABYLON.CameraInputsManager = CameraInputsManager;
  30054. })(BABYLON || (BABYLON = {}));
  30055. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  30056. var BABYLON;
  30057. (function (BABYLON) {
  30058. var FreeCameraMouseInput = (function () {
  30059. function FreeCameraMouseInput(touchEnabled) {
  30060. if (touchEnabled === void 0) { touchEnabled = true; }
  30061. this.touchEnabled = touchEnabled;
  30062. this.buttons = [0, 1, 2];
  30063. this.angularSensibility = 2000.0;
  30064. }
  30065. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  30066. var _this = this;
  30067. var engine = this.camera.getEngine();
  30068. if (!this._pointerInput) {
  30069. this._pointerInput = function (p, s) {
  30070. var evt = p.event;
  30071. if (!_this.touchEnabled && evt.pointerType === "touch") {
  30072. return;
  30073. }
  30074. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  30075. return;
  30076. }
  30077. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  30078. try {
  30079. evt.srcElement.setPointerCapture(evt.pointerId);
  30080. }
  30081. catch (e) {
  30082. //Nothing to do with the error. Execution will continue.
  30083. }
  30084. _this.previousPosition = {
  30085. x: evt.clientX,
  30086. y: evt.clientY
  30087. };
  30088. if (!noPreventDefault) {
  30089. evt.preventDefault();
  30090. element.focus();
  30091. }
  30092. }
  30093. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  30094. try {
  30095. evt.srcElement.releasePointerCapture(evt.pointerId);
  30096. }
  30097. catch (e) {
  30098. //Nothing to do with the error.
  30099. }
  30100. _this.previousPosition = null;
  30101. if (!noPreventDefault) {
  30102. evt.preventDefault();
  30103. }
  30104. }
  30105. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  30106. if (!_this.previousPosition || engine.isPointerLock) {
  30107. return;
  30108. }
  30109. var offsetX = evt.clientX - _this.previousPosition.x;
  30110. var offsetY = evt.clientY - _this.previousPosition.y;
  30111. if (_this.camera.getScene().useRightHandedSystem) {
  30112. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  30113. }
  30114. else {
  30115. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  30116. }
  30117. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  30118. _this.previousPosition = {
  30119. x: evt.clientX,
  30120. y: evt.clientY
  30121. };
  30122. if (!noPreventDefault) {
  30123. evt.preventDefault();
  30124. }
  30125. }
  30126. };
  30127. }
  30128. this._onMouseMove = function (evt) {
  30129. if (!engine.isPointerLock) {
  30130. return;
  30131. }
  30132. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  30133. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  30134. if (_this.camera.getScene().useRightHandedSystem) {
  30135. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  30136. }
  30137. else {
  30138. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  30139. }
  30140. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  30141. _this.previousPosition = null;
  30142. if (!noPreventDefault) {
  30143. evt.preventDefault();
  30144. }
  30145. };
  30146. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  30147. element.addEventListener("mousemove", this._onMouseMove, false);
  30148. };
  30149. FreeCameraMouseInput.prototype.detachControl = function (element) {
  30150. if (this._observer && element) {
  30151. this.camera.getScene().onPointerObservable.remove(this._observer);
  30152. element.removeEventListener("mousemove", this._onMouseMove);
  30153. this._observer = null;
  30154. this._onMouseMove = null;
  30155. this.previousPosition = null;
  30156. }
  30157. };
  30158. FreeCameraMouseInput.prototype.getTypeName = function () {
  30159. return "FreeCameraMouseInput";
  30160. };
  30161. FreeCameraMouseInput.prototype.getSimpleName = function () {
  30162. return "mouse";
  30163. };
  30164. return FreeCameraMouseInput;
  30165. }());
  30166. __decorate([
  30167. BABYLON.serialize()
  30168. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  30169. __decorate([
  30170. BABYLON.serialize()
  30171. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  30172. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  30173. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  30174. })(BABYLON || (BABYLON = {}));
  30175. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  30176. var BABYLON;
  30177. (function (BABYLON) {
  30178. var FreeCameraKeyboardMoveInput = (function () {
  30179. function FreeCameraKeyboardMoveInput() {
  30180. this._keys = [];
  30181. this.keysUp = [38];
  30182. this.keysDown = [40];
  30183. this.keysLeft = [37];
  30184. this.keysRight = [39];
  30185. }
  30186. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  30187. var _this = this;
  30188. if (!this._onKeyDown) {
  30189. element.tabIndex = 1;
  30190. this._onKeyDown = function (evt) {
  30191. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  30192. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  30193. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  30194. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  30195. var index = _this._keys.indexOf(evt.keyCode);
  30196. if (index === -1) {
  30197. _this._keys.push(evt.keyCode);
  30198. }
  30199. if (!noPreventDefault) {
  30200. evt.preventDefault();
  30201. }
  30202. }
  30203. };
  30204. this._onKeyUp = function (evt) {
  30205. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  30206. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  30207. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  30208. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  30209. var index = _this._keys.indexOf(evt.keyCode);
  30210. if (index >= 0) {
  30211. _this._keys.splice(index, 1);
  30212. }
  30213. if (!noPreventDefault) {
  30214. evt.preventDefault();
  30215. }
  30216. }
  30217. };
  30218. element.addEventListener("keydown", this._onKeyDown, false);
  30219. element.addEventListener("keyup", this._onKeyUp, false);
  30220. BABYLON.Tools.RegisterTopRootEvents([
  30221. { name: "blur", handler: this._onLostFocus }
  30222. ]);
  30223. }
  30224. };
  30225. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  30226. if (this._onKeyDown) {
  30227. element.removeEventListener("keydown", this._onKeyDown);
  30228. element.removeEventListener("keyup", this._onKeyUp);
  30229. BABYLON.Tools.UnregisterTopRootEvents([
  30230. { name: "blur", handler: this._onLostFocus }
  30231. ]);
  30232. this._keys = [];
  30233. this._onKeyDown = null;
  30234. this._onKeyUp = null;
  30235. }
  30236. };
  30237. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  30238. if (this._onKeyDown) {
  30239. var camera = this.camera;
  30240. // Keyboard
  30241. for (var index = 0; index < this._keys.length; index++) {
  30242. var keyCode = this._keys[index];
  30243. var speed = camera._computeLocalCameraSpeed();
  30244. if (this.keysLeft.indexOf(keyCode) !== -1) {
  30245. camera._localDirection.copyFromFloats(-speed, 0, 0);
  30246. }
  30247. else if (this.keysUp.indexOf(keyCode) !== -1) {
  30248. camera._localDirection.copyFromFloats(0, 0, speed);
  30249. }
  30250. else if (this.keysRight.indexOf(keyCode) !== -1) {
  30251. camera._localDirection.copyFromFloats(speed, 0, 0);
  30252. }
  30253. else if (this.keysDown.indexOf(keyCode) !== -1) {
  30254. camera._localDirection.copyFromFloats(0, 0, -speed);
  30255. }
  30256. if (camera.getScene().useRightHandedSystem) {
  30257. camera._localDirection.z *= -1;
  30258. }
  30259. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  30260. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  30261. camera.cameraDirection.addInPlace(camera._transformedDirection);
  30262. }
  30263. }
  30264. };
  30265. FreeCameraKeyboardMoveInput.prototype.getTypeName = function () {
  30266. return "FreeCameraKeyboardMoveInput";
  30267. };
  30268. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  30269. this._keys = [];
  30270. };
  30271. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  30272. return "keyboard";
  30273. };
  30274. return FreeCameraKeyboardMoveInput;
  30275. }());
  30276. __decorate([
  30277. BABYLON.serialize()
  30278. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  30279. __decorate([
  30280. BABYLON.serialize()
  30281. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  30282. __decorate([
  30283. BABYLON.serialize()
  30284. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  30285. __decorate([
  30286. BABYLON.serialize()
  30287. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  30288. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  30289. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  30290. })(BABYLON || (BABYLON = {}));
  30291. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  30292. var BABYLON;
  30293. (function (BABYLON) {
  30294. var FreeCameraInputsManager = (function (_super) {
  30295. __extends(FreeCameraInputsManager, _super);
  30296. function FreeCameraInputsManager(camera) {
  30297. return _super.call(this, camera) || this;
  30298. }
  30299. FreeCameraInputsManager.prototype.addKeyboard = function () {
  30300. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  30301. return this;
  30302. };
  30303. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  30304. if (touchEnabled === void 0) { touchEnabled = true; }
  30305. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  30306. return this;
  30307. };
  30308. FreeCameraInputsManager.prototype.addGamepad = function () {
  30309. this.add(new BABYLON.FreeCameraGamepadInput());
  30310. return this;
  30311. };
  30312. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  30313. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  30314. return this;
  30315. };
  30316. FreeCameraInputsManager.prototype.addTouch = function () {
  30317. this.add(new BABYLON.FreeCameraTouchInput());
  30318. return this;
  30319. };
  30320. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  30321. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  30322. return this;
  30323. };
  30324. return FreeCameraInputsManager;
  30325. }(BABYLON.CameraInputsManager));
  30326. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  30327. })(BABYLON || (BABYLON = {}));
  30328. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  30329. /// <reference path="babylon.camera.ts" />
  30330. var BABYLON;
  30331. (function (BABYLON) {
  30332. var TargetCamera = (function (_super) {
  30333. __extends(TargetCamera, _super);
  30334. function TargetCamera(name, position, scene) {
  30335. var _this = _super.call(this, name, position, scene) || this;
  30336. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  30337. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  30338. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  30339. _this.speed = 2.0;
  30340. _this.noRotationConstraint = false;
  30341. _this.lockedTarget = null;
  30342. _this._currentTarget = BABYLON.Vector3.Zero();
  30343. _this._viewMatrix = BABYLON.Matrix.Zero();
  30344. _this._camMatrix = BABYLON.Matrix.Zero();
  30345. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  30346. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  30347. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  30348. _this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  30349. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  30350. _this._lookAtTemp = BABYLON.Matrix.Zero();
  30351. _this._tempMatrix = BABYLON.Matrix.Zero();
  30352. return _this;
  30353. }
  30354. TargetCamera.prototype.getFrontPosition = function (distance) {
  30355. var direction = this.getTarget().subtract(this.position);
  30356. direction.normalize();
  30357. direction.scaleInPlace(distance);
  30358. return this.globalPosition.add(direction);
  30359. };
  30360. TargetCamera.prototype._getLockedTargetPosition = function () {
  30361. if (!this.lockedTarget) {
  30362. return null;
  30363. }
  30364. if (this.lockedTarget.absolutePosition) {
  30365. this.lockedTarget.computeWorldMatrix();
  30366. }
  30367. return this.lockedTarget.absolutePosition || this.lockedTarget;
  30368. };
  30369. // Cache
  30370. TargetCamera.prototype._initCache = function () {
  30371. _super.prototype._initCache.call(this);
  30372. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  30373. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  30374. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  30375. };
  30376. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  30377. if (!ignoreParentClass) {
  30378. _super.prototype._updateCache.call(this);
  30379. }
  30380. var lockedTargetPosition = this._getLockedTargetPosition();
  30381. if (!lockedTargetPosition) {
  30382. this._cache.lockedTarget = null;
  30383. }
  30384. else {
  30385. if (!this._cache.lockedTarget) {
  30386. this._cache.lockedTarget = lockedTargetPosition.clone();
  30387. }
  30388. else {
  30389. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  30390. }
  30391. }
  30392. this._cache.rotation.copyFrom(this.rotation);
  30393. if (this.rotationQuaternion)
  30394. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  30395. };
  30396. // Synchronized
  30397. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  30398. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  30399. return false;
  30400. }
  30401. var lockedTargetPosition = this._getLockedTargetPosition();
  30402. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  30403. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  30404. };
  30405. // Methods
  30406. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  30407. var engine = this.getEngine();
  30408. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  30409. };
  30410. // Target
  30411. TargetCamera.prototype.setTarget = function (target) {
  30412. this.upVector.normalize();
  30413. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  30414. this._camMatrix.invert();
  30415. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  30416. var vDir = target.subtract(this.position);
  30417. if (vDir.x >= 0.0) {
  30418. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  30419. }
  30420. else {
  30421. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  30422. }
  30423. this.rotation.z = 0;
  30424. if (isNaN(this.rotation.x)) {
  30425. this.rotation.x = 0;
  30426. }
  30427. if (isNaN(this.rotation.y)) {
  30428. this.rotation.y = 0;
  30429. }
  30430. if (isNaN(this.rotation.z)) {
  30431. this.rotation.z = 0;
  30432. }
  30433. if (this.rotationQuaternion) {
  30434. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  30435. }
  30436. };
  30437. /**
  30438. * Return the current target position of the camera. This value is expressed in local space.
  30439. */
  30440. TargetCamera.prototype.getTarget = function () {
  30441. return this._currentTarget;
  30442. };
  30443. TargetCamera.prototype._decideIfNeedsToMove = function () {
  30444. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  30445. };
  30446. TargetCamera.prototype._updatePosition = function () {
  30447. if (this.parent) {
  30448. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  30449. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  30450. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  30451. return;
  30452. }
  30453. this.position.addInPlace(this.cameraDirection);
  30454. };
  30455. TargetCamera.prototype._checkInputs = function () {
  30456. var needToMove = this._decideIfNeedsToMove();
  30457. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  30458. // Move
  30459. if (needToMove) {
  30460. this._updatePosition();
  30461. }
  30462. // Rotate
  30463. if (needToRotate) {
  30464. this.rotation.x += this.cameraRotation.x;
  30465. this.rotation.y += this.cameraRotation.y;
  30466. //rotate, if quaternion is set and rotation was used
  30467. if (this.rotationQuaternion) {
  30468. var len = this.rotation.lengthSquared();
  30469. if (len) {
  30470. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  30471. }
  30472. }
  30473. if (!this.noRotationConstraint) {
  30474. var limit = (Math.PI / 2) * 0.95;
  30475. if (this.rotation.x > limit)
  30476. this.rotation.x = limit;
  30477. if (this.rotation.x < -limit)
  30478. this.rotation.x = -limit;
  30479. }
  30480. }
  30481. // Inertia
  30482. if (needToMove) {
  30483. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  30484. this.cameraDirection.x = 0;
  30485. }
  30486. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  30487. this.cameraDirection.y = 0;
  30488. }
  30489. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  30490. this.cameraDirection.z = 0;
  30491. }
  30492. this.cameraDirection.scaleInPlace(this.inertia);
  30493. }
  30494. if (needToRotate) {
  30495. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  30496. this.cameraRotation.x = 0;
  30497. }
  30498. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  30499. this.cameraRotation.y = 0;
  30500. }
  30501. this.cameraRotation.scaleInPlace(this.inertia);
  30502. }
  30503. _super.prototype._checkInputs.call(this);
  30504. };
  30505. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  30506. if (this.rotationQuaternion) {
  30507. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  30508. //update the up vector!
  30509. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  30510. }
  30511. else {
  30512. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  30513. }
  30514. };
  30515. TargetCamera.prototype._getViewMatrix = function () {
  30516. if (!this.lockedTarget) {
  30517. // Compute
  30518. this._updateCameraRotationMatrix();
  30519. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  30520. // Computing target and final matrix
  30521. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  30522. }
  30523. else {
  30524. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  30525. }
  30526. if (this.getScene().useRightHandedSystem) {
  30527. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  30528. }
  30529. else {
  30530. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  30531. }
  30532. return this._viewMatrix;
  30533. };
  30534. /**
  30535. * @override
  30536. * Override Camera.createRigCamera
  30537. */
  30538. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  30539. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  30540. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  30541. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  30542. if (!this.rotationQuaternion) {
  30543. this.rotationQuaternion = new BABYLON.Quaternion();
  30544. }
  30545. rigCamera._cameraRigParams = {};
  30546. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  30547. }
  30548. return rigCamera;
  30549. }
  30550. return null;
  30551. };
  30552. /**
  30553. * @override
  30554. * Override Camera._updateRigCameras
  30555. */
  30556. TargetCamera.prototype._updateRigCameras = function () {
  30557. var camLeft = this._rigCameras[0];
  30558. var camRight = this._rigCameras[1];
  30559. switch (this.cameraRigMode) {
  30560. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  30561. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  30562. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  30563. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  30564. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  30565. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  30566. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  30567. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  30568. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  30569. camLeft.setTarget(this.getTarget());
  30570. camRight.setTarget(this.getTarget());
  30571. break;
  30572. case BABYLON.Camera.RIG_MODE_VR:
  30573. if (camLeft.rotationQuaternion) {
  30574. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  30575. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  30576. }
  30577. else {
  30578. camLeft.rotation.copyFrom(this.rotation);
  30579. camRight.rotation.copyFrom(this.rotation);
  30580. }
  30581. camLeft.position.copyFrom(this.position);
  30582. camRight.position.copyFrom(this.position);
  30583. break;
  30584. }
  30585. _super.prototype._updateRigCameras.call(this);
  30586. };
  30587. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  30588. if (!this._rigCamTransformMatrix) {
  30589. this._rigCamTransformMatrix = new BABYLON.Matrix();
  30590. }
  30591. var target = this.getTarget();
  30592. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  30593. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  30594. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  30595. };
  30596. TargetCamera.prototype.getClassName = function () {
  30597. return "TargetCamera";
  30598. };
  30599. return TargetCamera;
  30600. }(BABYLON.Camera));
  30601. __decorate([
  30602. BABYLON.serializeAsVector3()
  30603. ], TargetCamera.prototype, "rotation", void 0);
  30604. __decorate([
  30605. BABYLON.serialize()
  30606. ], TargetCamera.prototype, "speed", void 0);
  30607. __decorate([
  30608. BABYLON.serializeAsMeshReference("lockedTargetId")
  30609. ], TargetCamera.prototype, "lockedTarget", void 0);
  30610. BABYLON.TargetCamera = TargetCamera;
  30611. })(BABYLON || (BABYLON = {}));
  30612. //# sourceMappingURL=babylon.targetCamera.js.map
  30613. var BABYLON;
  30614. (function (BABYLON) {
  30615. var FreeCamera = (function (_super) {
  30616. __extends(FreeCamera, _super);
  30617. function FreeCamera(name, position, scene) {
  30618. var _this = _super.call(this, name, position, scene) || this;
  30619. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  30620. _this.checkCollisions = false;
  30621. _this.applyGravity = false;
  30622. _this._needMoveForGravity = false;
  30623. _this._oldPosition = BABYLON.Vector3.Zero();
  30624. _this._diffPosition = BABYLON.Vector3.Zero();
  30625. _this._newPosition = BABYLON.Vector3.Zero();
  30626. // Collisions
  30627. _this._collisionMask = -1;
  30628. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  30629. if (collidedMesh === void 0) { collidedMesh = null; }
  30630. //TODO move this to the collision coordinator!
  30631. if (_this.getScene().workerCollisions)
  30632. newPosition.multiplyInPlace(_this._collider.radius);
  30633. var updatePosition = function (newPos) {
  30634. _this._newPosition.copyFrom(newPos);
  30635. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  30636. var oldPosition = _this.position.clone();
  30637. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  30638. _this.position.addInPlace(_this._diffPosition);
  30639. if (_this.onCollide && collidedMesh) {
  30640. _this.onCollide(collidedMesh);
  30641. }
  30642. }
  30643. };
  30644. updatePosition(newPosition);
  30645. };
  30646. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  30647. _this.inputs.addKeyboard().addMouse();
  30648. return _this;
  30649. }
  30650. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  30651. //-- begin properties for backward compatibility for inputs
  30652. get: function () {
  30653. var mouse = this.inputs.attached["mouse"];
  30654. if (mouse)
  30655. return mouse.angularSensibility;
  30656. },
  30657. set: function (value) {
  30658. var mouse = this.inputs.attached["mouse"];
  30659. if (mouse)
  30660. mouse.angularSensibility = value;
  30661. },
  30662. enumerable: true,
  30663. configurable: true
  30664. });
  30665. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  30666. get: function () {
  30667. var keyboard = this.inputs.attached["keyboard"];
  30668. if (keyboard)
  30669. return keyboard.keysUp;
  30670. },
  30671. set: function (value) {
  30672. var keyboard = this.inputs.attached["keyboard"];
  30673. if (keyboard)
  30674. keyboard.keysUp = value;
  30675. },
  30676. enumerable: true,
  30677. configurable: true
  30678. });
  30679. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  30680. get: function () {
  30681. var keyboard = this.inputs.attached["keyboard"];
  30682. if (keyboard)
  30683. return keyboard.keysDown;
  30684. },
  30685. set: function (value) {
  30686. var keyboard = this.inputs.attached["keyboard"];
  30687. if (keyboard)
  30688. keyboard.keysDown = value;
  30689. },
  30690. enumerable: true,
  30691. configurable: true
  30692. });
  30693. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  30694. get: function () {
  30695. var keyboard = this.inputs.attached["keyboard"];
  30696. if (keyboard)
  30697. return keyboard.keysLeft;
  30698. },
  30699. set: function (value) {
  30700. var keyboard = this.inputs.attached["keyboard"];
  30701. if (keyboard)
  30702. keyboard.keysLeft = value;
  30703. },
  30704. enumerable: true,
  30705. configurable: true
  30706. });
  30707. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  30708. get: function () {
  30709. var keyboard = this.inputs.attached["keyboard"];
  30710. if (keyboard)
  30711. return keyboard.keysRight;
  30712. },
  30713. set: function (value) {
  30714. var keyboard = this.inputs.attached["keyboard"];
  30715. if (keyboard)
  30716. keyboard.keysRight = value;
  30717. },
  30718. enumerable: true,
  30719. configurable: true
  30720. });
  30721. // Controls
  30722. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  30723. this.inputs.attachElement(element, noPreventDefault);
  30724. };
  30725. FreeCamera.prototype.detachControl = function (element) {
  30726. this.inputs.detachElement(element);
  30727. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  30728. this.cameraRotation = new BABYLON.Vector2(0, 0);
  30729. };
  30730. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  30731. get: function () {
  30732. return this._collisionMask;
  30733. },
  30734. set: function (mask) {
  30735. this._collisionMask = !isNaN(mask) ? mask : -1;
  30736. },
  30737. enumerable: true,
  30738. configurable: true
  30739. });
  30740. FreeCamera.prototype._collideWithWorld = function (velocity) {
  30741. var globalPosition;
  30742. if (this.parent) {
  30743. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  30744. }
  30745. else {
  30746. globalPosition = this.position;
  30747. }
  30748. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  30749. if (!this._collider) {
  30750. this._collider = new BABYLON.Collider();
  30751. }
  30752. this._collider.radius = this.ellipsoid;
  30753. this._collider.collisionMask = this._collisionMask;
  30754. //no need for clone, as long as gravity is not on.
  30755. var actualVelocity = velocity;
  30756. //add gravity to the velocity to prevent the dual-collision checking
  30757. if (this.applyGravity) {
  30758. //this prevents mending with cameraDirection, a global variable of the free camera class.
  30759. actualVelocity = velocity.add(this.getScene().gravity);
  30760. }
  30761. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  30762. };
  30763. FreeCamera.prototype._checkInputs = function () {
  30764. if (!this._localDirection) {
  30765. this._localDirection = BABYLON.Vector3.Zero();
  30766. this._transformedDirection = BABYLON.Vector3.Zero();
  30767. }
  30768. this.inputs.checkInputs();
  30769. _super.prototype._checkInputs.call(this);
  30770. };
  30771. FreeCamera.prototype._decideIfNeedsToMove = function () {
  30772. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  30773. };
  30774. FreeCamera.prototype._updatePosition = function () {
  30775. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  30776. this._collideWithWorld(this.cameraDirection);
  30777. }
  30778. else {
  30779. _super.prototype._updatePosition.call(this);
  30780. }
  30781. };
  30782. FreeCamera.prototype.dispose = function () {
  30783. this.inputs.clear();
  30784. _super.prototype.dispose.call(this);
  30785. };
  30786. FreeCamera.prototype.getClassName = function () {
  30787. return "FreeCamera";
  30788. };
  30789. return FreeCamera;
  30790. }(BABYLON.TargetCamera));
  30791. __decorate([
  30792. BABYLON.serializeAsVector3()
  30793. ], FreeCamera.prototype, "ellipsoid", void 0);
  30794. __decorate([
  30795. BABYLON.serialize()
  30796. ], FreeCamera.prototype, "checkCollisions", void 0);
  30797. __decorate([
  30798. BABYLON.serialize()
  30799. ], FreeCamera.prototype, "applyGravity", void 0);
  30800. BABYLON.FreeCamera = FreeCamera;
  30801. })(BABYLON || (BABYLON = {}));
  30802. //# sourceMappingURL=babylon.freeCamera.js.map
  30803. var BABYLON;
  30804. (function (BABYLON) {
  30805. var ArcRotateCameraKeyboardMoveInput = (function () {
  30806. function ArcRotateCameraKeyboardMoveInput() {
  30807. this._keys = [];
  30808. this.keysUp = [38];
  30809. this.keysDown = [40];
  30810. this.keysLeft = [37];
  30811. this.keysRight = [39];
  30812. }
  30813. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  30814. var _this = this;
  30815. element.tabIndex = 1;
  30816. this._onKeyDown = function (evt) {
  30817. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  30818. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  30819. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  30820. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  30821. var index = _this._keys.indexOf(evt.keyCode);
  30822. if (index === -1) {
  30823. _this._keys.push(evt.keyCode);
  30824. }
  30825. if (evt.preventDefault) {
  30826. if (!noPreventDefault) {
  30827. evt.preventDefault();
  30828. }
  30829. }
  30830. }
  30831. };
  30832. this._onKeyUp = function (evt) {
  30833. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  30834. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  30835. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  30836. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  30837. var index = _this._keys.indexOf(evt.keyCode);
  30838. if (index >= 0) {
  30839. _this._keys.splice(index, 1);
  30840. }
  30841. if (evt.preventDefault) {
  30842. if (!noPreventDefault) {
  30843. evt.preventDefault();
  30844. }
  30845. }
  30846. }
  30847. };
  30848. this._onLostFocus = function () {
  30849. _this._keys = [];
  30850. };
  30851. element.addEventListener("keydown", this._onKeyDown, false);
  30852. element.addEventListener("keyup", this._onKeyUp, false);
  30853. BABYLON.Tools.RegisterTopRootEvents([
  30854. { name: "blur", handler: this._onLostFocus }
  30855. ]);
  30856. };
  30857. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  30858. if (element) {
  30859. element.removeEventListener("keydown", this._onKeyDown);
  30860. element.removeEventListener("keyup", this._onKeyUp);
  30861. }
  30862. BABYLON.Tools.UnregisterTopRootEvents([
  30863. { name: "blur", handler: this._onLostFocus }
  30864. ]);
  30865. this._keys = [];
  30866. this._onKeyDown = null;
  30867. this._onKeyUp = null;
  30868. this._onLostFocus = null;
  30869. };
  30870. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  30871. if (this._onKeyDown) {
  30872. var camera = this.camera;
  30873. for (var index = 0; index < this._keys.length; index++) {
  30874. var keyCode = this._keys[index];
  30875. if (this.keysLeft.indexOf(keyCode) !== -1) {
  30876. camera.inertialAlphaOffset -= 0.01;
  30877. }
  30878. else if (this.keysUp.indexOf(keyCode) !== -1) {
  30879. camera.inertialBetaOffset -= 0.01;
  30880. }
  30881. else if (this.keysRight.indexOf(keyCode) !== -1) {
  30882. camera.inertialAlphaOffset += 0.01;
  30883. }
  30884. else if (this.keysDown.indexOf(keyCode) !== -1) {
  30885. camera.inertialBetaOffset += 0.01;
  30886. }
  30887. }
  30888. }
  30889. };
  30890. ArcRotateCameraKeyboardMoveInput.prototype.getTypeName = function () {
  30891. return "ArcRotateCameraKeyboardMoveInput";
  30892. };
  30893. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  30894. return "keyboard";
  30895. };
  30896. return ArcRotateCameraKeyboardMoveInput;
  30897. }());
  30898. __decorate([
  30899. BABYLON.serialize()
  30900. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  30901. __decorate([
  30902. BABYLON.serialize()
  30903. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  30904. __decorate([
  30905. BABYLON.serialize()
  30906. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  30907. __decorate([
  30908. BABYLON.serialize()
  30909. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  30910. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  30911. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  30912. })(BABYLON || (BABYLON = {}));
  30913. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  30914. var BABYLON;
  30915. (function (BABYLON) {
  30916. var ArcRotateCameraMouseWheelInput = (function () {
  30917. function ArcRotateCameraMouseWheelInput() {
  30918. this.wheelPrecision = 3.0;
  30919. }
  30920. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  30921. var _this = this;
  30922. this._wheel = function (p, s) {
  30923. //sanity check - this should be a PointerWheel event.
  30924. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  30925. return;
  30926. var event = p.event;
  30927. var delta = 0;
  30928. if (event.wheelDelta) {
  30929. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  30930. }
  30931. else if (event.detail) {
  30932. delta = -event.detail / _this.wheelPrecision;
  30933. }
  30934. if (delta)
  30935. _this.camera.inertialRadiusOffset += delta;
  30936. if (event.preventDefault) {
  30937. if (!noPreventDefault) {
  30938. event.preventDefault();
  30939. }
  30940. }
  30941. };
  30942. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  30943. };
  30944. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  30945. if (this._observer && element) {
  30946. this.camera.getScene().onPointerObservable.remove(this._observer);
  30947. this._observer = null;
  30948. this._wheel = null;
  30949. }
  30950. };
  30951. ArcRotateCameraMouseWheelInput.prototype.getTypeName = function () {
  30952. return "ArcRotateCameraMouseWheelInput";
  30953. };
  30954. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  30955. return "mousewheel";
  30956. };
  30957. return ArcRotateCameraMouseWheelInput;
  30958. }());
  30959. __decorate([
  30960. BABYLON.serialize()
  30961. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  30962. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  30963. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  30964. })(BABYLON || (BABYLON = {}));
  30965. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  30966. var BABYLON;
  30967. (function (BABYLON) {
  30968. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  30969. var ArcRotateCameraPointersInput = (function () {
  30970. function ArcRotateCameraPointersInput() {
  30971. this.buttons = [0, 1, 2];
  30972. this.angularSensibilityX = 1000.0;
  30973. this.angularSensibilityY = 1000.0;
  30974. this.pinchPrecision = 6.0;
  30975. this.panningSensibility = 50.0;
  30976. this._isPanClick = false;
  30977. this.pinchInwards = true;
  30978. }
  30979. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  30980. var _this = this;
  30981. var engine = this.camera.getEngine();
  30982. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  30983. var pointA, pointB;
  30984. var previousPinchDistance = 0;
  30985. this._pointerInput = function (p, s) {
  30986. var evt = p.event;
  30987. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  30988. return;
  30989. }
  30990. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  30991. try {
  30992. evt.srcElement.setPointerCapture(evt.pointerId);
  30993. }
  30994. catch (e) {
  30995. //Nothing to do with the error. Execution will continue.
  30996. }
  30997. // Manage panning with pan button click
  30998. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  30999. // manage pointers
  31000. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  31001. if (pointA === undefined) {
  31002. pointA = cacheSoloPointer;
  31003. }
  31004. else if (pointB === undefined) {
  31005. pointB = cacheSoloPointer;
  31006. }
  31007. if (!noPreventDefault) {
  31008. evt.preventDefault();
  31009. element.focus();
  31010. }
  31011. }
  31012. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  31013. try {
  31014. evt.srcElement.releasePointerCapture(evt.pointerId);
  31015. }
  31016. catch (e) {
  31017. //Nothing to do with the error.
  31018. }
  31019. cacheSoloPointer = null;
  31020. previousPinchDistance = 0;
  31021. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  31022. //but emptying completly pointers collection is required to fix a bug on iPhone :
  31023. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  31024. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  31025. pointA = pointB = undefined;
  31026. if (!noPreventDefault) {
  31027. evt.preventDefault();
  31028. }
  31029. }
  31030. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  31031. if (!noPreventDefault) {
  31032. evt.preventDefault();
  31033. }
  31034. // One button down
  31035. if (pointA && pointB === undefined) {
  31036. if (_this.panningSensibility !== 0 &&
  31037. ((evt.ctrlKey && _this.camera._useCtrlForPanning) ||
  31038. (!_this.camera._useCtrlForPanning && _this._isPanClick))) {
  31039. _this.camera
  31040. .inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  31041. _this.camera
  31042. .inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  31043. }
  31044. else {
  31045. var offsetX = evt.clientX - cacheSoloPointer.x;
  31046. var offsetY = evt.clientY - cacheSoloPointer.y;
  31047. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  31048. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  31049. }
  31050. cacheSoloPointer.x = evt.clientX;
  31051. cacheSoloPointer.y = evt.clientY;
  31052. }
  31053. else if (pointA && pointB) {
  31054. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  31055. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  31056. ed.x = evt.clientX;
  31057. ed.y = evt.clientY;
  31058. var direction = _this.pinchInwards ? 1 : -1;
  31059. var distX = pointA.x - pointB.x;
  31060. var distY = pointA.y - pointB.y;
  31061. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  31062. if (previousPinchDistance === 0) {
  31063. previousPinchDistance = pinchSquaredDistance;
  31064. return;
  31065. }
  31066. if (pinchSquaredDistance !== previousPinchDistance) {
  31067. _this.camera
  31068. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) /
  31069. (_this.pinchPrecision *
  31070. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  31071. direction);
  31072. previousPinchDistance = pinchSquaredDistance;
  31073. }
  31074. }
  31075. }
  31076. };
  31077. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  31078. this._onContextMenu = function (evt) {
  31079. evt.preventDefault();
  31080. };
  31081. if (!this.camera._useCtrlForPanning) {
  31082. element.addEventListener("contextmenu", this._onContextMenu, false);
  31083. }
  31084. this._onLostFocus = function () {
  31085. //this._keys = [];
  31086. pointA = pointB = undefined;
  31087. previousPinchDistance = 0;
  31088. cacheSoloPointer = null;
  31089. };
  31090. this._onMouseMove = function (evt) {
  31091. if (!engine.isPointerLock) {
  31092. return;
  31093. }
  31094. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  31095. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  31096. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  31097. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  31098. if (!noPreventDefault) {
  31099. evt.preventDefault();
  31100. }
  31101. };
  31102. this._onGestureStart = function (e) {
  31103. if (window.MSGesture === undefined) {
  31104. return;
  31105. }
  31106. if (!_this._MSGestureHandler) {
  31107. _this._MSGestureHandler = new MSGesture();
  31108. _this._MSGestureHandler.target = element;
  31109. }
  31110. _this._MSGestureHandler.addPointer(e.pointerId);
  31111. };
  31112. this._onGesture = function (e) {
  31113. _this.camera.radius *= e.scale;
  31114. if (e.preventDefault) {
  31115. if (!noPreventDefault) {
  31116. e.stopPropagation();
  31117. e.preventDefault();
  31118. }
  31119. }
  31120. };
  31121. element.addEventListener("mousemove", this._onMouseMove, false);
  31122. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  31123. element.addEventListener("MSGestureChange", this._onGesture, false);
  31124. BABYLON.Tools.RegisterTopRootEvents([
  31125. { name: "blur", handler: this._onLostFocus }
  31126. ]);
  31127. };
  31128. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  31129. if (element && this._observer) {
  31130. this.camera.getScene().onPointerObservable.remove(this._observer);
  31131. this._observer = null;
  31132. element.removeEventListener("contextmenu", this._onContextMenu);
  31133. element.removeEventListener("mousemove", this._onMouseMove);
  31134. element.removeEventListener("MSPointerDown", this._onGestureStart);
  31135. element.removeEventListener("MSGestureChange", this._onGesture);
  31136. this._isPanClick = false;
  31137. this.pinchInwards = true;
  31138. this._onMouseMove = null;
  31139. this._onGestureStart = null;
  31140. this._onGesture = null;
  31141. this._MSGestureHandler = null;
  31142. this._onLostFocus = null;
  31143. this._onContextMenu = null;
  31144. }
  31145. BABYLON.Tools.UnregisterTopRootEvents([
  31146. { name: "blur", handler: this._onLostFocus }
  31147. ]);
  31148. };
  31149. ArcRotateCameraPointersInput.prototype.getTypeName = function () {
  31150. return "ArcRotateCameraPointersInput";
  31151. };
  31152. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  31153. return "pointers";
  31154. };
  31155. return ArcRotateCameraPointersInput;
  31156. }());
  31157. __decorate([
  31158. BABYLON.serialize()
  31159. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  31160. __decorate([
  31161. BABYLON.serialize()
  31162. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  31163. __decorate([
  31164. BABYLON.serialize()
  31165. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  31166. __decorate([
  31167. BABYLON.serialize()
  31168. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  31169. __decorate([
  31170. BABYLON.serialize()
  31171. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  31172. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  31173. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  31174. })(BABYLON || (BABYLON = {}));
  31175. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  31176. /// <reference path="babylon.targetCamera.ts" />
  31177. /// <reference path="..\Tools\babylon.tools.ts" />
  31178. var BABYLON;
  31179. (function (BABYLON) {
  31180. var ArcRotateCamera = (function (_super) {
  31181. __extends(ArcRotateCamera, _super);
  31182. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  31183. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  31184. _this.inertialAlphaOffset = 0;
  31185. _this.inertialBetaOffset = 0;
  31186. _this.inertialRadiusOffset = 0;
  31187. _this.lowerAlphaLimit = null;
  31188. _this.upperAlphaLimit = null;
  31189. _this.lowerBetaLimit = 0.01;
  31190. _this.upperBetaLimit = Math.PI;
  31191. _this.lowerRadiusLimit = null;
  31192. _this.upperRadiusLimit = null;
  31193. _this.inertialPanningX = 0;
  31194. _this.inertialPanningY = 0;
  31195. //-- end properties for backward compatibility for inputs
  31196. _this.zoomOnFactor = 1;
  31197. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  31198. _this.allowUpsideDown = true;
  31199. _this._viewMatrix = new BABYLON.Matrix();
  31200. // Panning
  31201. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  31202. _this.checkCollisions = false;
  31203. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  31204. _this._previousPosition = BABYLON.Vector3.Zero();
  31205. _this._collisionVelocity = BABYLON.Vector3.Zero();
  31206. _this._newPosition = BABYLON.Vector3.Zero();
  31207. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  31208. if (collidedMesh === void 0) { collidedMesh = null; }
  31209. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  31210. newPosition.multiplyInPlace(_this._collider.radius);
  31211. }
  31212. if (!collidedMesh) {
  31213. _this._previousPosition.copyFrom(_this.position);
  31214. }
  31215. else {
  31216. _this.setPosition(newPosition);
  31217. if (_this.onCollide) {
  31218. _this.onCollide(collidedMesh);
  31219. }
  31220. }
  31221. // Recompute because of constraints
  31222. var cosa = Math.cos(_this.alpha);
  31223. var sina = Math.sin(_this.alpha);
  31224. var cosb = Math.cos(_this.beta);
  31225. var sinb = Math.sin(_this.beta);
  31226. if (sinb === 0) {
  31227. sinb = 0.0001;
  31228. }
  31229. var target = _this._getTargetPosition();
  31230. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  31231. _this.position.copyFrom(_this._newPosition);
  31232. var up = _this.upVector;
  31233. if (_this.allowUpsideDown && _this.beta < 0) {
  31234. up = up.clone();
  31235. up = up.negate();
  31236. }
  31237. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  31238. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  31239. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  31240. _this._collisionTriggered = false;
  31241. };
  31242. _this._target = BABYLON.Vector3.Zero();
  31243. if (target) {
  31244. _this.setTarget(target);
  31245. }
  31246. _this.alpha = alpha;
  31247. _this.beta = beta;
  31248. _this.radius = radius;
  31249. _this.getViewMatrix();
  31250. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  31251. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  31252. return _this;
  31253. }
  31254. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  31255. get: function () {
  31256. return this._target;
  31257. },
  31258. set: function (value) {
  31259. this.setTarget(value);
  31260. },
  31261. enumerable: true,
  31262. configurable: true
  31263. });
  31264. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  31265. //-- begin properties for backward compatibility for inputs
  31266. get: function () {
  31267. var pointers = this.inputs.attached["pointers"];
  31268. if (pointers)
  31269. return pointers.angularSensibilityX;
  31270. },
  31271. set: function (value) {
  31272. var pointers = this.inputs.attached["pointers"];
  31273. if (pointers) {
  31274. pointers.angularSensibilityX = value;
  31275. }
  31276. },
  31277. enumerable: true,
  31278. configurable: true
  31279. });
  31280. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  31281. get: function () {
  31282. var pointers = this.inputs.attached["pointers"];
  31283. if (pointers)
  31284. return pointers.angularSensibilityY;
  31285. },
  31286. set: function (value) {
  31287. var pointers = this.inputs.attached["pointers"];
  31288. if (pointers) {
  31289. pointers.angularSensibilityY = value;
  31290. }
  31291. },
  31292. enumerable: true,
  31293. configurable: true
  31294. });
  31295. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  31296. get: function () {
  31297. var pointers = this.inputs.attached["pointers"];
  31298. if (pointers)
  31299. return pointers.pinchPrecision;
  31300. },
  31301. set: function (value) {
  31302. var pointers = this.inputs.attached["pointers"];
  31303. if (pointers) {
  31304. pointers.pinchPrecision = value;
  31305. }
  31306. },
  31307. enumerable: true,
  31308. configurable: true
  31309. });
  31310. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  31311. get: function () {
  31312. var pointers = this.inputs.attached["pointers"];
  31313. if (pointers)
  31314. return pointers.panningSensibility;
  31315. },
  31316. set: function (value) {
  31317. var pointers = this.inputs.attached["pointers"];
  31318. if (pointers) {
  31319. pointers.panningSensibility = value;
  31320. }
  31321. },
  31322. enumerable: true,
  31323. configurable: true
  31324. });
  31325. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  31326. get: function () {
  31327. var keyboard = this.inputs.attached["keyboard"];
  31328. if (keyboard)
  31329. return keyboard.keysUp;
  31330. },
  31331. set: function (value) {
  31332. var keyboard = this.inputs.attached["keyboard"];
  31333. if (keyboard)
  31334. keyboard.keysUp = value;
  31335. },
  31336. enumerable: true,
  31337. configurable: true
  31338. });
  31339. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  31340. get: function () {
  31341. var keyboard = this.inputs.attached["keyboard"];
  31342. if (keyboard)
  31343. return keyboard.keysDown;
  31344. },
  31345. set: function (value) {
  31346. var keyboard = this.inputs.attached["keyboard"];
  31347. if (keyboard)
  31348. keyboard.keysDown = value;
  31349. },
  31350. enumerable: true,
  31351. configurable: true
  31352. });
  31353. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  31354. get: function () {
  31355. var keyboard = this.inputs.attached["keyboard"];
  31356. if (keyboard)
  31357. return keyboard.keysLeft;
  31358. },
  31359. set: function (value) {
  31360. var keyboard = this.inputs.attached["keyboard"];
  31361. if (keyboard)
  31362. keyboard.keysLeft = value;
  31363. },
  31364. enumerable: true,
  31365. configurable: true
  31366. });
  31367. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  31368. get: function () {
  31369. var keyboard = this.inputs.attached["keyboard"];
  31370. if (keyboard)
  31371. return keyboard.keysRight;
  31372. },
  31373. set: function (value) {
  31374. var keyboard = this.inputs.attached["keyboard"];
  31375. if (keyboard)
  31376. keyboard.keysRight = value;
  31377. },
  31378. enumerable: true,
  31379. configurable: true
  31380. });
  31381. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  31382. get: function () {
  31383. var mousewheel = this.inputs.attached["mousewheel"];
  31384. if (mousewheel)
  31385. return mousewheel.wheelPrecision;
  31386. },
  31387. set: function (value) {
  31388. var mousewheel = this.inputs.attached["mousewheel"];
  31389. if (mousewheel)
  31390. mousewheel.wheelPrecision = value;
  31391. },
  31392. enumerable: true,
  31393. configurable: true
  31394. });
  31395. // Cache
  31396. ArcRotateCamera.prototype._initCache = function () {
  31397. _super.prototype._initCache.call(this);
  31398. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  31399. this._cache.alpha = undefined;
  31400. this._cache.beta = undefined;
  31401. this._cache.radius = undefined;
  31402. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  31403. };
  31404. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  31405. if (!ignoreParentClass) {
  31406. _super.prototype._updateCache.call(this);
  31407. }
  31408. this._cache._target.copyFrom(this._getTargetPosition());
  31409. this._cache.alpha = this.alpha;
  31410. this._cache.beta = this.beta;
  31411. this._cache.radius = this.radius;
  31412. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  31413. };
  31414. ArcRotateCamera.prototype._getTargetPosition = function () {
  31415. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  31416. var pos = this._targetHost.getAbsolutePosition();
  31417. if (this._targetBoundingCenter) {
  31418. pos.addToRef(this._targetBoundingCenter, this._target);
  31419. }
  31420. else {
  31421. this._target.copyFrom(pos);
  31422. }
  31423. }
  31424. return this._target;
  31425. };
  31426. // Synchronized
  31427. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  31428. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  31429. return false;
  31430. return this._cache._target.equals(this._target)
  31431. && this._cache.alpha === this.alpha
  31432. && this._cache.beta === this.beta
  31433. && this._cache.radius === this.radius
  31434. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  31435. };
  31436. // Methods
  31437. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  31438. var _this = this;
  31439. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  31440. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  31441. this._useCtrlForPanning = useCtrlForPanning;
  31442. this._panningMouseButton = panningMouseButton;
  31443. this.inputs.attachElement(element, noPreventDefault);
  31444. this._reset = function () {
  31445. _this.inertialAlphaOffset = 0;
  31446. _this.inertialBetaOffset = 0;
  31447. _this.inertialRadiusOffset = 0;
  31448. };
  31449. };
  31450. ArcRotateCamera.prototype.detachControl = function (element) {
  31451. this.inputs.detachElement(element);
  31452. if (this._reset) {
  31453. this._reset();
  31454. }
  31455. };
  31456. ArcRotateCamera.prototype._checkInputs = function () {
  31457. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  31458. if (this._collisionTriggered) {
  31459. return;
  31460. }
  31461. this.inputs.checkInputs();
  31462. // Inertia
  31463. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  31464. if (this.getScene().useRightHandedSystem) {
  31465. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  31466. }
  31467. else {
  31468. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  31469. }
  31470. this.beta += this.inertialBetaOffset;
  31471. this.radius -= this.inertialRadiusOffset;
  31472. this.inertialAlphaOffset *= this.inertia;
  31473. this.inertialBetaOffset *= this.inertia;
  31474. this.inertialRadiusOffset *= this.inertia;
  31475. if (Math.abs(this.inertialAlphaOffset) < this.speed * BABYLON.Epsilon)
  31476. this.inertialAlphaOffset = 0;
  31477. if (Math.abs(this.inertialBetaOffset) < this.speed * BABYLON.Epsilon)
  31478. this.inertialBetaOffset = 0;
  31479. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  31480. this.inertialRadiusOffset = 0;
  31481. }
  31482. // Panning inertia
  31483. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  31484. if (!this._localDirection) {
  31485. this._localDirection = BABYLON.Vector3.Zero();
  31486. this._transformedDirection = BABYLON.Vector3.Zero();
  31487. }
  31488. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  31489. this._localDirection.multiplyInPlace(this.panningAxis);
  31490. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  31491. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  31492. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  31493. if (!this.panningAxis.y) {
  31494. this._transformedDirection.y = 0;
  31495. }
  31496. if (!this._targetHost) {
  31497. this._target.addInPlace(this._transformedDirection);
  31498. }
  31499. this.inertialPanningX *= this.inertia;
  31500. this.inertialPanningY *= this.inertia;
  31501. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  31502. this.inertialPanningX = 0;
  31503. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  31504. this.inertialPanningY = 0;
  31505. }
  31506. // Limits
  31507. this._checkLimits();
  31508. _super.prototype._checkInputs.call(this);
  31509. };
  31510. ArcRotateCamera.prototype._checkLimits = function () {
  31511. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  31512. if (this.allowUpsideDown && this.beta > Math.PI) {
  31513. this.beta = this.beta - (2 * Math.PI);
  31514. }
  31515. }
  31516. else {
  31517. if (this.beta < this.lowerBetaLimit) {
  31518. this.beta = this.lowerBetaLimit;
  31519. }
  31520. }
  31521. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  31522. if (this.allowUpsideDown && this.beta < -Math.PI) {
  31523. this.beta = this.beta + (2 * Math.PI);
  31524. }
  31525. }
  31526. else {
  31527. if (this.beta > this.upperBetaLimit) {
  31528. this.beta = this.upperBetaLimit;
  31529. }
  31530. }
  31531. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  31532. this.alpha = this.lowerAlphaLimit;
  31533. }
  31534. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  31535. this.alpha = this.upperAlphaLimit;
  31536. }
  31537. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  31538. this.radius = this.lowerRadiusLimit;
  31539. }
  31540. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  31541. this.radius = this.upperRadiusLimit;
  31542. }
  31543. };
  31544. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  31545. var radiusv3 = this.position.subtract(this._getTargetPosition());
  31546. this.radius = radiusv3.length();
  31547. // Alpha
  31548. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  31549. if (radiusv3.z < 0) {
  31550. this.alpha = 2 * Math.PI - this.alpha;
  31551. }
  31552. // Beta
  31553. this.beta = Math.acos(radiusv3.y / this.radius);
  31554. this._checkLimits();
  31555. };
  31556. ArcRotateCamera.prototype.setPosition = function (position) {
  31557. if (this.position.equals(position)) {
  31558. return;
  31559. }
  31560. this.position.copyFrom(position);
  31561. this.rebuildAnglesAndRadius();
  31562. };
  31563. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  31564. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  31565. if (allowSamePosition === void 0) { allowSamePosition = false; }
  31566. if (target.getBoundingInfo) {
  31567. if (toBoundingCenter) {
  31568. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  31569. }
  31570. else {
  31571. this._targetBoundingCenter = null;
  31572. }
  31573. this._targetHost = target;
  31574. this._target = this._getTargetPosition();
  31575. }
  31576. else {
  31577. var newTarget = target;
  31578. var currentTarget = this._getTargetPosition();
  31579. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  31580. return;
  31581. }
  31582. this._target = newTarget;
  31583. this._targetBoundingCenter = null;
  31584. }
  31585. this.rebuildAnglesAndRadius();
  31586. };
  31587. ArcRotateCamera.prototype._getViewMatrix = function () {
  31588. // Compute
  31589. var cosa = Math.cos(this.alpha);
  31590. var sina = Math.sin(this.alpha);
  31591. var cosb = Math.cos(this.beta);
  31592. var sinb = Math.sin(this.beta);
  31593. if (sinb === 0) {
  31594. sinb = 0.0001;
  31595. }
  31596. var target = this._getTargetPosition();
  31597. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  31598. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  31599. if (!this._collider) {
  31600. this._collider = new BABYLON.Collider();
  31601. }
  31602. this._collider.radius = this.collisionRadius;
  31603. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  31604. this._collisionTriggered = true;
  31605. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  31606. }
  31607. else {
  31608. this.position.copyFrom(this._newPosition);
  31609. var up = this.upVector;
  31610. if (this.allowUpsideDown && sinb < 0) {
  31611. up = up.clone();
  31612. up = up.negate();
  31613. }
  31614. if (this.getScene().useRightHandedSystem) {
  31615. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  31616. }
  31617. else {
  31618. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  31619. }
  31620. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  31621. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  31622. }
  31623. this._currentTarget = target;
  31624. return this._viewMatrix;
  31625. };
  31626. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  31627. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  31628. meshes = meshes || this.getScene().meshes;
  31629. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  31630. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  31631. this.radius = distance * this.zoomOnFactor;
  31632. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  31633. };
  31634. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  31635. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  31636. var meshesOrMinMaxVector;
  31637. var distance;
  31638. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  31639. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  31640. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  31641. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  31642. }
  31643. else {
  31644. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  31645. distance = meshesOrMinMaxVectorAndDistance.distance;
  31646. }
  31647. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  31648. if (!doNotUpdateMaxZ) {
  31649. this.maxZ = distance * 2;
  31650. }
  31651. };
  31652. /**
  31653. * @override
  31654. * Override Camera.createRigCamera
  31655. */
  31656. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  31657. var alphaShift;
  31658. switch (this.cameraRigMode) {
  31659. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  31660. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  31661. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  31662. case BABYLON.Camera.RIG_MODE_VR:
  31663. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  31664. break;
  31665. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  31666. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  31667. break;
  31668. }
  31669. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  31670. rigCam._cameraRigParams = {};
  31671. return rigCam;
  31672. };
  31673. /**
  31674. * @override
  31675. * Override Camera._updateRigCameras
  31676. */
  31677. ArcRotateCamera.prototype._updateRigCameras = function () {
  31678. var camLeft = this._rigCameras[0];
  31679. var camRight = this._rigCameras[1];
  31680. camLeft.beta = camRight.beta = this.beta;
  31681. camLeft.radius = camRight.radius = this.radius;
  31682. switch (this.cameraRigMode) {
  31683. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  31684. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  31685. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  31686. case BABYLON.Camera.RIG_MODE_VR:
  31687. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  31688. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  31689. break;
  31690. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  31691. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  31692. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  31693. break;
  31694. }
  31695. _super.prototype._updateRigCameras.call(this);
  31696. };
  31697. ArcRotateCamera.prototype.dispose = function () {
  31698. this.inputs.clear();
  31699. _super.prototype.dispose.call(this);
  31700. };
  31701. ArcRotateCamera.prototype.getClassName = function () {
  31702. return "ArcRotateCamera";
  31703. };
  31704. return ArcRotateCamera;
  31705. }(BABYLON.TargetCamera));
  31706. __decorate([
  31707. BABYLON.serialize()
  31708. ], ArcRotateCamera.prototype, "alpha", void 0);
  31709. __decorate([
  31710. BABYLON.serialize()
  31711. ], ArcRotateCamera.prototype, "beta", void 0);
  31712. __decorate([
  31713. BABYLON.serialize()
  31714. ], ArcRotateCamera.prototype, "radius", void 0);
  31715. __decorate([
  31716. BABYLON.serializeAsVector3("target")
  31717. ], ArcRotateCamera.prototype, "_target", void 0);
  31718. __decorate([
  31719. BABYLON.serialize()
  31720. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  31721. __decorate([
  31722. BABYLON.serialize()
  31723. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  31724. __decorate([
  31725. BABYLON.serialize()
  31726. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  31727. __decorate([
  31728. BABYLON.serialize()
  31729. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  31730. __decorate([
  31731. BABYLON.serialize()
  31732. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  31733. __decorate([
  31734. BABYLON.serialize()
  31735. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  31736. __decorate([
  31737. BABYLON.serialize()
  31738. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  31739. __decorate([
  31740. BABYLON.serialize()
  31741. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  31742. __decorate([
  31743. BABYLON.serialize()
  31744. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  31745. __decorate([
  31746. BABYLON.serialize()
  31747. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  31748. __decorate([
  31749. BABYLON.serialize()
  31750. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  31751. __decorate([
  31752. BABYLON.serialize()
  31753. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  31754. __decorate([
  31755. BABYLON.serialize()
  31756. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  31757. BABYLON.ArcRotateCamera = ArcRotateCamera;
  31758. })(BABYLON || (BABYLON = {}));
  31759. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  31760. /// <reference path="..\Cameras\babylon.cameraInputsManager.ts" />
  31761. var BABYLON;
  31762. (function (BABYLON) {
  31763. var ArcRotateCameraInputsManager = (function (_super) {
  31764. __extends(ArcRotateCameraInputsManager, _super);
  31765. function ArcRotateCameraInputsManager(camera) {
  31766. return _super.call(this, camera) || this;
  31767. }
  31768. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  31769. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  31770. return this;
  31771. };
  31772. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  31773. this.add(new BABYLON.ArcRotateCameraPointersInput());
  31774. return this;
  31775. };
  31776. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  31777. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  31778. return this;
  31779. };
  31780. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  31781. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  31782. return this;
  31783. };
  31784. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  31785. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  31786. return this;
  31787. };
  31788. return ArcRotateCameraInputsManager;
  31789. }(BABYLON.CameraInputsManager));
  31790. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  31791. })(BABYLON || (BABYLON = {}));
  31792. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  31793. var BABYLON;
  31794. (function (BABYLON) {
  31795. var HemisphericLight = (function (_super) {
  31796. __extends(HemisphericLight, _super);
  31797. /**
  31798. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  31799. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  31800. * The HemisphericLight can't cast shadows.
  31801. * Documentation : http://doc.babylonjs.com/tutorials/lights
  31802. */
  31803. function HemisphericLight(name, direction, scene) {
  31804. var _this = _super.call(this, name, scene) || this;
  31805. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  31806. _this.direction = direction || BABYLON.Vector3.Up();
  31807. return _this;
  31808. }
  31809. HemisphericLight.prototype._buildUniformLayout = function () {
  31810. this._uniformBuffer.addUniform("vLightData", 4);
  31811. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  31812. this._uniformBuffer.addUniform("vLightSpecular", 3);
  31813. this._uniformBuffer.addUniform("vLightGround", 3);
  31814. this._uniformBuffer.addUniform("shadowsInfo", 3);
  31815. this._uniformBuffer.create();
  31816. };
  31817. /**
  31818. * Returns the string "HemisphericLight".
  31819. */
  31820. HemisphericLight.prototype.getClassName = function () {
  31821. return "HemisphericLight";
  31822. };
  31823. /**
  31824. * Sets the HemisphericLight direction towards the passed target (Vector3).
  31825. * Returns the updated direction.
  31826. */
  31827. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  31828. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  31829. return this.direction;
  31830. };
  31831. HemisphericLight.prototype.getShadowGenerator = function () {
  31832. return null;
  31833. };
  31834. /**
  31835. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  31836. * Returns the HemisphericLight.
  31837. */
  31838. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  31839. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  31840. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  31841. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  31842. return this;
  31843. };
  31844. HemisphericLight.prototype._getWorldMatrix = function () {
  31845. if (!this._worldMatrix) {
  31846. this._worldMatrix = BABYLON.Matrix.Identity();
  31847. }
  31848. return this._worldMatrix;
  31849. };
  31850. /**
  31851. * Returns the integer 3.
  31852. */
  31853. HemisphericLight.prototype.getTypeID = function () {
  31854. return 3;
  31855. };
  31856. return HemisphericLight;
  31857. }(BABYLON.Light));
  31858. __decorate([
  31859. BABYLON.serializeAsColor3()
  31860. ], HemisphericLight.prototype, "groundColor", void 0);
  31861. __decorate([
  31862. BABYLON.serializeAsVector3()
  31863. ], HemisphericLight.prototype, "direction", void 0);
  31864. BABYLON.HemisphericLight = HemisphericLight;
  31865. })(BABYLON || (BABYLON = {}));
  31866. //# sourceMappingURL=babylon.hemisphericLight.js.map
  31867. var BABYLON;
  31868. (function (BABYLON) {
  31869. var PointLight = (function (_super) {
  31870. __extends(PointLight, _super);
  31871. /**
  31872. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  31873. * A PointLight emits the light in every direction.
  31874. * It can cast shadows.
  31875. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  31876. * ```javascript
  31877. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  31878. * ```
  31879. * Documentation : http://doc.babylonjs.com/tutorials/lights
  31880. */
  31881. function PointLight(name, position, scene) {
  31882. var _this = _super.call(this, name, scene) || this;
  31883. _this.position = position;
  31884. return _this;
  31885. }
  31886. PointLight.prototype._buildUniformLayout = function () {
  31887. this._uniformBuffer.addUniform("vLightData", 4);
  31888. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  31889. this._uniformBuffer.addUniform("vLightSpecular", 3);
  31890. this._uniformBuffer.addUniform("shadowsInfo", 3);
  31891. this._uniformBuffer.create();
  31892. };
  31893. /**
  31894. * Returns the string "PointLight"
  31895. */
  31896. PointLight.prototype.getClassName = function () {
  31897. return "PointLight";
  31898. };
  31899. /**
  31900. * Returns a Vector3, the PointLight absolute position in the World.
  31901. */
  31902. PointLight.prototype.getAbsolutePosition = function () {
  31903. return this.transformedPosition ? this.transformedPosition : this.position;
  31904. };
  31905. /**
  31906. * Computes the PointLight transformed position if parented. Returns true if ok, false if not parented.
  31907. */
  31908. PointLight.prototype.computeTransformedPosition = function () {
  31909. if (this.parent && this.parent.getWorldMatrix) {
  31910. if (!this.transformedPosition) {
  31911. this.transformedPosition = BABYLON.Vector3.Zero();
  31912. }
  31913. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  31914. return true;
  31915. }
  31916. return false;
  31917. };
  31918. /**
  31919. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  31920. * Returns the PointLight.
  31921. */
  31922. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  31923. if (this.parent && this.parent.getWorldMatrix) {
  31924. this.computeTransformedPosition();
  31925. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  31926. return this;
  31927. }
  31928. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  31929. return this;
  31930. };
  31931. /**
  31932. * Boolean : returns true by default.
  31933. */
  31934. PointLight.prototype.needCube = function () {
  31935. return true;
  31936. };
  31937. /**
  31938. * Boolean : returns false by default.
  31939. */
  31940. PointLight.prototype.needRefreshPerFrame = function () {
  31941. return false;
  31942. };
  31943. /**
  31944. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  31945. */
  31946. PointLight.prototype.getShadowDirection = function (faceIndex) {
  31947. switch (faceIndex) {
  31948. case 0:
  31949. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  31950. case 1:
  31951. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  31952. case 2:
  31953. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  31954. case 3:
  31955. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  31956. case 4:
  31957. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  31958. case 5:
  31959. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  31960. }
  31961. return BABYLON.Vector3.Zero();
  31962. };
  31963. /**
  31964. * Return the depth scale used for the shadow map.
  31965. */
  31966. PointLight.prototype.getDepthScale = function () {
  31967. return 30.0;
  31968. };
  31969. /**
  31970. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  31971. * - fov = PI / 2
  31972. * - aspect ratio : 1.0
  31973. * - z-near and far equal to the active camera minZ and maxZ.
  31974. * Returns the PointLight.
  31975. */
  31976. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  31977. if (this.customProjectionMatrixBuilder) {
  31978. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  31979. }
  31980. else {
  31981. var activeCamera = this.getScene().activeCamera;
  31982. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  31983. }
  31984. return this;
  31985. };
  31986. PointLight.prototype._getWorldMatrix = function () {
  31987. if (!this._worldMatrix) {
  31988. this._worldMatrix = BABYLON.Matrix.Identity();
  31989. }
  31990. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  31991. return this._worldMatrix;
  31992. };
  31993. /**
  31994. * Returns the integer 0.
  31995. */
  31996. PointLight.prototype.getTypeID = function () {
  31997. return 0;
  31998. };
  31999. return PointLight;
  32000. }(BABYLON.Light));
  32001. __decorate([
  32002. BABYLON.serializeAsVector3()
  32003. ], PointLight.prototype, "position", void 0);
  32004. __decorate([
  32005. BABYLON.serialize()
  32006. ], PointLight.prototype, "shadowMinZ", void 0);
  32007. __decorate([
  32008. BABYLON.serialize()
  32009. ], PointLight.prototype, "shadowMaxZ", void 0);
  32010. BABYLON.PointLight = PointLight;
  32011. })(BABYLON || (BABYLON = {}));
  32012. //# sourceMappingURL=babylon.pointLight.js.map
  32013. /// <reference path="babylon.light.ts" />
  32014. var BABYLON;
  32015. (function (BABYLON) {
  32016. var DirectionalLight = (function (_super) {
  32017. __extends(DirectionalLight, _super);
  32018. /**
  32019. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  32020. * The directional light is emitted from everywhere in the given direction.
  32021. * It can cast shawdows.
  32022. * Documentation : http://doc.babylonjs.com/tutorials/lights
  32023. */
  32024. function DirectionalLight(name, direction, scene) {
  32025. var _this = _super.call(this, name, scene) || this;
  32026. _this.shadowOrthoScale = 0.5;
  32027. _this.autoUpdateExtends = true;
  32028. // Cache
  32029. _this._orthoLeft = Number.MAX_VALUE;
  32030. _this._orthoRight = Number.MIN_VALUE;
  32031. _this._orthoTop = Number.MIN_VALUE;
  32032. _this._orthoBottom = Number.MAX_VALUE;
  32033. _this.position = direction.scale(-1.0);
  32034. _this.direction = direction;
  32035. return _this;
  32036. }
  32037. DirectionalLight.prototype._buildUniformLayout = function () {
  32038. this._uniformBuffer.addUniform("vLightData", 4);
  32039. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  32040. this._uniformBuffer.addUniform("vLightSpecular", 3);
  32041. this._uniformBuffer.addUniform("shadowsInfo", 3);
  32042. this._uniformBuffer.create();
  32043. };
  32044. /**
  32045. * Returns the string "DirectionalLight".
  32046. */
  32047. DirectionalLight.prototype.getClassName = function () {
  32048. return "DirectionalLight";
  32049. };
  32050. /**
  32051. * Returns the DirectionalLight absolute position in the World.
  32052. */
  32053. DirectionalLight.prototype.getAbsolutePosition = function () {
  32054. return this.transformedPosition ? this.transformedPosition : this.position;
  32055. };
  32056. /**
  32057. * Sets the DirectionalLight direction toward the passed target (Vector3).
  32058. * Returns the updated DirectionalLight direction (Vector3).
  32059. */
  32060. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  32061. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  32062. return this.direction;
  32063. };
  32064. /**
  32065. * Return the depth scale used for the shadow map.
  32066. */
  32067. DirectionalLight.prototype.getDepthScale = function () {
  32068. return 30.0;
  32069. };
  32070. /**
  32071. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  32072. * Returns the DirectionalLight.
  32073. */
  32074. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  32075. if (this.customProjectionMatrixBuilder) {
  32076. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  32077. }
  32078. else {
  32079. var activeCamera = this.getScene().activeCamera;
  32080. // Check extends
  32081. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  32082. var tempVector3 = BABYLON.Vector3.Zero();
  32083. this._orthoLeft = Number.MAX_VALUE;
  32084. this._orthoRight = Number.MIN_VALUE;
  32085. this._orthoTop = Number.MIN_VALUE;
  32086. this._orthoBottom = Number.MAX_VALUE;
  32087. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  32088. var mesh = renderList[meshIndex];
  32089. if (!mesh) {
  32090. continue;
  32091. }
  32092. var boundingInfo = mesh.getBoundingInfo();
  32093. if (!boundingInfo) {
  32094. continue;
  32095. }
  32096. var boundingBox = boundingInfo.boundingBox;
  32097. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  32098. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  32099. if (tempVector3.x < this._orthoLeft)
  32100. this._orthoLeft = tempVector3.x;
  32101. if (tempVector3.y < this._orthoBottom)
  32102. this._orthoBottom = tempVector3.y;
  32103. if (tempVector3.x > this._orthoRight)
  32104. this._orthoRight = tempVector3.x;
  32105. if (tempVector3.y > this._orthoTop)
  32106. this._orthoTop = tempVector3.y;
  32107. }
  32108. }
  32109. }
  32110. var xOffset = this._orthoRight - this._orthoLeft;
  32111. var yOffset = this._orthoTop - this._orthoBottom;
  32112. 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);
  32113. }
  32114. return this;
  32115. };
  32116. /**
  32117. * Boolean : true by default.
  32118. */
  32119. DirectionalLight.prototype.needRefreshPerFrame = function () {
  32120. return true;
  32121. };
  32122. /**
  32123. * Boolean : false by default.
  32124. */
  32125. DirectionalLight.prototype.needCube = function () {
  32126. return false;
  32127. };
  32128. /**
  32129. * Returns the light direction (Vector3) for any passed face index.
  32130. */
  32131. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  32132. return this.direction;
  32133. };
  32134. /**
  32135. * Computes the light transformed position in case the light is parented. Returns true if parented, else false.
  32136. */
  32137. DirectionalLight.prototype.computeTransformedPosition = function () {
  32138. if (this.parent && this.parent.getWorldMatrix) {
  32139. if (!this.transformedPosition) {
  32140. this.transformedPosition = BABYLON.Vector3.Zero();
  32141. }
  32142. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  32143. return true;
  32144. }
  32145. return false;
  32146. };
  32147. /**
  32148. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  32149. * Returns the DirectionalLight.
  32150. */
  32151. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  32152. if (this.parent && this.parent.getWorldMatrix) {
  32153. if (!this._transformedDirection) {
  32154. this._transformedDirection = BABYLON.Vector3.Zero();
  32155. }
  32156. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  32157. this._uniformBuffer.updateFloat4("vLightData", this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1, lightIndex);
  32158. return this;
  32159. }
  32160. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  32161. return this;
  32162. };
  32163. DirectionalLight.prototype._getWorldMatrix = function () {
  32164. if (!this._worldMatrix) {
  32165. this._worldMatrix = BABYLON.Matrix.Identity();
  32166. }
  32167. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  32168. return this._worldMatrix;
  32169. };
  32170. /**
  32171. * Returns the integer 1.
  32172. */
  32173. DirectionalLight.prototype.getTypeID = function () {
  32174. return 1;
  32175. };
  32176. return DirectionalLight;
  32177. }(BABYLON.Light));
  32178. __decorate([
  32179. BABYLON.serializeAsVector3()
  32180. ], DirectionalLight.prototype, "position", void 0);
  32181. __decorate([
  32182. BABYLON.serializeAsVector3()
  32183. ], DirectionalLight.prototype, "direction", void 0);
  32184. __decorate([
  32185. BABYLON.serialize()
  32186. ], DirectionalLight.prototype, "shadowOrthoScale", void 0);
  32187. __decorate([
  32188. BABYLON.serialize()
  32189. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  32190. __decorate([
  32191. BABYLON.serialize()
  32192. ], DirectionalLight.prototype, "shadowMinZ", void 0);
  32193. __decorate([
  32194. BABYLON.serialize()
  32195. ], DirectionalLight.prototype, "shadowMaxZ", void 0);
  32196. BABYLON.DirectionalLight = DirectionalLight;
  32197. })(BABYLON || (BABYLON = {}));
  32198. //# sourceMappingURL=babylon.directionalLight.js.map
  32199. var BABYLON;
  32200. (function (BABYLON) {
  32201. var SpotLight = (function (_super) {
  32202. __extends(SpotLight, _super);
  32203. /**
  32204. * Creates a SpotLight object in the scene with the passed parameters :
  32205. * - `position` (Vector3) is the initial SpotLight position,
  32206. * - `direction` (Vector3) is the initial SpotLight direction,
  32207. * - `angle` (float, in radians) is the spot light cone angle,
  32208. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  32209. * A spot light is a simply light oriented cone.
  32210. * It can cast shadows.
  32211. * Documentation : http://doc.babylonjs.com/tutorials/lights
  32212. */
  32213. function SpotLight(name, position, direction, angle, exponent, scene) {
  32214. var _this = _super.call(this, name, scene) || this;
  32215. _this.position = position;
  32216. _this.direction = direction;
  32217. _this.angle = angle;
  32218. _this.exponent = exponent;
  32219. return _this;
  32220. }
  32221. SpotLight.prototype._buildUniformLayout = function () {
  32222. this._uniformBuffer.addUniform("vLightData", 4);
  32223. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  32224. this._uniformBuffer.addUniform("vLightSpecular", 3);
  32225. this._uniformBuffer.addUniform("vLightDirection", 3);
  32226. this._uniformBuffer.addUniform("shadowsInfo", 3);
  32227. this._uniformBuffer.create();
  32228. };
  32229. /**
  32230. * Returns the string "SpotLight".
  32231. */
  32232. SpotLight.prototype.getClassName = function () {
  32233. return "SpotLight";
  32234. };
  32235. /**
  32236. * Returns the SpotLight absolute position in the World (Vector3).
  32237. */
  32238. SpotLight.prototype.getAbsolutePosition = function () {
  32239. return this.transformedPosition ? this.transformedPosition : this.position;
  32240. };
  32241. /**
  32242. * Return the depth scale used for the shadow map.
  32243. */
  32244. SpotLight.prototype.getDepthScale = function () {
  32245. return 30.0;
  32246. };
  32247. /**
  32248. * 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.
  32249. * Returns the SpotLight.
  32250. */
  32251. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  32252. if (this.customProjectionMatrixBuilder) {
  32253. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  32254. }
  32255. else {
  32256. var activeCamera = this.getScene().activeCamera;
  32257. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  32258. }
  32259. return this;
  32260. };
  32261. /**
  32262. * Boolean : false by default.
  32263. */
  32264. SpotLight.prototype.needCube = function () {
  32265. return false;
  32266. };
  32267. /**
  32268. * Boolean : false by default.
  32269. */
  32270. SpotLight.prototype.needRefreshPerFrame = function () {
  32271. return false;
  32272. };
  32273. /**
  32274. * Returns the SpotLight direction (Vector3) for any passed face index.
  32275. */
  32276. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  32277. return this.direction;
  32278. };
  32279. /**
  32280. * Updates the SpotLight direction towards the passed target (Vector3).
  32281. * Returns the updated direction.
  32282. */
  32283. SpotLight.prototype.setDirectionToTarget = function (target) {
  32284. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  32285. return this.direction;
  32286. };
  32287. /**
  32288. * Computes the SpotLight transformed position if parented. Returns true if parented, else false.
  32289. */
  32290. SpotLight.prototype.computeTransformedPosition = function () {
  32291. if (this.parent && this.parent.getWorldMatrix) {
  32292. if (!this.transformedPosition) {
  32293. this.transformedPosition = BABYLON.Vector3.Zero();
  32294. }
  32295. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  32296. return true;
  32297. }
  32298. return false;
  32299. };
  32300. /**
  32301. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  32302. * Return the SpotLight.
  32303. */
  32304. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  32305. var normalizeDirection;
  32306. if (this.parent && this.parent.getWorldMatrix) {
  32307. if (!this._transformedDirection) {
  32308. this._transformedDirection = BABYLON.Vector3.Zero();
  32309. }
  32310. this.computeTransformedPosition();
  32311. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  32312. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  32313. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  32314. }
  32315. else {
  32316. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  32317. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  32318. }
  32319. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  32320. return this;
  32321. };
  32322. SpotLight.prototype._getWorldMatrix = function () {
  32323. if (!this._worldMatrix) {
  32324. this._worldMatrix = BABYLON.Matrix.Identity();
  32325. }
  32326. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  32327. return this._worldMatrix;
  32328. };
  32329. /**
  32330. * Returns the integer 2.
  32331. */
  32332. SpotLight.prototype.getTypeID = function () {
  32333. return 2;
  32334. };
  32335. /**
  32336. * Returns the SpotLight rotation (Vector3).
  32337. */
  32338. SpotLight.prototype.getRotation = function () {
  32339. this.direction.normalize();
  32340. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  32341. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  32342. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  32343. };
  32344. return SpotLight;
  32345. }(BABYLON.Light));
  32346. __decorate([
  32347. BABYLON.serializeAsVector3()
  32348. ], SpotLight.prototype, "position", void 0);
  32349. __decorate([
  32350. BABYLON.serializeAsVector3()
  32351. ], SpotLight.prototype, "direction", void 0);
  32352. __decorate([
  32353. BABYLON.serialize()
  32354. ], SpotLight.prototype, "angle", void 0);
  32355. __decorate([
  32356. BABYLON.serialize()
  32357. ], SpotLight.prototype, "exponent", void 0);
  32358. __decorate([
  32359. BABYLON.serialize()
  32360. ], SpotLight.prototype, "shadowMinZ", void 0);
  32361. __decorate([
  32362. BABYLON.serialize()
  32363. ], SpotLight.prototype, "shadowMaxZ", void 0);
  32364. BABYLON.SpotLight = SpotLight;
  32365. })(BABYLON || (BABYLON = {}));
  32366. //# sourceMappingURL=babylon.spotLight.js.map
  32367. var BABYLON;
  32368. (function (BABYLON) {
  32369. var AnimationRange = (function () {
  32370. function AnimationRange(name, from, to) {
  32371. this.name = name;
  32372. this.from = from;
  32373. this.to = to;
  32374. }
  32375. AnimationRange.prototype.clone = function () {
  32376. return new AnimationRange(this.name, this.from, this.to);
  32377. };
  32378. return AnimationRange;
  32379. }());
  32380. BABYLON.AnimationRange = AnimationRange;
  32381. /**
  32382. * Composed of a frame, and an action function
  32383. */
  32384. var AnimationEvent = (function () {
  32385. function AnimationEvent(frame, action, onlyOnce) {
  32386. this.frame = frame;
  32387. this.action = action;
  32388. this.onlyOnce = onlyOnce;
  32389. this.isDone = false;
  32390. }
  32391. return AnimationEvent;
  32392. }());
  32393. BABYLON.AnimationEvent = AnimationEvent;
  32394. var PathCursor = (function () {
  32395. function PathCursor(path) {
  32396. this.path = path;
  32397. this._onchange = new Array();
  32398. this.value = 0;
  32399. this.animations = new Array();
  32400. }
  32401. PathCursor.prototype.getPoint = function () {
  32402. var point = this.path.getPointAtLengthPosition(this.value);
  32403. return new BABYLON.Vector3(point.x, 0, point.y);
  32404. };
  32405. PathCursor.prototype.moveAhead = function (step) {
  32406. if (step === void 0) { step = 0.002; }
  32407. this.move(step);
  32408. return this;
  32409. };
  32410. PathCursor.prototype.moveBack = function (step) {
  32411. if (step === void 0) { step = 0.002; }
  32412. this.move(-step);
  32413. return this;
  32414. };
  32415. PathCursor.prototype.move = function (step) {
  32416. if (Math.abs(step) > 1) {
  32417. throw "step size should be less than 1.";
  32418. }
  32419. this.value += step;
  32420. this.ensureLimits();
  32421. this.raiseOnChange();
  32422. return this;
  32423. };
  32424. PathCursor.prototype.ensureLimits = function () {
  32425. while (this.value > 1) {
  32426. this.value -= 1;
  32427. }
  32428. while (this.value < 0) {
  32429. this.value += 1;
  32430. }
  32431. return this;
  32432. };
  32433. // used by animation engine
  32434. PathCursor.prototype.markAsDirty = function (propertyName) {
  32435. this.ensureLimits();
  32436. this.raiseOnChange();
  32437. return this;
  32438. };
  32439. PathCursor.prototype.raiseOnChange = function () {
  32440. var _this = this;
  32441. this._onchange.forEach(function (f) { return f(_this); });
  32442. return this;
  32443. };
  32444. PathCursor.prototype.onchange = function (f) {
  32445. this._onchange.push(f);
  32446. return this;
  32447. };
  32448. return PathCursor;
  32449. }());
  32450. BABYLON.PathCursor = PathCursor;
  32451. var Animation = (function () {
  32452. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  32453. this.name = name;
  32454. this.targetProperty = targetProperty;
  32455. this.framePerSecond = framePerSecond;
  32456. this.dataType = dataType;
  32457. this.loopMode = loopMode;
  32458. this.enableBlending = enableBlending;
  32459. this._offsetsCache = {};
  32460. this._highLimitsCache = {};
  32461. this._stopped = false;
  32462. this._blendingFactor = 0;
  32463. // The set of event that will be linked to this animation
  32464. this._events = new Array();
  32465. this.allowMatricesInterpolation = false;
  32466. this.blendingSpeed = 0.01;
  32467. this._ranges = {};
  32468. this.targetPropertyPath = targetProperty.split(".");
  32469. this.dataType = dataType;
  32470. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  32471. }
  32472. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  32473. var dataType = undefined;
  32474. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  32475. dataType = Animation.ANIMATIONTYPE_FLOAT;
  32476. }
  32477. else if (from instanceof BABYLON.Quaternion) {
  32478. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  32479. }
  32480. else if (from instanceof BABYLON.Vector3) {
  32481. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  32482. }
  32483. else if (from instanceof BABYLON.Vector2) {
  32484. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  32485. }
  32486. else if (from instanceof BABYLON.Color3) {
  32487. dataType = Animation.ANIMATIONTYPE_COLOR3;
  32488. }
  32489. else if (from instanceof BABYLON.Size) {
  32490. dataType = Animation.ANIMATIONTYPE_SIZE;
  32491. }
  32492. if (dataType == undefined) {
  32493. return null;
  32494. }
  32495. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  32496. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  32497. animation.setKeys(keys);
  32498. if (easingFunction !== undefined) {
  32499. animation.setEasingFunction(easingFunction);
  32500. }
  32501. return animation;
  32502. };
  32503. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  32504. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  32505. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  32506. };
  32507. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  32508. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  32509. node.animations.push(animation);
  32510. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  32511. };
  32512. // Methods
  32513. /**
  32514. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  32515. */
  32516. Animation.prototype.toString = function (fullDetails) {
  32517. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  32518. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  32519. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  32520. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  32521. if (fullDetails) {
  32522. ret += ", Ranges: {";
  32523. var first = true;
  32524. for (var name in this._ranges) {
  32525. if (first) {
  32526. ret += ", ";
  32527. first = false;
  32528. }
  32529. ret += name;
  32530. }
  32531. ret += "}";
  32532. }
  32533. return ret;
  32534. };
  32535. /**
  32536. * Add an event to this animation.
  32537. */
  32538. Animation.prototype.addEvent = function (event) {
  32539. this._events.push(event);
  32540. };
  32541. /**
  32542. * Remove all events found at the given frame
  32543. * @param frame
  32544. */
  32545. Animation.prototype.removeEvents = function (frame) {
  32546. for (var index = 0; index < this._events.length; index++) {
  32547. if (this._events[index].frame === frame) {
  32548. this._events.splice(index, 1);
  32549. index--;
  32550. }
  32551. }
  32552. };
  32553. Animation.prototype.createRange = function (name, from, to) {
  32554. // check name not already in use; could happen for bones after serialized
  32555. if (!this._ranges[name]) {
  32556. this._ranges[name] = new AnimationRange(name, from, to);
  32557. }
  32558. };
  32559. Animation.prototype.deleteRange = function (name, deleteFrames) {
  32560. if (deleteFrames === void 0) { deleteFrames = true; }
  32561. if (this._ranges[name]) {
  32562. if (deleteFrames) {
  32563. var from = this._ranges[name].from;
  32564. var to = this._ranges[name].to;
  32565. // this loop MUST go high to low for multiple splices to work
  32566. for (var key = this._keys.length - 1; key >= 0; key--) {
  32567. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  32568. this._keys.splice(key, 1);
  32569. }
  32570. }
  32571. }
  32572. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  32573. }
  32574. };
  32575. Animation.prototype.getRange = function (name) {
  32576. return this._ranges[name];
  32577. };
  32578. Animation.prototype.reset = function () {
  32579. this._offsetsCache = {};
  32580. this._highLimitsCache = {};
  32581. this.currentFrame = 0;
  32582. this._blendingFactor = 0;
  32583. this._originalBlendValue = null;
  32584. };
  32585. Animation.prototype.isStopped = function () {
  32586. return this._stopped;
  32587. };
  32588. Animation.prototype.getKeys = function () {
  32589. return this._keys;
  32590. };
  32591. Animation.prototype.getHighestFrame = function () {
  32592. var ret = 0;
  32593. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  32594. if (ret < this._keys[key].frame) {
  32595. ret = this._keys[key].frame;
  32596. }
  32597. }
  32598. return ret;
  32599. };
  32600. Animation.prototype.getEasingFunction = function () {
  32601. return this._easingFunction;
  32602. };
  32603. Animation.prototype.setEasingFunction = function (easingFunction) {
  32604. this._easingFunction = easingFunction;
  32605. };
  32606. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  32607. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  32608. };
  32609. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  32610. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  32611. };
  32612. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  32613. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  32614. };
  32615. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  32616. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  32617. };
  32618. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  32619. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  32620. };
  32621. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  32622. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  32623. };
  32624. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  32625. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  32626. };
  32627. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  32628. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  32629. };
  32630. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  32631. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  32632. };
  32633. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  32634. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  32635. };
  32636. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  32637. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  32638. };
  32639. Animation.prototype.clone = function () {
  32640. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  32641. clone.enableBlending = this.enableBlending;
  32642. clone.blendingSpeed = this.blendingSpeed;
  32643. if (this._keys) {
  32644. clone.setKeys(this._keys);
  32645. }
  32646. if (this._ranges) {
  32647. clone._ranges = {};
  32648. for (var name in this._ranges) {
  32649. clone._ranges[name] = this._ranges[name].clone();
  32650. }
  32651. }
  32652. return clone;
  32653. };
  32654. Animation.prototype.setKeys = function (values) {
  32655. this._keys = values.slice(0);
  32656. this._offsetsCache = {};
  32657. this._highLimitsCache = {};
  32658. };
  32659. Animation.prototype._getKeyValue = function (value) {
  32660. if (typeof value === "function") {
  32661. return value();
  32662. }
  32663. return value;
  32664. };
  32665. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  32666. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  32667. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  32668. }
  32669. this.currentFrame = currentFrame;
  32670. // Try to get a hash to find the right key
  32671. var startKeyIndex = Math.max(0, Math.min(this._keys.length - 1, Math.floor(this._keys.length * (currentFrame - this._keys[0].frame) / (this._keys[this._keys.length - 1].frame - this._keys[0].frame)) - 1));
  32672. if (this._keys[startKeyIndex].frame >= currentFrame) {
  32673. while (startKeyIndex - 1 >= 0 && this._keys[startKeyIndex].frame >= currentFrame) {
  32674. startKeyIndex--;
  32675. }
  32676. }
  32677. for (var key = startKeyIndex; key < this._keys.length; key++) {
  32678. var endKey = this._keys[key + 1];
  32679. if (endKey.frame >= currentFrame) {
  32680. var startKey = this._keys[key];
  32681. var startValue = this._getKeyValue(startKey.value);
  32682. var endValue = this._getKeyValue(endKey.value);
  32683. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  32684. var frameDelta = endKey.frame - startKey.frame;
  32685. // gradient : percent of currentFrame between the frame inf and the frame sup
  32686. var gradient = (currentFrame - startKey.frame) / frameDelta;
  32687. // check for easingFunction and correction of gradient
  32688. if (this._easingFunction != null) {
  32689. gradient = this._easingFunction.ease(gradient);
  32690. }
  32691. switch (this.dataType) {
  32692. // Float
  32693. case Animation.ANIMATIONTYPE_FLOAT:
  32694. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  32695. switch (loopMode) {
  32696. case Animation.ANIMATIONLOOPMODE_CYCLE:
  32697. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  32698. return floatValue;
  32699. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  32700. return offsetValue * repeatCount + floatValue;
  32701. }
  32702. break;
  32703. // Quaternion
  32704. case Animation.ANIMATIONTYPE_QUATERNION:
  32705. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  32706. switch (loopMode) {
  32707. case Animation.ANIMATIONLOOPMODE_CYCLE:
  32708. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  32709. return quatValue;
  32710. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  32711. return quatValue.add(offsetValue.scale(repeatCount));
  32712. }
  32713. return quatValue;
  32714. // Vector3
  32715. case Animation.ANIMATIONTYPE_VECTOR3:
  32716. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  32717. switch (loopMode) {
  32718. case Animation.ANIMATIONLOOPMODE_CYCLE:
  32719. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  32720. return vec3Value;
  32721. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  32722. return vec3Value.add(offsetValue.scale(repeatCount));
  32723. }
  32724. // Vector2
  32725. case Animation.ANIMATIONTYPE_VECTOR2:
  32726. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  32727. switch (loopMode) {
  32728. case Animation.ANIMATIONLOOPMODE_CYCLE:
  32729. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  32730. return vec2Value;
  32731. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  32732. return vec2Value.add(offsetValue.scale(repeatCount));
  32733. }
  32734. // Size
  32735. case Animation.ANIMATIONTYPE_SIZE:
  32736. switch (loopMode) {
  32737. case Animation.ANIMATIONLOOPMODE_CYCLE:
  32738. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  32739. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  32740. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  32741. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  32742. }
  32743. // Color3
  32744. case Animation.ANIMATIONTYPE_COLOR3:
  32745. switch (loopMode) {
  32746. case Animation.ANIMATIONLOOPMODE_CYCLE:
  32747. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  32748. return this.color3InterpolateFunction(startValue, endValue, gradient);
  32749. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  32750. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  32751. }
  32752. // Matrix
  32753. case Animation.ANIMATIONTYPE_MATRIX:
  32754. switch (loopMode) {
  32755. case Animation.ANIMATIONLOOPMODE_CYCLE:
  32756. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  32757. if (this.allowMatricesInterpolation) {
  32758. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  32759. }
  32760. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  32761. return startValue;
  32762. }
  32763. default:
  32764. break;
  32765. }
  32766. break;
  32767. }
  32768. }
  32769. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  32770. };
  32771. Animation.prototype.setValue = function (currentValue, blend) {
  32772. if (blend === void 0) { blend = false; }
  32773. // Set value
  32774. var path;
  32775. var destination;
  32776. if (this.targetPropertyPath.length > 1) {
  32777. var property = this._target[this.targetPropertyPath[0]];
  32778. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  32779. property = property[this.targetPropertyPath[index]];
  32780. }
  32781. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  32782. destination = property;
  32783. }
  32784. else {
  32785. path = this.targetPropertyPath[0];
  32786. destination = this._target;
  32787. }
  32788. // Blending
  32789. if (this.enableBlending && this._blendingFactor <= 1.0) {
  32790. if (!this._originalBlendValue) {
  32791. if (destination[path].clone) {
  32792. this._originalBlendValue = destination[path].clone();
  32793. }
  32794. else {
  32795. this._originalBlendValue = destination[path];
  32796. }
  32797. }
  32798. if (this._originalBlendValue.prototype) {
  32799. if (this._originalBlendValue.prototype.Lerp) {
  32800. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  32801. }
  32802. else {
  32803. destination[path] = currentValue;
  32804. }
  32805. }
  32806. else if (this._originalBlendValue.m) {
  32807. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  32808. }
  32809. else {
  32810. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  32811. }
  32812. this._blendingFactor += this.blendingSpeed;
  32813. }
  32814. else {
  32815. destination[path] = currentValue;
  32816. }
  32817. if (this._target.markAsDirty) {
  32818. this._target.markAsDirty(this.targetProperty);
  32819. }
  32820. };
  32821. Animation.prototype.goToFrame = function (frame) {
  32822. if (frame < this._keys[0].frame) {
  32823. frame = this._keys[0].frame;
  32824. }
  32825. else if (frame > this._keys[this._keys.length - 1].frame) {
  32826. frame = this._keys[this._keys.length - 1].frame;
  32827. }
  32828. var currentValue = this._interpolate(frame, 0, this.loopMode);
  32829. this.setValue(currentValue);
  32830. };
  32831. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  32832. if (blend === void 0) { blend = false; }
  32833. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  32834. this._stopped = true;
  32835. return false;
  32836. }
  32837. var returnValue = true;
  32838. // Adding a start key at frame 0 if missing
  32839. if (this._keys[0].frame !== 0) {
  32840. var newKey = { frame: 0, value: this._keys[0].value };
  32841. this._keys.splice(0, 0, newKey);
  32842. }
  32843. // Check limits
  32844. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  32845. from = this._keys[0].frame;
  32846. }
  32847. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  32848. to = this._keys[this._keys.length - 1].frame;
  32849. }
  32850. //to and from cannot be the same key
  32851. if (from === to) {
  32852. from++;
  32853. }
  32854. // Compute ratio
  32855. var range = to - from;
  32856. var offsetValue;
  32857. // ratio represents the frame delta between from and to
  32858. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  32859. var highLimitValue = 0;
  32860. if (ratio > range && !loop) {
  32861. returnValue = false;
  32862. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  32863. }
  32864. else {
  32865. // Get max value if required
  32866. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  32867. var keyOffset = to.toString() + from.toString();
  32868. if (!this._offsetsCache[keyOffset]) {
  32869. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  32870. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  32871. switch (this.dataType) {
  32872. // Float
  32873. case Animation.ANIMATIONTYPE_FLOAT:
  32874. this._offsetsCache[keyOffset] = toValue - fromValue;
  32875. break;
  32876. // Quaternion
  32877. case Animation.ANIMATIONTYPE_QUATERNION:
  32878. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  32879. break;
  32880. // Vector3
  32881. case Animation.ANIMATIONTYPE_VECTOR3:
  32882. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  32883. // Vector2
  32884. case Animation.ANIMATIONTYPE_VECTOR2:
  32885. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  32886. // Size
  32887. case Animation.ANIMATIONTYPE_SIZE:
  32888. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  32889. // Color3
  32890. case Animation.ANIMATIONTYPE_COLOR3:
  32891. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  32892. default:
  32893. break;
  32894. }
  32895. this._highLimitsCache[keyOffset] = toValue;
  32896. }
  32897. highLimitValue = this._highLimitsCache[keyOffset];
  32898. offsetValue = this._offsetsCache[keyOffset];
  32899. }
  32900. }
  32901. if (offsetValue === undefined) {
  32902. switch (this.dataType) {
  32903. // Float
  32904. case Animation.ANIMATIONTYPE_FLOAT:
  32905. offsetValue = 0;
  32906. break;
  32907. // Quaternion
  32908. case Animation.ANIMATIONTYPE_QUATERNION:
  32909. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  32910. break;
  32911. // Vector3
  32912. case Animation.ANIMATIONTYPE_VECTOR3:
  32913. offsetValue = BABYLON.Vector3.Zero();
  32914. break;
  32915. // Vector2
  32916. case Animation.ANIMATIONTYPE_VECTOR2:
  32917. offsetValue = BABYLON.Vector2.Zero();
  32918. break;
  32919. // Size
  32920. case Animation.ANIMATIONTYPE_SIZE:
  32921. offsetValue = BABYLON.Size.Zero();
  32922. break;
  32923. // Color3
  32924. case Animation.ANIMATIONTYPE_COLOR3:
  32925. offsetValue = BABYLON.Color3.Black();
  32926. }
  32927. }
  32928. // Compute value
  32929. var repeatCount = (ratio / range) >> 0;
  32930. var currentFrame = returnValue ? from + ratio % range : to;
  32931. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  32932. // Set value
  32933. this.setValue(currentValue);
  32934. // Check events
  32935. for (var index = 0; index < this._events.length; index++) {
  32936. if (currentFrame >= this._events[index].frame) {
  32937. var event = this._events[index];
  32938. if (!event.isDone) {
  32939. // If event should be done only once, remove it.
  32940. if (event.onlyOnce) {
  32941. this._events.splice(index, 1);
  32942. index--;
  32943. }
  32944. event.isDone = true;
  32945. event.action();
  32946. } // Don't do anything if the event has already be done.
  32947. }
  32948. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  32949. // reset event, the animation is looping
  32950. this._events[index].isDone = false;
  32951. }
  32952. }
  32953. if (!returnValue) {
  32954. this._stopped = true;
  32955. }
  32956. return returnValue;
  32957. };
  32958. Animation.prototype.serialize = function () {
  32959. var serializationObject = {};
  32960. serializationObject.name = this.name;
  32961. serializationObject.property = this.targetProperty;
  32962. serializationObject.framePerSecond = this.framePerSecond;
  32963. serializationObject.dataType = this.dataType;
  32964. serializationObject.loopBehavior = this.loopMode;
  32965. serializationObject.enableBlending = this.enableBlending;
  32966. serializationObject.blendingSpeed = this.blendingSpeed;
  32967. var dataType = this.dataType;
  32968. serializationObject.keys = [];
  32969. var keys = this.getKeys();
  32970. for (var index = 0; index < keys.length; index++) {
  32971. var animationKey = keys[index];
  32972. var key = {};
  32973. key.frame = animationKey.frame;
  32974. switch (dataType) {
  32975. case Animation.ANIMATIONTYPE_FLOAT:
  32976. key.values = [animationKey.value];
  32977. break;
  32978. case Animation.ANIMATIONTYPE_QUATERNION:
  32979. case Animation.ANIMATIONTYPE_MATRIX:
  32980. case Animation.ANIMATIONTYPE_VECTOR3:
  32981. case Animation.ANIMATIONTYPE_COLOR3:
  32982. key.values = animationKey.value.asArray();
  32983. break;
  32984. }
  32985. serializationObject.keys.push(key);
  32986. }
  32987. serializationObject.ranges = [];
  32988. for (var name in this._ranges) {
  32989. var range = {};
  32990. range.name = name;
  32991. range.from = this._ranges[name].from;
  32992. range.to = this._ranges[name].to;
  32993. serializationObject.ranges.push(range);
  32994. }
  32995. return serializationObject;
  32996. };
  32997. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  32998. get: function () {
  32999. return Animation._ANIMATIONTYPE_FLOAT;
  33000. },
  33001. enumerable: true,
  33002. configurable: true
  33003. });
  33004. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  33005. get: function () {
  33006. return Animation._ANIMATIONTYPE_VECTOR3;
  33007. },
  33008. enumerable: true,
  33009. configurable: true
  33010. });
  33011. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  33012. get: function () {
  33013. return Animation._ANIMATIONTYPE_VECTOR2;
  33014. },
  33015. enumerable: true,
  33016. configurable: true
  33017. });
  33018. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  33019. get: function () {
  33020. return Animation._ANIMATIONTYPE_SIZE;
  33021. },
  33022. enumerable: true,
  33023. configurable: true
  33024. });
  33025. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  33026. get: function () {
  33027. return Animation._ANIMATIONTYPE_QUATERNION;
  33028. },
  33029. enumerable: true,
  33030. configurable: true
  33031. });
  33032. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  33033. get: function () {
  33034. return Animation._ANIMATIONTYPE_MATRIX;
  33035. },
  33036. enumerable: true,
  33037. configurable: true
  33038. });
  33039. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  33040. get: function () {
  33041. return Animation._ANIMATIONTYPE_COLOR3;
  33042. },
  33043. enumerable: true,
  33044. configurable: true
  33045. });
  33046. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  33047. get: function () {
  33048. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  33049. },
  33050. enumerable: true,
  33051. configurable: true
  33052. });
  33053. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  33054. get: function () {
  33055. return Animation._ANIMATIONLOOPMODE_CYCLE;
  33056. },
  33057. enumerable: true,
  33058. configurable: true
  33059. });
  33060. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  33061. get: function () {
  33062. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  33063. },
  33064. enumerable: true,
  33065. configurable: true
  33066. });
  33067. Animation.Parse = function (parsedAnimation) {
  33068. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  33069. var dataType = parsedAnimation.dataType;
  33070. var keys = [];
  33071. var data;
  33072. var index;
  33073. if (parsedAnimation.enableBlending) {
  33074. animation.enableBlending = parsedAnimation.enableBlending;
  33075. }
  33076. if (parsedAnimation.blendingSpeed) {
  33077. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  33078. }
  33079. for (index = 0; index < parsedAnimation.keys.length; index++) {
  33080. var key = parsedAnimation.keys[index];
  33081. switch (dataType) {
  33082. case Animation.ANIMATIONTYPE_FLOAT:
  33083. data = key.values[0];
  33084. break;
  33085. case Animation.ANIMATIONTYPE_QUATERNION:
  33086. data = BABYLON.Quaternion.FromArray(key.values);
  33087. break;
  33088. case Animation.ANIMATIONTYPE_MATRIX:
  33089. data = BABYLON.Matrix.FromArray(key.values);
  33090. break;
  33091. case Animation.ANIMATIONTYPE_COLOR3:
  33092. data = BABYLON.Color3.FromArray(key.values);
  33093. break;
  33094. case Animation.ANIMATIONTYPE_VECTOR3:
  33095. default:
  33096. data = BABYLON.Vector3.FromArray(key.values);
  33097. break;
  33098. }
  33099. keys.push({
  33100. frame: key.frame,
  33101. value: data
  33102. });
  33103. }
  33104. animation.setKeys(keys);
  33105. if (parsedAnimation.ranges) {
  33106. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  33107. data = parsedAnimation.ranges[index];
  33108. animation.createRange(data.name, data.from, data.to);
  33109. }
  33110. }
  33111. return animation;
  33112. };
  33113. Animation.AppendSerializedAnimations = function (source, destination) {
  33114. if (source.animations) {
  33115. destination.animations = [];
  33116. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  33117. var animation = source.animations[animationIndex];
  33118. destination.animations.push(animation.serialize());
  33119. }
  33120. }
  33121. };
  33122. return Animation;
  33123. }());
  33124. // Statics
  33125. Animation._ANIMATIONTYPE_FLOAT = 0;
  33126. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  33127. Animation._ANIMATIONTYPE_QUATERNION = 2;
  33128. Animation._ANIMATIONTYPE_MATRIX = 3;
  33129. Animation._ANIMATIONTYPE_COLOR3 = 4;
  33130. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  33131. Animation._ANIMATIONTYPE_SIZE = 6;
  33132. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  33133. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  33134. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  33135. BABYLON.Animation = Animation;
  33136. })(BABYLON || (BABYLON = {}));
  33137. //# sourceMappingURL=babylon.animation.js.map
  33138. var BABYLON;
  33139. (function (BABYLON) {
  33140. var Animatable = (function () {
  33141. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  33142. if (fromFrame === void 0) { fromFrame = 0; }
  33143. if (toFrame === void 0) { toFrame = 100; }
  33144. if (loopAnimation === void 0) { loopAnimation = false; }
  33145. if (speedRatio === void 0) { speedRatio = 1.0; }
  33146. this.target = target;
  33147. this.fromFrame = fromFrame;
  33148. this.toFrame = toFrame;
  33149. this.loopAnimation = loopAnimation;
  33150. this.speedRatio = speedRatio;
  33151. this.onAnimationEnd = onAnimationEnd;
  33152. this._localDelayOffset = null;
  33153. this._pausedDelay = null;
  33154. this._animations = new Array();
  33155. this._paused = false;
  33156. this.animationStarted = false;
  33157. if (animations) {
  33158. this.appendAnimations(target, animations);
  33159. }
  33160. this._scene = scene;
  33161. scene._activeAnimatables.push(this);
  33162. }
  33163. // Methods
  33164. Animatable.prototype.getAnimations = function () {
  33165. return this._animations;
  33166. };
  33167. Animatable.prototype.appendAnimations = function (target, animations) {
  33168. for (var index = 0; index < animations.length; index++) {
  33169. var animation = animations[index];
  33170. animation._target = target;
  33171. this._animations.push(animation);
  33172. }
  33173. };
  33174. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  33175. var animations = this._animations;
  33176. for (var index = 0; index < animations.length; index++) {
  33177. if (animations[index].targetProperty === property) {
  33178. return animations[index];
  33179. }
  33180. }
  33181. return null;
  33182. };
  33183. Animatable.prototype.reset = function () {
  33184. var animations = this._animations;
  33185. for (var index = 0; index < animations.length; index++) {
  33186. animations[index].reset();
  33187. }
  33188. this._localDelayOffset = null;
  33189. this._pausedDelay = null;
  33190. };
  33191. Animatable.prototype.enableBlending = function (blendingSpeed) {
  33192. var animations = this._animations;
  33193. for (var index = 0; index < animations.length; index++) {
  33194. animations[index].enableBlending = true;
  33195. animations[index].blendingSpeed = blendingSpeed;
  33196. }
  33197. };
  33198. Animatable.prototype.disableBlending = function () {
  33199. var animations = this._animations;
  33200. for (var index = 0; index < animations.length; index++) {
  33201. animations[index].enableBlending = false;
  33202. }
  33203. };
  33204. Animatable.prototype.goToFrame = function (frame) {
  33205. var animations = this._animations;
  33206. if (animations[0]) {
  33207. var fps = animations[0].framePerSecond;
  33208. var currentFrame = animations[0].currentFrame;
  33209. var adjustTime = frame - currentFrame;
  33210. var delay = adjustTime * 1000 / fps;
  33211. this._localDelayOffset -= delay;
  33212. }
  33213. for (var index = 0; index < animations.length; index++) {
  33214. animations[index].goToFrame(frame);
  33215. }
  33216. };
  33217. Animatable.prototype.pause = function () {
  33218. if (this._paused) {
  33219. return;
  33220. }
  33221. this._paused = true;
  33222. };
  33223. Animatable.prototype.restart = function () {
  33224. this._paused = false;
  33225. };
  33226. Animatable.prototype.stop = function (animationName) {
  33227. if (animationName) {
  33228. var idx = this._scene._activeAnimatables.indexOf(this);
  33229. if (idx > -1) {
  33230. var animations = this._animations;
  33231. for (var index = animations.length - 1; index >= 0; index--) {
  33232. if (typeof animationName === "string" && animations[index].name != animationName) {
  33233. continue;
  33234. }
  33235. animations[index].reset();
  33236. animations.splice(index, 1);
  33237. }
  33238. if (animations.length == 0) {
  33239. this._scene._activeAnimatables.splice(idx, 1);
  33240. if (this.onAnimationEnd) {
  33241. this.onAnimationEnd();
  33242. }
  33243. }
  33244. }
  33245. }
  33246. else {
  33247. var index = this._scene._activeAnimatables.indexOf(this);
  33248. if (index > -1) {
  33249. this._scene._activeAnimatables.splice(index, 1);
  33250. var animations = this._animations;
  33251. for (var index = 0; index < animations.length; index++) {
  33252. animations[index].reset();
  33253. }
  33254. if (this.onAnimationEnd) {
  33255. this.onAnimationEnd();
  33256. }
  33257. }
  33258. }
  33259. };
  33260. Animatable.prototype._animate = function (delay) {
  33261. if (this._paused) {
  33262. this.animationStarted = false;
  33263. if (this._pausedDelay === null) {
  33264. this._pausedDelay = delay;
  33265. }
  33266. return true;
  33267. }
  33268. if (this._localDelayOffset === null) {
  33269. this._localDelayOffset = delay;
  33270. }
  33271. else if (this._pausedDelay !== null) {
  33272. this._localDelayOffset += delay - this._pausedDelay;
  33273. this._pausedDelay = null;
  33274. }
  33275. // Animating
  33276. var running = false;
  33277. var animations = this._animations;
  33278. var index;
  33279. for (index = 0; index < animations.length; index++) {
  33280. var animation = animations[index];
  33281. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  33282. running = running || isRunning;
  33283. }
  33284. this.animationStarted = running;
  33285. if (!running) {
  33286. // Remove from active animatables
  33287. index = this._scene._activeAnimatables.indexOf(this);
  33288. this._scene._activeAnimatables.splice(index, 1);
  33289. }
  33290. if (!running && this.onAnimationEnd) {
  33291. this.onAnimationEnd();
  33292. this.onAnimationEnd = null;
  33293. }
  33294. return running;
  33295. };
  33296. return Animatable;
  33297. }());
  33298. BABYLON.Animatable = Animatable;
  33299. })(BABYLON || (BABYLON = {}));
  33300. //# sourceMappingURL=babylon.animatable.js.map
  33301. var BABYLON;
  33302. (function (BABYLON) {
  33303. var EasingFunction = (function () {
  33304. function EasingFunction() {
  33305. // Properties
  33306. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  33307. }
  33308. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  33309. get: function () {
  33310. return EasingFunction._EASINGMODE_EASEIN;
  33311. },
  33312. enumerable: true,
  33313. configurable: true
  33314. });
  33315. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  33316. get: function () {
  33317. return EasingFunction._EASINGMODE_EASEOUT;
  33318. },
  33319. enumerable: true,
  33320. configurable: true
  33321. });
  33322. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  33323. get: function () {
  33324. return EasingFunction._EASINGMODE_EASEINOUT;
  33325. },
  33326. enumerable: true,
  33327. configurable: true
  33328. });
  33329. EasingFunction.prototype.setEasingMode = function (easingMode) {
  33330. var n = Math.min(Math.max(easingMode, 0), 2);
  33331. this._easingMode = n;
  33332. };
  33333. EasingFunction.prototype.getEasingMode = function () {
  33334. return this._easingMode;
  33335. };
  33336. EasingFunction.prototype.easeInCore = function (gradient) {
  33337. throw new Error('You must implement this method');
  33338. };
  33339. EasingFunction.prototype.ease = function (gradient) {
  33340. switch (this._easingMode) {
  33341. case EasingFunction.EASINGMODE_EASEIN:
  33342. return this.easeInCore(gradient);
  33343. case EasingFunction.EASINGMODE_EASEOUT:
  33344. return (1 - this.easeInCore(1 - gradient));
  33345. }
  33346. if (gradient >= 0.5) {
  33347. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  33348. }
  33349. return (this.easeInCore(gradient * 2) * 0.5);
  33350. };
  33351. return EasingFunction;
  33352. }());
  33353. //Statics
  33354. EasingFunction._EASINGMODE_EASEIN = 0;
  33355. EasingFunction._EASINGMODE_EASEOUT = 1;
  33356. EasingFunction._EASINGMODE_EASEINOUT = 2;
  33357. BABYLON.EasingFunction = EasingFunction;
  33358. var CircleEase = (function (_super) {
  33359. __extends(CircleEase, _super);
  33360. function CircleEase() {
  33361. return _super !== null && _super.apply(this, arguments) || this;
  33362. }
  33363. CircleEase.prototype.easeInCore = function (gradient) {
  33364. gradient = Math.max(0, Math.min(1, gradient));
  33365. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  33366. };
  33367. return CircleEase;
  33368. }(EasingFunction));
  33369. BABYLON.CircleEase = CircleEase;
  33370. var BackEase = (function (_super) {
  33371. __extends(BackEase, _super);
  33372. function BackEase(amplitude) {
  33373. if (amplitude === void 0) { amplitude = 1; }
  33374. var _this = _super.call(this) || this;
  33375. _this.amplitude = amplitude;
  33376. return _this;
  33377. }
  33378. BackEase.prototype.easeInCore = function (gradient) {
  33379. var num = Math.max(0, this.amplitude);
  33380. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  33381. };
  33382. return BackEase;
  33383. }(EasingFunction));
  33384. BABYLON.BackEase = BackEase;
  33385. var BounceEase = (function (_super) {
  33386. __extends(BounceEase, _super);
  33387. function BounceEase(bounces, bounciness) {
  33388. if (bounces === void 0) { bounces = 3; }
  33389. if (bounciness === void 0) { bounciness = 2; }
  33390. var _this = _super.call(this) || this;
  33391. _this.bounces = bounces;
  33392. _this.bounciness = bounciness;
  33393. return _this;
  33394. }
  33395. BounceEase.prototype.easeInCore = function (gradient) {
  33396. var y = Math.max(0.0, this.bounces);
  33397. var bounciness = this.bounciness;
  33398. if (bounciness <= 1.0) {
  33399. bounciness = 1.001;
  33400. }
  33401. var num9 = Math.pow(bounciness, y);
  33402. var num5 = 1.0 - bounciness;
  33403. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  33404. var num15 = gradient * num4;
  33405. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  33406. var num3 = Math.floor(num65);
  33407. var num13 = num3 + 1.0;
  33408. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  33409. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  33410. var num7 = (num8 + num12) * 0.5;
  33411. var num6 = gradient - num7;
  33412. var num2 = num7 - num8;
  33413. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  33414. };
  33415. return BounceEase;
  33416. }(EasingFunction));
  33417. BABYLON.BounceEase = BounceEase;
  33418. var CubicEase = (function (_super) {
  33419. __extends(CubicEase, _super);
  33420. function CubicEase() {
  33421. return _super !== null && _super.apply(this, arguments) || this;
  33422. }
  33423. CubicEase.prototype.easeInCore = function (gradient) {
  33424. return (gradient * gradient * gradient);
  33425. };
  33426. return CubicEase;
  33427. }(EasingFunction));
  33428. BABYLON.CubicEase = CubicEase;
  33429. var ElasticEase = (function (_super) {
  33430. __extends(ElasticEase, _super);
  33431. function ElasticEase(oscillations, springiness) {
  33432. if (oscillations === void 0) { oscillations = 3; }
  33433. if (springiness === void 0) { springiness = 3; }
  33434. var _this = _super.call(this) || this;
  33435. _this.oscillations = oscillations;
  33436. _this.springiness = springiness;
  33437. return _this;
  33438. }
  33439. ElasticEase.prototype.easeInCore = function (gradient) {
  33440. var num2;
  33441. var num3 = Math.max(0.0, this.oscillations);
  33442. var num = Math.max(0.0, this.springiness);
  33443. if (num == 0) {
  33444. num2 = gradient;
  33445. }
  33446. else {
  33447. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  33448. }
  33449. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  33450. };
  33451. return ElasticEase;
  33452. }(EasingFunction));
  33453. BABYLON.ElasticEase = ElasticEase;
  33454. var ExponentialEase = (function (_super) {
  33455. __extends(ExponentialEase, _super);
  33456. function ExponentialEase(exponent) {
  33457. if (exponent === void 0) { exponent = 2; }
  33458. var _this = _super.call(this) || this;
  33459. _this.exponent = exponent;
  33460. return _this;
  33461. }
  33462. ExponentialEase.prototype.easeInCore = function (gradient) {
  33463. if (this.exponent <= 0) {
  33464. return gradient;
  33465. }
  33466. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  33467. };
  33468. return ExponentialEase;
  33469. }(EasingFunction));
  33470. BABYLON.ExponentialEase = ExponentialEase;
  33471. var PowerEase = (function (_super) {
  33472. __extends(PowerEase, _super);
  33473. function PowerEase(power) {
  33474. if (power === void 0) { power = 2; }
  33475. var _this = _super.call(this) || this;
  33476. _this.power = power;
  33477. return _this;
  33478. }
  33479. PowerEase.prototype.easeInCore = function (gradient) {
  33480. var y = Math.max(0.0, this.power);
  33481. return Math.pow(gradient, y);
  33482. };
  33483. return PowerEase;
  33484. }(EasingFunction));
  33485. BABYLON.PowerEase = PowerEase;
  33486. var QuadraticEase = (function (_super) {
  33487. __extends(QuadraticEase, _super);
  33488. function QuadraticEase() {
  33489. return _super !== null && _super.apply(this, arguments) || this;
  33490. }
  33491. QuadraticEase.prototype.easeInCore = function (gradient) {
  33492. return (gradient * gradient);
  33493. };
  33494. return QuadraticEase;
  33495. }(EasingFunction));
  33496. BABYLON.QuadraticEase = QuadraticEase;
  33497. var QuarticEase = (function (_super) {
  33498. __extends(QuarticEase, _super);
  33499. function QuarticEase() {
  33500. return _super !== null && _super.apply(this, arguments) || this;
  33501. }
  33502. QuarticEase.prototype.easeInCore = function (gradient) {
  33503. return (gradient * gradient * gradient * gradient);
  33504. };
  33505. return QuarticEase;
  33506. }(EasingFunction));
  33507. BABYLON.QuarticEase = QuarticEase;
  33508. var QuinticEase = (function (_super) {
  33509. __extends(QuinticEase, _super);
  33510. function QuinticEase() {
  33511. return _super !== null && _super.apply(this, arguments) || this;
  33512. }
  33513. QuinticEase.prototype.easeInCore = function (gradient) {
  33514. return (gradient * gradient * gradient * gradient * gradient);
  33515. };
  33516. return QuinticEase;
  33517. }(EasingFunction));
  33518. BABYLON.QuinticEase = QuinticEase;
  33519. var SineEase = (function (_super) {
  33520. __extends(SineEase, _super);
  33521. function SineEase() {
  33522. return _super !== null && _super.apply(this, arguments) || this;
  33523. }
  33524. SineEase.prototype.easeInCore = function (gradient) {
  33525. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  33526. };
  33527. return SineEase;
  33528. }(EasingFunction));
  33529. BABYLON.SineEase = SineEase;
  33530. var BezierCurveEase = (function (_super) {
  33531. __extends(BezierCurveEase, _super);
  33532. function BezierCurveEase(x1, y1, x2, y2) {
  33533. if (x1 === void 0) { x1 = 0; }
  33534. if (y1 === void 0) { y1 = 0; }
  33535. if (x2 === void 0) { x2 = 1; }
  33536. if (y2 === void 0) { y2 = 1; }
  33537. var _this = _super.call(this) || this;
  33538. _this.x1 = x1;
  33539. _this.y1 = y1;
  33540. _this.x2 = x2;
  33541. _this.y2 = y2;
  33542. return _this;
  33543. }
  33544. BezierCurveEase.prototype.easeInCore = function (gradient) {
  33545. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  33546. };
  33547. return BezierCurveEase;
  33548. }(EasingFunction));
  33549. BABYLON.BezierCurveEase = BezierCurveEase;
  33550. })(BABYLON || (BABYLON = {}));
  33551. //# sourceMappingURL=babylon.easing.js.map
  33552. var BABYLON;
  33553. (function (BABYLON) {
  33554. var Condition = (function () {
  33555. function Condition(actionManager) {
  33556. this._actionManager = actionManager;
  33557. }
  33558. Condition.prototype.isValid = function () {
  33559. return true;
  33560. };
  33561. Condition.prototype._getProperty = function (propertyPath) {
  33562. return this._actionManager._getProperty(propertyPath);
  33563. };
  33564. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  33565. return this._actionManager._getEffectiveTarget(target, propertyPath);
  33566. };
  33567. Condition.prototype.serialize = function () {
  33568. };
  33569. Condition.prototype._serialize = function (serializedCondition) {
  33570. return {
  33571. type: 2,
  33572. children: [],
  33573. name: serializedCondition.name,
  33574. properties: serializedCondition.properties
  33575. };
  33576. };
  33577. return Condition;
  33578. }());
  33579. BABYLON.Condition = Condition;
  33580. var ValueCondition = (function (_super) {
  33581. __extends(ValueCondition, _super);
  33582. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  33583. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  33584. var _this = _super.call(this, actionManager) || this;
  33585. _this.propertyPath = propertyPath;
  33586. _this.value = value;
  33587. _this.operator = operator;
  33588. _this._target = target;
  33589. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  33590. _this._property = _this._getProperty(_this.propertyPath);
  33591. return _this;
  33592. }
  33593. Object.defineProperty(ValueCondition, "IsEqual", {
  33594. get: function () {
  33595. return ValueCondition._IsEqual;
  33596. },
  33597. enumerable: true,
  33598. configurable: true
  33599. });
  33600. Object.defineProperty(ValueCondition, "IsDifferent", {
  33601. get: function () {
  33602. return ValueCondition._IsDifferent;
  33603. },
  33604. enumerable: true,
  33605. configurable: true
  33606. });
  33607. Object.defineProperty(ValueCondition, "IsGreater", {
  33608. get: function () {
  33609. return ValueCondition._IsGreater;
  33610. },
  33611. enumerable: true,
  33612. configurable: true
  33613. });
  33614. Object.defineProperty(ValueCondition, "IsLesser", {
  33615. get: function () {
  33616. return ValueCondition._IsLesser;
  33617. },
  33618. enumerable: true,
  33619. configurable: true
  33620. });
  33621. // Methods
  33622. ValueCondition.prototype.isValid = function () {
  33623. switch (this.operator) {
  33624. case ValueCondition.IsGreater:
  33625. return this._effectiveTarget[this._property] > this.value;
  33626. case ValueCondition.IsLesser:
  33627. return this._effectiveTarget[this._property] < this.value;
  33628. case ValueCondition.IsEqual:
  33629. case ValueCondition.IsDifferent:
  33630. var check;
  33631. if (this.value.equals) {
  33632. check = this.value.equals(this._effectiveTarget[this._property]);
  33633. }
  33634. else {
  33635. check = this.value === this._effectiveTarget[this._property];
  33636. }
  33637. return this.operator === ValueCondition.IsEqual ? check : !check;
  33638. }
  33639. return false;
  33640. };
  33641. ValueCondition.prototype.serialize = function () {
  33642. return this._serialize({
  33643. name: "ValueCondition",
  33644. properties: [
  33645. BABYLON.Action._GetTargetProperty(this._target),
  33646. { name: "propertyPath", value: this.propertyPath },
  33647. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  33648. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  33649. ]
  33650. });
  33651. };
  33652. ValueCondition.GetOperatorName = function (operator) {
  33653. switch (operator) {
  33654. case ValueCondition._IsEqual: return "IsEqual";
  33655. case ValueCondition._IsDifferent: return "IsDifferent";
  33656. case ValueCondition._IsGreater: return "IsGreater";
  33657. case ValueCondition._IsLesser: return "IsLesser";
  33658. default: return "";
  33659. }
  33660. };
  33661. return ValueCondition;
  33662. }(Condition));
  33663. // Statics
  33664. ValueCondition._IsEqual = 0;
  33665. ValueCondition._IsDifferent = 1;
  33666. ValueCondition._IsGreater = 2;
  33667. ValueCondition._IsLesser = 3;
  33668. BABYLON.ValueCondition = ValueCondition;
  33669. var PredicateCondition = (function (_super) {
  33670. __extends(PredicateCondition, _super);
  33671. function PredicateCondition(actionManager, predicate) {
  33672. var _this = _super.call(this, actionManager) || this;
  33673. _this.predicate = predicate;
  33674. return _this;
  33675. }
  33676. PredicateCondition.prototype.isValid = function () {
  33677. return this.predicate();
  33678. };
  33679. return PredicateCondition;
  33680. }(Condition));
  33681. BABYLON.PredicateCondition = PredicateCondition;
  33682. var StateCondition = (function (_super) {
  33683. __extends(StateCondition, _super);
  33684. function StateCondition(actionManager, target, value) {
  33685. var _this = _super.call(this, actionManager) || this;
  33686. _this.value = value;
  33687. _this._target = target;
  33688. return _this;
  33689. }
  33690. // Methods
  33691. StateCondition.prototype.isValid = function () {
  33692. return this._target.state === this.value;
  33693. };
  33694. StateCondition.prototype.serialize = function () {
  33695. return this._serialize({
  33696. name: "StateCondition",
  33697. properties: [
  33698. BABYLON.Action._GetTargetProperty(this._target),
  33699. { name: "value", value: this.value }
  33700. ]
  33701. });
  33702. };
  33703. return StateCondition;
  33704. }(Condition));
  33705. BABYLON.StateCondition = StateCondition;
  33706. })(BABYLON || (BABYLON = {}));
  33707. //# sourceMappingURL=babylon.condition.js.map
  33708. var BABYLON;
  33709. (function (BABYLON) {
  33710. var Action = (function () {
  33711. function Action(triggerOptions, condition) {
  33712. this.triggerOptions = triggerOptions;
  33713. if (triggerOptions.parameter) {
  33714. this.trigger = triggerOptions.trigger;
  33715. this._triggerParameter = triggerOptions.parameter;
  33716. }
  33717. else {
  33718. this.trigger = triggerOptions;
  33719. }
  33720. this._nextActiveAction = this;
  33721. this._condition = condition;
  33722. }
  33723. // Methods
  33724. Action.prototype._prepare = function () {
  33725. };
  33726. Action.prototype.getTriggerParameter = function () {
  33727. return this._triggerParameter;
  33728. };
  33729. Action.prototype._executeCurrent = function (evt) {
  33730. if (this._nextActiveAction._condition) {
  33731. var condition = this._nextActiveAction._condition;
  33732. var currentRenderId = this._actionManager.getScene().getRenderId();
  33733. // We cache the current evaluation for the current frame
  33734. if (condition._evaluationId === currentRenderId) {
  33735. if (!condition._currentResult) {
  33736. return;
  33737. }
  33738. }
  33739. else {
  33740. condition._evaluationId = currentRenderId;
  33741. if (!condition.isValid()) {
  33742. condition._currentResult = false;
  33743. return;
  33744. }
  33745. condition._currentResult = true;
  33746. }
  33747. }
  33748. this._nextActiveAction.execute(evt);
  33749. this.skipToNextActiveAction();
  33750. };
  33751. Action.prototype.execute = function (evt) {
  33752. };
  33753. Action.prototype.skipToNextActiveAction = function () {
  33754. if (this._nextActiveAction._child) {
  33755. if (!this._nextActiveAction._child._actionManager) {
  33756. this._nextActiveAction._child._actionManager = this._actionManager;
  33757. }
  33758. this._nextActiveAction = this._nextActiveAction._child;
  33759. }
  33760. else {
  33761. this._nextActiveAction = this;
  33762. }
  33763. };
  33764. Action.prototype.then = function (action) {
  33765. this._child = action;
  33766. action._actionManager = this._actionManager;
  33767. action._prepare();
  33768. return action;
  33769. };
  33770. Action.prototype._getProperty = function (propertyPath) {
  33771. return this._actionManager._getProperty(propertyPath);
  33772. };
  33773. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  33774. return this._actionManager._getEffectiveTarget(target, propertyPath);
  33775. };
  33776. Action.prototype.serialize = function (parent) {
  33777. };
  33778. // Called by BABYLON.Action objects in serialize(...). Internal use
  33779. Action.prototype._serialize = function (serializedAction, parent) {
  33780. var serializationObject = {
  33781. type: 1,
  33782. children: [],
  33783. name: serializedAction.name,
  33784. properties: serializedAction.properties || []
  33785. };
  33786. // Serialize child
  33787. if (this._child) {
  33788. this._child.serialize(serializationObject);
  33789. }
  33790. // Check if "this" has a condition
  33791. if (this._condition) {
  33792. var serializedCondition = this._condition.serialize();
  33793. serializedCondition.children.push(serializationObject);
  33794. if (parent) {
  33795. parent.children.push(serializedCondition);
  33796. }
  33797. return serializedCondition;
  33798. }
  33799. if (parent) {
  33800. parent.children.push(serializationObject);
  33801. }
  33802. return serializationObject;
  33803. };
  33804. return Action;
  33805. }());
  33806. Action._SerializeValueAsString = function (value) {
  33807. if (typeof value === "number") {
  33808. return value.toString();
  33809. }
  33810. if (typeof value === "boolean") {
  33811. return value ? "true" : "false";
  33812. }
  33813. if (value instanceof BABYLON.Vector2) {
  33814. return value.x + ", " + value.y;
  33815. }
  33816. if (value instanceof BABYLON.Vector3) {
  33817. return value.x + ", " + value.y + ", " + value.z;
  33818. }
  33819. if (value instanceof BABYLON.Color3) {
  33820. return value.r + ", " + value.g + ", " + value.b;
  33821. }
  33822. if (value instanceof BABYLON.Color4) {
  33823. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  33824. }
  33825. return value; // string
  33826. };
  33827. Action._GetTargetProperty = function (target) {
  33828. return {
  33829. name: "target",
  33830. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  33831. : target instanceof BABYLON.Light ? "LightProperties"
  33832. : target instanceof BABYLON.Camera ? "CameraProperties"
  33833. : "SceneProperties",
  33834. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  33835. };
  33836. };
  33837. BABYLON.Action = Action;
  33838. })(BABYLON || (BABYLON = {}));
  33839. //# sourceMappingURL=babylon.action.js.map
  33840. var BABYLON;
  33841. (function (BABYLON) {
  33842. /**
  33843. * ActionEvent is the event beint sent when an action is triggered.
  33844. */
  33845. var ActionEvent = (function () {
  33846. /**
  33847. * @constructor
  33848. * @param source The mesh or sprite that triggered the action.
  33849. * @param pointerX The X mouse cursor position at the time of the event
  33850. * @param pointerY The Y mouse cursor position at the time of the event
  33851. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  33852. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  33853. */
  33854. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  33855. this.source = source;
  33856. this.pointerX = pointerX;
  33857. this.pointerY = pointerY;
  33858. this.meshUnderPointer = meshUnderPointer;
  33859. this.sourceEvent = sourceEvent;
  33860. this.additionalData = additionalData;
  33861. }
  33862. /**
  33863. * Helper function to auto-create an ActionEvent from a source mesh.
  33864. * @param source The source mesh that triggered the event
  33865. * @param evt {Event} The original (browser) event
  33866. */
  33867. ActionEvent.CreateNew = function (source, evt, additionalData) {
  33868. var scene = source.getScene();
  33869. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  33870. };
  33871. /**
  33872. * Helper function to auto-create an ActionEvent from a source mesh.
  33873. * @param source The source sprite that triggered the event
  33874. * @param scene Scene associated with the sprite
  33875. * @param evt {Event} The original (browser) event
  33876. */
  33877. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  33878. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  33879. };
  33880. /**
  33881. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  33882. * @param scene the scene where the event occurred
  33883. * @param evt {Event} The original (browser) event
  33884. */
  33885. ActionEvent.CreateNewFromScene = function (scene, evt) {
  33886. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  33887. };
  33888. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  33889. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  33890. };
  33891. return ActionEvent;
  33892. }());
  33893. BABYLON.ActionEvent = ActionEvent;
  33894. /**
  33895. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  33896. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  33897. */
  33898. var ActionManager = (function () {
  33899. function ActionManager(scene) {
  33900. // Members
  33901. this.actions = new Array();
  33902. this.hoverCursor = '';
  33903. this._scene = scene;
  33904. scene._actionManagers.push(this);
  33905. }
  33906. Object.defineProperty(ActionManager, "NothingTrigger", {
  33907. get: function () {
  33908. return ActionManager._NothingTrigger;
  33909. },
  33910. enumerable: true,
  33911. configurable: true
  33912. });
  33913. Object.defineProperty(ActionManager, "OnPickTrigger", {
  33914. get: function () {
  33915. return ActionManager._OnPickTrigger;
  33916. },
  33917. enumerable: true,
  33918. configurable: true
  33919. });
  33920. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  33921. get: function () {
  33922. return ActionManager._OnLeftPickTrigger;
  33923. },
  33924. enumerable: true,
  33925. configurable: true
  33926. });
  33927. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  33928. get: function () {
  33929. return ActionManager._OnRightPickTrigger;
  33930. },
  33931. enumerable: true,
  33932. configurable: true
  33933. });
  33934. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  33935. get: function () {
  33936. return ActionManager._OnCenterPickTrigger;
  33937. },
  33938. enumerable: true,
  33939. configurable: true
  33940. });
  33941. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  33942. get: function () {
  33943. return ActionManager._OnPickDownTrigger;
  33944. },
  33945. enumerable: true,
  33946. configurable: true
  33947. });
  33948. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  33949. get: function () {
  33950. return ActionManager._OnDoublePickTrigger;
  33951. },
  33952. enumerable: true,
  33953. configurable: true
  33954. });
  33955. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  33956. get: function () {
  33957. return ActionManager._OnPickUpTrigger;
  33958. },
  33959. enumerable: true,
  33960. configurable: true
  33961. });
  33962. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  33963. /// This trigger will only be raised if you also declared a OnPickDown
  33964. get: function () {
  33965. return ActionManager._OnPickOutTrigger;
  33966. },
  33967. enumerable: true,
  33968. configurable: true
  33969. });
  33970. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  33971. get: function () {
  33972. return ActionManager._OnLongPressTrigger;
  33973. },
  33974. enumerable: true,
  33975. configurable: true
  33976. });
  33977. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  33978. get: function () {
  33979. return ActionManager._OnPointerOverTrigger;
  33980. },
  33981. enumerable: true,
  33982. configurable: true
  33983. });
  33984. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  33985. get: function () {
  33986. return ActionManager._OnPointerOutTrigger;
  33987. },
  33988. enumerable: true,
  33989. configurable: true
  33990. });
  33991. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  33992. get: function () {
  33993. return ActionManager._OnEveryFrameTrigger;
  33994. },
  33995. enumerable: true,
  33996. configurable: true
  33997. });
  33998. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  33999. get: function () {
  34000. return ActionManager._OnIntersectionEnterTrigger;
  34001. },
  34002. enumerable: true,
  34003. configurable: true
  34004. });
  34005. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  34006. get: function () {
  34007. return ActionManager._OnIntersectionExitTrigger;
  34008. },
  34009. enumerable: true,
  34010. configurable: true
  34011. });
  34012. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  34013. get: function () {
  34014. return ActionManager._OnKeyDownTrigger;
  34015. },
  34016. enumerable: true,
  34017. configurable: true
  34018. });
  34019. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  34020. get: function () {
  34021. return ActionManager._OnKeyUpTrigger;
  34022. },
  34023. enumerable: true,
  34024. configurable: true
  34025. });
  34026. // Methods
  34027. ActionManager.prototype.dispose = function () {
  34028. var index = this._scene._actionManagers.indexOf(this);
  34029. for (var i = 0; i < this.actions.length; i++) {
  34030. var action = this.actions[i];
  34031. ActionManager.Triggers[action.trigger]--;
  34032. if (ActionManager.Triggers[action.trigger] === 0) {
  34033. delete ActionManager.Triggers[action.trigger];
  34034. }
  34035. }
  34036. if (index > -1) {
  34037. this._scene._actionManagers.splice(index, 1);
  34038. }
  34039. };
  34040. ActionManager.prototype.getScene = function () {
  34041. return this._scene;
  34042. };
  34043. /**
  34044. * Does this action manager handles actions of any of the given triggers
  34045. * @param {number[]} triggers - the triggers to be tested
  34046. * @return {boolean} whether one (or more) of the triggers is handeled
  34047. */
  34048. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  34049. for (var index = 0; index < this.actions.length; index++) {
  34050. var action = this.actions[index];
  34051. if (triggers.indexOf(action.trigger) > -1) {
  34052. return true;
  34053. }
  34054. }
  34055. return false;
  34056. };
  34057. /**
  34058. * Does this action manager handles actions of a given trigger
  34059. * @param {number} trigger - the trigger to be tested
  34060. * @return {boolean} whether the trigger is handeled
  34061. */
  34062. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  34063. for (var index = 0; index < this.actions.length; index++) {
  34064. var action = this.actions[index];
  34065. if (action.trigger === trigger) {
  34066. return true;
  34067. }
  34068. }
  34069. return false;
  34070. };
  34071. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  34072. /**
  34073. * Does this action manager has pointer triggers
  34074. * @return {boolean} whether or not it has pointer triggers
  34075. */
  34076. get: function () {
  34077. for (var index = 0; index < this.actions.length; index++) {
  34078. var action = this.actions[index];
  34079. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  34080. return true;
  34081. }
  34082. }
  34083. return false;
  34084. },
  34085. enumerable: true,
  34086. configurable: true
  34087. });
  34088. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  34089. /**
  34090. * Does this action manager has pick triggers
  34091. * @return {boolean} whether or not it has pick triggers
  34092. */
  34093. get: function () {
  34094. for (var index = 0; index < this.actions.length; index++) {
  34095. var action = this.actions[index];
  34096. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  34097. return true;
  34098. }
  34099. }
  34100. return false;
  34101. },
  34102. enumerable: true,
  34103. configurable: true
  34104. });
  34105. Object.defineProperty(ActionManager, "HasTriggers", {
  34106. /**
  34107. * Does exist one action manager with at least one trigger
  34108. * @return {boolean} whether or not it exists one action manager with one trigger
  34109. **/
  34110. get: function () {
  34111. for (var t in ActionManager.Triggers) {
  34112. if (ActionManager.Triggers.hasOwnProperty(t)) {
  34113. return true;
  34114. }
  34115. }
  34116. return false;
  34117. },
  34118. enumerable: true,
  34119. configurable: true
  34120. });
  34121. Object.defineProperty(ActionManager, "HasPickTriggers", {
  34122. /**
  34123. * Does exist one action manager with at least one pick trigger
  34124. * @return {boolean} whether or not it exists one action manager with one pick trigger
  34125. **/
  34126. get: function () {
  34127. for (var t in ActionManager.Triggers) {
  34128. if (ActionManager.Triggers.hasOwnProperty(t)) {
  34129. var t_int = parseInt(t);
  34130. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  34131. return true;
  34132. }
  34133. }
  34134. }
  34135. return false;
  34136. },
  34137. enumerable: true,
  34138. configurable: true
  34139. });
  34140. /**
  34141. * Does exist one action manager that handles actions of a given trigger
  34142. * @param {number} trigger - the trigger to be tested
  34143. * @return {boolean} whether the trigger is handeled by at least one action manager
  34144. **/
  34145. ActionManager.HasSpecificTrigger = function (trigger) {
  34146. for (var t in ActionManager.Triggers) {
  34147. if (ActionManager.Triggers.hasOwnProperty(t)) {
  34148. var t_int = parseInt(t);
  34149. if (t_int === trigger) {
  34150. return true;
  34151. }
  34152. }
  34153. }
  34154. return false;
  34155. };
  34156. /**
  34157. * Registers an action to this action manager
  34158. * @param {BABYLON.Action} action - the action to be registered
  34159. * @return {BABYLON.Action} the action amended (prepared) after registration
  34160. */
  34161. ActionManager.prototype.registerAction = function (action) {
  34162. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  34163. if (this.getScene().actionManager !== this) {
  34164. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  34165. return null;
  34166. }
  34167. }
  34168. this.actions.push(action);
  34169. if (ActionManager.Triggers[action.trigger]) {
  34170. ActionManager.Triggers[action.trigger]++;
  34171. }
  34172. else {
  34173. ActionManager.Triggers[action.trigger] = 1;
  34174. }
  34175. action._actionManager = this;
  34176. action._prepare();
  34177. return action;
  34178. };
  34179. /**
  34180. * Process a specific trigger
  34181. * @param {number} trigger - the trigger to process
  34182. * @param evt {BABYLON.ActionEvent} the event details to be processed
  34183. */
  34184. ActionManager.prototype.processTrigger = function (trigger, evt) {
  34185. for (var index = 0; index < this.actions.length; index++) {
  34186. var action = this.actions[index];
  34187. if (action.trigger === trigger) {
  34188. if (trigger === ActionManager.OnKeyUpTrigger
  34189. || trigger === ActionManager.OnKeyDownTrigger) {
  34190. var parameter = action.getTriggerParameter();
  34191. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  34192. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  34193. var actualkey = String.fromCharCode(unicode).toLowerCase();
  34194. if (actualkey !== parameter.toLowerCase()) {
  34195. continue;
  34196. }
  34197. }
  34198. }
  34199. action._executeCurrent(evt);
  34200. }
  34201. }
  34202. };
  34203. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  34204. var properties = propertyPath.split(".");
  34205. for (var index = 0; index < properties.length - 1; index++) {
  34206. target = target[properties[index]];
  34207. }
  34208. return target;
  34209. };
  34210. ActionManager.prototype._getProperty = function (propertyPath) {
  34211. var properties = propertyPath.split(".");
  34212. return properties[properties.length - 1];
  34213. };
  34214. ActionManager.prototype.serialize = function (name) {
  34215. var root = {
  34216. children: [],
  34217. name: name,
  34218. type: 3,
  34219. properties: [] // Empty for root but required
  34220. };
  34221. for (var i = 0; i < this.actions.length; i++) {
  34222. var triggerObject = {
  34223. type: 0,
  34224. children: [],
  34225. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  34226. properties: []
  34227. };
  34228. var triggerOptions = this.actions[i].triggerOptions;
  34229. if (triggerOptions && typeof triggerOptions !== "number") {
  34230. if (triggerOptions.parameter instanceof BABYLON.Node) {
  34231. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  34232. }
  34233. else {
  34234. var parameter = {};
  34235. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  34236. if (triggerOptions.parameter.mesh) {
  34237. parameter._meshId = triggerOptions.parameter.mesh.id;
  34238. }
  34239. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  34240. }
  34241. }
  34242. // Serialize child action, recursively
  34243. this.actions[i].serialize(triggerObject);
  34244. // Add serialized trigger
  34245. root.children.push(triggerObject);
  34246. }
  34247. return root;
  34248. };
  34249. ActionManager.Parse = function (parsedActions, object, scene) {
  34250. var actionManager = new BABYLON.ActionManager(scene);
  34251. if (object === null)
  34252. scene.actionManager = actionManager;
  34253. else
  34254. object.actionManager = actionManager;
  34255. // instanciate a new object
  34256. var instanciate = function (name, params) {
  34257. var newInstance = Object.create(BABYLON[name].prototype);
  34258. newInstance.constructor.apply(newInstance, params);
  34259. return newInstance;
  34260. };
  34261. var parseParameter = function (name, value, target, propertyPath) {
  34262. if (propertyPath === null) {
  34263. // String, boolean or float
  34264. var floatValue = parseFloat(value);
  34265. if (value === "true" || value === "false")
  34266. return value === "true";
  34267. else
  34268. return isNaN(floatValue) ? value : floatValue;
  34269. }
  34270. var effectiveTarget = propertyPath.split(".");
  34271. var values = value.split(",");
  34272. // Get effective Target
  34273. for (var i = 0; i < effectiveTarget.length; i++) {
  34274. target = target[effectiveTarget[i]];
  34275. }
  34276. // Return appropriate value with its type
  34277. if (typeof (target) === "boolean")
  34278. return values[0] === "true";
  34279. if (typeof (target) === "string")
  34280. return values[0];
  34281. // Parameters with multiple values such as Vector3 etc.
  34282. var split = new Array();
  34283. for (var i = 0; i < values.length; i++)
  34284. split.push(parseFloat(values[i]));
  34285. if (target instanceof BABYLON.Vector3)
  34286. return BABYLON.Vector3.FromArray(split);
  34287. if (target instanceof BABYLON.Vector4)
  34288. return BABYLON.Vector4.FromArray(split);
  34289. if (target instanceof BABYLON.Color3)
  34290. return BABYLON.Color3.FromArray(split);
  34291. if (target instanceof BABYLON.Color4)
  34292. return BABYLON.Color4.FromArray(split);
  34293. return parseFloat(values[0]);
  34294. };
  34295. // traverse graph per trigger
  34296. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  34297. if (combineArray === void 0) { combineArray = null; }
  34298. if (parsedAction.detached)
  34299. return;
  34300. var parameters = new Array();
  34301. var target = null;
  34302. var propertyPath = null;
  34303. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  34304. // Parameters
  34305. if (parsedAction.type === 2)
  34306. parameters.push(actionManager);
  34307. else
  34308. parameters.push(trigger);
  34309. if (combine) {
  34310. var actions = new Array();
  34311. for (var j = 0; j < parsedAction.combine.length; j++) {
  34312. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  34313. }
  34314. parameters.push(actions);
  34315. }
  34316. else {
  34317. for (var i = 0; i < parsedAction.properties.length; i++) {
  34318. var value = parsedAction.properties[i].value;
  34319. var name = parsedAction.properties[i].name;
  34320. var targetType = parsedAction.properties[i].targetType;
  34321. if (name === "target")
  34322. if (targetType !== null && targetType === "SceneProperties")
  34323. value = target = scene;
  34324. else
  34325. value = target = scene.getNodeByName(value);
  34326. else if (name === "parent")
  34327. value = scene.getNodeByName(value);
  34328. else if (name === "sound")
  34329. value = scene.getSoundByName(value);
  34330. else if (name !== "propertyPath") {
  34331. if (parsedAction.type === 2 && name === "operator")
  34332. value = BABYLON.ValueCondition[value];
  34333. else
  34334. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  34335. }
  34336. else {
  34337. propertyPath = value;
  34338. }
  34339. parameters.push(value);
  34340. }
  34341. }
  34342. if (combineArray === null) {
  34343. parameters.push(condition);
  34344. }
  34345. else {
  34346. parameters.push(null);
  34347. }
  34348. // If interpolate value action
  34349. if (parsedAction.name === "InterpolateValueAction") {
  34350. var param = parameters[parameters.length - 2];
  34351. parameters[parameters.length - 1] = param;
  34352. parameters[parameters.length - 2] = condition;
  34353. }
  34354. // Action or condition(s) and not CombineAction
  34355. var newAction = instanciate(parsedAction.name, parameters);
  34356. if (newAction instanceof BABYLON.Condition && condition !== null) {
  34357. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  34358. if (action)
  34359. action.then(nothing);
  34360. else
  34361. actionManager.registerAction(nothing);
  34362. action = nothing;
  34363. }
  34364. if (combineArray === null) {
  34365. if (newAction instanceof BABYLON.Condition) {
  34366. condition = newAction;
  34367. newAction = action;
  34368. }
  34369. else {
  34370. condition = null;
  34371. if (action)
  34372. action.then(newAction);
  34373. else
  34374. actionManager.registerAction(newAction);
  34375. }
  34376. }
  34377. else {
  34378. combineArray.push(newAction);
  34379. }
  34380. for (var i = 0; i < parsedAction.children.length; i++)
  34381. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  34382. };
  34383. // triggers
  34384. for (var i = 0; i < parsedActions.children.length; i++) {
  34385. var triggerParams;
  34386. var trigger = parsedActions.children[i];
  34387. if (trigger.properties.length > 0) {
  34388. var param = trigger.properties[0].value;
  34389. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  34390. if (value._meshId) {
  34391. value.mesh = scene.getMeshByID(value._meshId);
  34392. }
  34393. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  34394. }
  34395. else
  34396. triggerParams = BABYLON.ActionManager[trigger.name];
  34397. for (var j = 0; j < trigger.children.length; j++) {
  34398. if (!trigger.detached)
  34399. traverse(trigger.children[j], triggerParams, null, null);
  34400. }
  34401. }
  34402. };
  34403. ActionManager.GetTriggerName = function (trigger) {
  34404. switch (trigger) {
  34405. case 0: return "NothingTrigger";
  34406. case 1: return "OnPickTrigger";
  34407. case 2: return "OnLeftPickTrigger";
  34408. case 3: return "OnRightPickTrigger";
  34409. case 4: return "OnCenterPickTrigger";
  34410. case 5: return "OnPickDownTrigger";
  34411. case 6: return "OnPickUpTrigger";
  34412. case 7: return "OnLongPressTrigger";
  34413. case 8: return "OnPointerOverTrigger";
  34414. case 9: return "OnPointerOutTrigger";
  34415. case 10: return "OnEveryFrameTrigger";
  34416. case 11: return "OnIntersectionEnterTrigger";
  34417. case 12: return "OnIntersectionExitTrigger";
  34418. case 13: return "OnKeyDownTrigger";
  34419. case 14: return "OnKeyUpTrigger";
  34420. case 15: return "OnPickOutTrigger";
  34421. default: return "";
  34422. }
  34423. };
  34424. return ActionManager;
  34425. }());
  34426. // Statics
  34427. ActionManager._NothingTrigger = 0;
  34428. ActionManager._OnPickTrigger = 1;
  34429. ActionManager._OnLeftPickTrigger = 2;
  34430. ActionManager._OnRightPickTrigger = 3;
  34431. ActionManager._OnCenterPickTrigger = 4;
  34432. ActionManager._OnPickDownTrigger = 5;
  34433. ActionManager._OnDoublePickTrigger = 6;
  34434. ActionManager._OnPickUpTrigger = 7;
  34435. ActionManager._OnLongPressTrigger = 8;
  34436. ActionManager._OnPointerOverTrigger = 9;
  34437. ActionManager._OnPointerOutTrigger = 10;
  34438. ActionManager._OnEveryFrameTrigger = 11;
  34439. ActionManager._OnIntersectionEnterTrigger = 12;
  34440. ActionManager._OnIntersectionExitTrigger = 13;
  34441. ActionManager._OnKeyDownTrigger = 14;
  34442. ActionManager._OnKeyUpTrigger = 15;
  34443. ActionManager._OnPickOutTrigger = 16;
  34444. ActionManager.Triggers = {};
  34445. BABYLON.ActionManager = ActionManager;
  34446. })(BABYLON || (BABYLON = {}));
  34447. //# sourceMappingURL=babylon.actionManager.js.map
  34448. var BABYLON;
  34449. (function (BABYLON) {
  34450. var InterpolateValueAction = (function (_super) {
  34451. __extends(InterpolateValueAction, _super);
  34452. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  34453. if (duration === void 0) { duration = 1000; }
  34454. var _this = _super.call(this, triggerOptions, condition) || this;
  34455. _this.propertyPath = propertyPath;
  34456. _this.value = value;
  34457. _this.duration = duration;
  34458. _this.stopOtherAnimations = stopOtherAnimations;
  34459. _this.onInterpolationDone = onInterpolationDone;
  34460. _this._target = _this._effectiveTarget = target;
  34461. return _this;
  34462. }
  34463. InterpolateValueAction.prototype._prepare = function () {
  34464. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  34465. this._property = this._getProperty(this.propertyPath);
  34466. };
  34467. InterpolateValueAction.prototype.execute = function () {
  34468. var scene = this._actionManager.getScene();
  34469. var keys = [
  34470. {
  34471. frame: 0,
  34472. value: this._effectiveTarget[this._property]
  34473. }, {
  34474. frame: 100,
  34475. value: this.value
  34476. }
  34477. ];
  34478. var dataType;
  34479. if (typeof this.value === "number") {
  34480. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  34481. }
  34482. else if (this.value instanceof BABYLON.Color3) {
  34483. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  34484. }
  34485. else if (this.value instanceof BABYLON.Vector3) {
  34486. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  34487. }
  34488. else if (this.value instanceof BABYLON.Matrix) {
  34489. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  34490. }
  34491. else if (this.value instanceof BABYLON.Quaternion) {
  34492. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  34493. }
  34494. else {
  34495. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  34496. return;
  34497. }
  34498. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  34499. animation.setKeys(keys);
  34500. if (this.stopOtherAnimations) {
  34501. scene.stopAnimation(this._effectiveTarget);
  34502. }
  34503. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
  34504. };
  34505. InterpolateValueAction.prototype.serialize = function (parent) {
  34506. return _super.prototype._serialize.call(this, {
  34507. name: "InterpolateValueAction",
  34508. properties: [
  34509. BABYLON.Action._GetTargetProperty(this._target),
  34510. { name: "propertyPath", value: this.propertyPath },
  34511. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  34512. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  34513. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  34514. ]
  34515. }, parent);
  34516. };
  34517. return InterpolateValueAction;
  34518. }(BABYLON.Action));
  34519. BABYLON.InterpolateValueAction = InterpolateValueAction;
  34520. })(BABYLON || (BABYLON = {}));
  34521. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  34522. var BABYLON;
  34523. (function (BABYLON) {
  34524. var SwitchBooleanAction = (function (_super) {
  34525. __extends(SwitchBooleanAction, _super);
  34526. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  34527. var _this = _super.call(this, triggerOptions, condition) || this;
  34528. _this.propertyPath = propertyPath;
  34529. _this._target = _this._effectiveTarget = target;
  34530. return _this;
  34531. }
  34532. SwitchBooleanAction.prototype._prepare = function () {
  34533. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  34534. this._property = this._getProperty(this.propertyPath);
  34535. };
  34536. SwitchBooleanAction.prototype.execute = function () {
  34537. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  34538. };
  34539. SwitchBooleanAction.prototype.serialize = function (parent) {
  34540. return _super.prototype._serialize.call(this, {
  34541. name: "SwitchBooleanAction",
  34542. properties: [
  34543. BABYLON.Action._GetTargetProperty(this._target),
  34544. { name: "propertyPath", value: this.propertyPath }
  34545. ]
  34546. }, parent);
  34547. };
  34548. return SwitchBooleanAction;
  34549. }(BABYLON.Action));
  34550. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  34551. var SetStateAction = (function (_super) {
  34552. __extends(SetStateAction, _super);
  34553. function SetStateAction(triggerOptions, target, value, condition) {
  34554. var _this = _super.call(this, triggerOptions, condition) || this;
  34555. _this.value = value;
  34556. _this._target = target;
  34557. return _this;
  34558. }
  34559. SetStateAction.prototype.execute = function () {
  34560. this._target.state = this.value;
  34561. };
  34562. SetStateAction.prototype.serialize = function (parent) {
  34563. return _super.prototype._serialize.call(this, {
  34564. name: "SetStateAction",
  34565. properties: [
  34566. BABYLON.Action._GetTargetProperty(this._target),
  34567. { name: "value", value: this.value }
  34568. ]
  34569. }, parent);
  34570. };
  34571. return SetStateAction;
  34572. }(BABYLON.Action));
  34573. BABYLON.SetStateAction = SetStateAction;
  34574. var SetValueAction = (function (_super) {
  34575. __extends(SetValueAction, _super);
  34576. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  34577. var _this = _super.call(this, triggerOptions, condition) || this;
  34578. _this.propertyPath = propertyPath;
  34579. _this.value = value;
  34580. _this._target = _this._effectiveTarget = target;
  34581. return _this;
  34582. }
  34583. SetValueAction.prototype._prepare = function () {
  34584. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  34585. this._property = this._getProperty(this.propertyPath);
  34586. };
  34587. SetValueAction.prototype.execute = function () {
  34588. this._effectiveTarget[this._property] = this.value;
  34589. if (this._target.markAsDirty) {
  34590. this._target.markAsDirty(this._property);
  34591. }
  34592. };
  34593. SetValueAction.prototype.serialize = function (parent) {
  34594. return _super.prototype._serialize.call(this, {
  34595. name: "SetValueAction",
  34596. properties: [
  34597. BABYLON.Action._GetTargetProperty(this._target),
  34598. { name: "propertyPath", value: this.propertyPath },
  34599. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  34600. ]
  34601. }, parent);
  34602. };
  34603. return SetValueAction;
  34604. }(BABYLON.Action));
  34605. BABYLON.SetValueAction = SetValueAction;
  34606. var IncrementValueAction = (function (_super) {
  34607. __extends(IncrementValueAction, _super);
  34608. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  34609. var _this = _super.call(this, triggerOptions, condition) || this;
  34610. _this.propertyPath = propertyPath;
  34611. _this.value = value;
  34612. _this._target = _this._effectiveTarget = target;
  34613. return _this;
  34614. }
  34615. IncrementValueAction.prototype._prepare = function () {
  34616. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  34617. this._property = this._getProperty(this.propertyPath);
  34618. if (typeof this._effectiveTarget[this._property] !== "number") {
  34619. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  34620. }
  34621. };
  34622. IncrementValueAction.prototype.execute = function () {
  34623. this._effectiveTarget[this._property] += this.value;
  34624. if (this._target.markAsDirty) {
  34625. this._target.markAsDirty(this._property);
  34626. }
  34627. };
  34628. IncrementValueAction.prototype.serialize = function (parent) {
  34629. return _super.prototype._serialize.call(this, {
  34630. name: "IncrementValueAction",
  34631. properties: [
  34632. BABYLON.Action._GetTargetProperty(this._target),
  34633. { name: "propertyPath", value: this.propertyPath },
  34634. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  34635. ]
  34636. }, parent);
  34637. };
  34638. return IncrementValueAction;
  34639. }(BABYLON.Action));
  34640. BABYLON.IncrementValueAction = IncrementValueAction;
  34641. var PlayAnimationAction = (function (_super) {
  34642. __extends(PlayAnimationAction, _super);
  34643. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  34644. var _this = _super.call(this, triggerOptions, condition) || this;
  34645. _this.from = from;
  34646. _this.to = to;
  34647. _this.loop = loop;
  34648. _this._target = target;
  34649. return _this;
  34650. }
  34651. PlayAnimationAction.prototype._prepare = function () {
  34652. };
  34653. PlayAnimationAction.prototype.execute = function () {
  34654. var scene = this._actionManager.getScene();
  34655. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  34656. };
  34657. PlayAnimationAction.prototype.serialize = function (parent) {
  34658. return _super.prototype._serialize.call(this, {
  34659. name: "PlayAnimationAction",
  34660. properties: [
  34661. BABYLON.Action._GetTargetProperty(this._target),
  34662. { name: "from", value: String(this.from) },
  34663. { name: "to", value: String(this.to) },
  34664. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  34665. ]
  34666. }, parent);
  34667. };
  34668. return PlayAnimationAction;
  34669. }(BABYLON.Action));
  34670. BABYLON.PlayAnimationAction = PlayAnimationAction;
  34671. var StopAnimationAction = (function (_super) {
  34672. __extends(StopAnimationAction, _super);
  34673. function StopAnimationAction(triggerOptions, target, condition) {
  34674. var _this = _super.call(this, triggerOptions, condition) || this;
  34675. _this._target = target;
  34676. return _this;
  34677. }
  34678. StopAnimationAction.prototype._prepare = function () {
  34679. };
  34680. StopAnimationAction.prototype.execute = function () {
  34681. var scene = this._actionManager.getScene();
  34682. scene.stopAnimation(this._target);
  34683. };
  34684. StopAnimationAction.prototype.serialize = function (parent) {
  34685. return _super.prototype._serialize.call(this, {
  34686. name: "StopAnimationAction",
  34687. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  34688. }, parent);
  34689. };
  34690. return StopAnimationAction;
  34691. }(BABYLON.Action));
  34692. BABYLON.StopAnimationAction = StopAnimationAction;
  34693. var DoNothingAction = (function (_super) {
  34694. __extends(DoNothingAction, _super);
  34695. function DoNothingAction(triggerOptions, condition) {
  34696. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  34697. return _super.call(this, triggerOptions, condition) || this;
  34698. }
  34699. DoNothingAction.prototype.execute = function () {
  34700. };
  34701. DoNothingAction.prototype.serialize = function (parent) {
  34702. return _super.prototype._serialize.call(this, {
  34703. name: "DoNothingAction",
  34704. properties: []
  34705. }, parent);
  34706. };
  34707. return DoNothingAction;
  34708. }(BABYLON.Action));
  34709. BABYLON.DoNothingAction = DoNothingAction;
  34710. var CombineAction = (function (_super) {
  34711. __extends(CombineAction, _super);
  34712. function CombineAction(triggerOptions, children, condition) {
  34713. var _this = _super.call(this, triggerOptions, condition) || this;
  34714. _this.children = children;
  34715. return _this;
  34716. }
  34717. CombineAction.prototype._prepare = function () {
  34718. for (var index = 0; index < this.children.length; index++) {
  34719. this.children[index]._actionManager = this._actionManager;
  34720. this.children[index]._prepare();
  34721. }
  34722. };
  34723. CombineAction.prototype.execute = function (evt) {
  34724. for (var index = 0; index < this.children.length; index++) {
  34725. this.children[index].execute(evt);
  34726. }
  34727. };
  34728. CombineAction.prototype.serialize = function (parent) {
  34729. var serializationObject = _super.prototype._serialize.call(this, {
  34730. name: "CombineAction",
  34731. properties: [],
  34732. combine: []
  34733. }, parent);
  34734. for (var i = 0; i < this.children.length; i++) {
  34735. serializationObject.combine.push(this.children[i].serialize(null));
  34736. }
  34737. return serializationObject;
  34738. };
  34739. return CombineAction;
  34740. }(BABYLON.Action));
  34741. BABYLON.CombineAction = CombineAction;
  34742. var ExecuteCodeAction = (function (_super) {
  34743. __extends(ExecuteCodeAction, _super);
  34744. function ExecuteCodeAction(triggerOptions, func, condition) {
  34745. var _this = _super.call(this, triggerOptions, condition) || this;
  34746. _this.func = func;
  34747. return _this;
  34748. }
  34749. ExecuteCodeAction.prototype.execute = function (evt) {
  34750. this.func(evt);
  34751. };
  34752. return ExecuteCodeAction;
  34753. }(BABYLON.Action));
  34754. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  34755. var SetParentAction = (function (_super) {
  34756. __extends(SetParentAction, _super);
  34757. function SetParentAction(triggerOptions, target, parent, condition) {
  34758. var _this = _super.call(this, triggerOptions, condition) || this;
  34759. _this._target = target;
  34760. _this._parent = parent;
  34761. return _this;
  34762. }
  34763. SetParentAction.prototype._prepare = function () {
  34764. };
  34765. SetParentAction.prototype.execute = function () {
  34766. if (this._target.parent === this._parent) {
  34767. return;
  34768. }
  34769. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  34770. invertParentWorldMatrix.invert();
  34771. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  34772. this._target.parent = this._parent;
  34773. };
  34774. SetParentAction.prototype.serialize = function (parent) {
  34775. return _super.prototype._serialize.call(this, {
  34776. name: "SetParentAction",
  34777. properties: [
  34778. BABYLON.Action._GetTargetProperty(this._target),
  34779. BABYLON.Action._GetTargetProperty(this._parent),
  34780. ]
  34781. }, parent);
  34782. };
  34783. return SetParentAction;
  34784. }(BABYLON.Action));
  34785. BABYLON.SetParentAction = SetParentAction;
  34786. var PlaySoundAction = (function (_super) {
  34787. __extends(PlaySoundAction, _super);
  34788. function PlaySoundAction(triggerOptions, sound, condition) {
  34789. var _this = _super.call(this, triggerOptions, condition) || this;
  34790. _this._sound = sound;
  34791. return _this;
  34792. }
  34793. PlaySoundAction.prototype._prepare = function () {
  34794. };
  34795. PlaySoundAction.prototype.execute = function () {
  34796. if (this._sound !== undefined)
  34797. this._sound.play();
  34798. };
  34799. PlaySoundAction.prototype.serialize = function (parent) {
  34800. return _super.prototype._serialize.call(this, {
  34801. name: "PlaySoundAction",
  34802. properties: [{ name: "sound", value: this._sound.name }]
  34803. }, parent);
  34804. };
  34805. return PlaySoundAction;
  34806. }(BABYLON.Action));
  34807. BABYLON.PlaySoundAction = PlaySoundAction;
  34808. var StopSoundAction = (function (_super) {
  34809. __extends(StopSoundAction, _super);
  34810. function StopSoundAction(triggerOptions, sound, condition) {
  34811. var _this = _super.call(this, triggerOptions, condition) || this;
  34812. _this._sound = sound;
  34813. return _this;
  34814. }
  34815. StopSoundAction.prototype._prepare = function () {
  34816. };
  34817. StopSoundAction.prototype.execute = function () {
  34818. if (this._sound !== undefined)
  34819. this._sound.stop();
  34820. };
  34821. StopSoundAction.prototype.serialize = function (parent) {
  34822. return _super.prototype._serialize.call(this, {
  34823. name: "StopSoundAction",
  34824. properties: [{ name: "sound", value: this._sound.name }]
  34825. }, parent);
  34826. };
  34827. return StopSoundAction;
  34828. }(BABYLON.Action));
  34829. BABYLON.StopSoundAction = StopSoundAction;
  34830. })(BABYLON || (BABYLON = {}));
  34831. //# sourceMappingURL=babylon.directActions.js.map
  34832. var BABYLON;
  34833. (function (BABYLON) {
  34834. var SpriteManager = (function () {
  34835. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  34836. if (epsilon === void 0) { epsilon = 0.01; }
  34837. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  34838. this.name = name;
  34839. this.sprites = new Array();
  34840. this.renderingGroupId = 0;
  34841. this.layerMask = 0x0FFFFFFF;
  34842. this.fogEnabled = true;
  34843. this.isPickable = false;
  34844. /**
  34845. * An event triggered when the manager is disposed.
  34846. * @type {BABYLON.Observable}
  34847. */
  34848. this.onDisposeObservable = new BABYLON.Observable();
  34849. this._vertexBuffers = {};
  34850. this._capacity = capacity;
  34851. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  34852. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34853. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34854. if (cellSize.width && cellSize.height) {
  34855. this.cellWidth = cellSize.width;
  34856. this.cellHeight = cellSize.height;
  34857. }
  34858. else if (cellSize !== undefined) {
  34859. this.cellWidth = cellSize;
  34860. this.cellHeight = cellSize;
  34861. }
  34862. else {
  34863. return;
  34864. }
  34865. this._epsilon = epsilon;
  34866. this._scene = scene;
  34867. this._scene.spriteManagers.push(this);
  34868. var indices = [];
  34869. var index = 0;
  34870. for (var count = 0; count < capacity; count++) {
  34871. indices.push(index);
  34872. indices.push(index + 1);
  34873. indices.push(index + 2);
  34874. indices.push(index);
  34875. indices.push(index + 2);
  34876. indices.push(index + 3);
  34877. index += 4;
  34878. }
  34879. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  34880. // VBO
  34881. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  34882. this._vertexData = new Float32Array(capacity * 16 * 4);
  34883. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  34884. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  34885. var options = this._buffer.createVertexBuffer("options", 4, 4);
  34886. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  34887. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  34888. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  34889. this._vertexBuffers["options"] = options;
  34890. this._vertexBuffers["cellInfo"] = cellInfo;
  34891. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  34892. // Effects
  34893. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  34894. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  34895. }
  34896. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  34897. set: function (callback) {
  34898. if (this._onDisposeObserver) {
  34899. this.onDisposeObservable.remove(this._onDisposeObserver);
  34900. }
  34901. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  34902. },
  34903. enumerable: true,
  34904. configurable: true
  34905. });
  34906. Object.defineProperty(SpriteManager.prototype, "texture", {
  34907. get: function () {
  34908. return this._spriteTexture;
  34909. },
  34910. set: function (value) {
  34911. this._spriteTexture = value;
  34912. },
  34913. enumerable: true,
  34914. configurable: true
  34915. });
  34916. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  34917. var arrayOffset = index * 16;
  34918. if (offsetX === 0)
  34919. offsetX = this._epsilon;
  34920. else if (offsetX === 1)
  34921. offsetX = 1 - this._epsilon;
  34922. if (offsetY === 0)
  34923. offsetY = this._epsilon;
  34924. else if (offsetY === 1)
  34925. offsetY = 1 - this._epsilon;
  34926. this._vertexData[arrayOffset] = sprite.position.x;
  34927. this._vertexData[arrayOffset + 1] = sprite.position.y;
  34928. this._vertexData[arrayOffset + 2] = sprite.position.z;
  34929. this._vertexData[arrayOffset + 3] = sprite.angle;
  34930. this._vertexData[arrayOffset + 4] = sprite.width;
  34931. this._vertexData[arrayOffset + 5] = sprite.height;
  34932. this._vertexData[arrayOffset + 6] = offsetX;
  34933. this._vertexData[arrayOffset + 7] = offsetY;
  34934. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  34935. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  34936. var offset = (sprite.cellIndex / rowSize) >> 0;
  34937. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  34938. this._vertexData[arrayOffset + 11] = offset;
  34939. // Color
  34940. this._vertexData[arrayOffset + 12] = sprite.color.r;
  34941. this._vertexData[arrayOffset + 13] = sprite.color.g;
  34942. this._vertexData[arrayOffset + 14] = sprite.color.b;
  34943. this._vertexData[arrayOffset + 15] = sprite.color.a;
  34944. };
  34945. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  34946. var count = Math.min(this._capacity, this.sprites.length);
  34947. var min = BABYLON.Vector3.Zero();
  34948. var max = BABYLON.Vector3.Zero();
  34949. var distance = Number.MAX_VALUE;
  34950. var currentSprite;
  34951. var cameraSpacePosition = BABYLON.Vector3.Zero();
  34952. var cameraView = camera.getViewMatrix();
  34953. for (var index = 0; index < count; index++) {
  34954. var sprite = this.sprites[index];
  34955. if (!sprite) {
  34956. continue;
  34957. }
  34958. if (predicate) {
  34959. if (!predicate(sprite)) {
  34960. continue;
  34961. }
  34962. }
  34963. else if (!sprite.isPickable) {
  34964. continue;
  34965. }
  34966. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  34967. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  34968. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  34969. if (ray.intersectsBoxMinMax(min, max)) {
  34970. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  34971. if (distance > currentDistance) {
  34972. distance = currentDistance;
  34973. currentSprite = sprite;
  34974. if (fastCheck) {
  34975. break;
  34976. }
  34977. }
  34978. }
  34979. }
  34980. if (currentSprite) {
  34981. var result = new BABYLON.PickingInfo();
  34982. result.hit = true;
  34983. result.pickedSprite = currentSprite;
  34984. result.distance = distance;
  34985. return result;
  34986. }
  34987. return null;
  34988. };
  34989. SpriteManager.prototype.render = function () {
  34990. // Check
  34991. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  34992. return;
  34993. var engine = this._scene.getEngine();
  34994. var baseSize = this._spriteTexture.getBaseSize();
  34995. // Sprites
  34996. var deltaTime = engine.getDeltaTime();
  34997. var max = Math.min(this._capacity, this.sprites.length);
  34998. var rowSize = baseSize.width / this.cellWidth;
  34999. var offset = 0;
  35000. for (var index = 0; index < max; index++) {
  35001. var sprite = this.sprites[index];
  35002. if (!sprite) {
  35003. continue;
  35004. }
  35005. sprite._animate(deltaTime);
  35006. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  35007. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  35008. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  35009. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  35010. }
  35011. this._buffer.update(this._vertexData);
  35012. // Render
  35013. var effect = this._effectBase;
  35014. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  35015. effect = this._effectFog;
  35016. }
  35017. engine.enableEffect(effect);
  35018. var viewMatrix = this._scene.getViewMatrix();
  35019. effect.setTexture("diffuseSampler", this._spriteTexture);
  35020. effect.setMatrix("view", viewMatrix);
  35021. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  35022. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  35023. // Fog
  35024. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  35025. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  35026. effect.setColor3("vFogColor", this._scene.fogColor);
  35027. }
  35028. // VBOs
  35029. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  35030. // Draw order
  35031. engine.setDepthFunctionToLessOrEqual();
  35032. effect.setBool("alphaTest", true);
  35033. engine.setColorWrite(false);
  35034. engine.draw(true, 0, max * 6);
  35035. engine.setColorWrite(true);
  35036. effect.setBool("alphaTest", false);
  35037. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  35038. engine.draw(true, 0, max * 6);
  35039. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  35040. };
  35041. SpriteManager.prototype.dispose = function () {
  35042. if (this._buffer) {
  35043. this._buffer.dispose();
  35044. this._buffer = null;
  35045. }
  35046. if (this._indexBuffer) {
  35047. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  35048. this._indexBuffer = null;
  35049. }
  35050. if (this._spriteTexture) {
  35051. this._spriteTexture.dispose();
  35052. this._spriteTexture = null;
  35053. }
  35054. // Remove from scene
  35055. var index = this._scene.spriteManagers.indexOf(this);
  35056. this._scene.spriteManagers.splice(index, 1);
  35057. // Callback
  35058. this.onDisposeObservable.notifyObservers(this);
  35059. this.onDisposeObservable.clear();
  35060. };
  35061. return SpriteManager;
  35062. }());
  35063. BABYLON.SpriteManager = SpriteManager;
  35064. })(BABYLON || (BABYLON = {}));
  35065. //# sourceMappingURL=babylon.spriteManager.js.map
  35066. var BABYLON;
  35067. (function (BABYLON) {
  35068. var Sprite = (function () {
  35069. function Sprite(name, manager) {
  35070. this.name = name;
  35071. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  35072. this.width = 1.0;
  35073. this.height = 1.0;
  35074. this.angle = 0;
  35075. this.cellIndex = 0;
  35076. this.invertU = 0;
  35077. this.invertV = 0;
  35078. this.animations = new Array();
  35079. this.isPickable = false;
  35080. this._animationStarted = false;
  35081. this._loopAnimation = false;
  35082. this._fromIndex = 0;
  35083. this._toIndex = 0;
  35084. this._delay = 0;
  35085. this._direction = 1;
  35086. this._frameCount = 0;
  35087. this._time = 0;
  35088. this._manager = manager;
  35089. this._manager.sprites.push(this);
  35090. this.position = BABYLON.Vector3.Zero();
  35091. }
  35092. Object.defineProperty(Sprite.prototype, "size", {
  35093. get: function () {
  35094. return this.width;
  35095. },
  35096. set: function (value) {
  35097. this.width = value;
  35098. this.height = value;
  35099. },
  35100. enumerable: true,
  35101. configurable: true
  35102. });
  35103. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  35104. this._fromIndex = from;
  35105. this._toIndex = to;
  35106. this._loopAnimation = loop;
  35107. this._delay = delay;
  35108. this._animationStarted = true;
  35109. this._direction = from < to ? 1 : -1;
  35110. this.cellIndex = from;
  35111. this._time = 0;
  35112. this._onAnimationEnd = onAnimationEnd;
  35113. };
  35114. Sprite.prototype.stopAnimation = function () {
  35115. this._animationStarted = false;
  35116. };
  35117. Sprite.prototype._animate = function (deltaTime) {
  35118. if (!this._animationStarted)
  35119. return;
  35120. this._time += deltaTime;
  35121. if (this._time > this._delay) {
  35122. this._time = this._time % this._delay;
  35123. this.cellIndex += this._direction;
  35124. if (this.cellIndex === this._toIndex) {
  35125. if (this._loopAnimation) {
  35126. this.cellIndex = this._fromIndex;
  35127. }
  35128. else {
  35129. this._animationStarted = false;
  35130. if (this._onAnimationEnd) {
  35131. this._onAnimationEnd();
  35132. }
  35133. if (this.disposeWhenFinishedAnimating) {
  35134. this.dispose();
  35135. }
  35136. }
  35137. }
  35138. }
  35139. };
  35140. Sprite.prototype.dispose = function () {
  35141. for (var i = 0; i < this._manager.sprites.length; i++) {
  35142. if (this._manager.sprites[i] == this) {
  35143. this._manager.sprites.splice(i, 1);
  35144. }
  35145. }
  35146. };
  35147. return Sprite;
  35148. }());
  35149. BABYLON.Sprite = Sprite;
  35150. })(BABYLON || (BABYLON = {}));
  35151. //# sourceMappingURL=babylon.sprite.js.map
  35152. var BABYLON;
  35153. (function (BABYLON) {
  35154. var IntersectionInfo = (function () {
  35155. function IntersectionInfo(bu, bv, distance) {
  35156. this.bu = bu;
  35157. this.bv = bv;
  35158. this.distance = distance;
  35159. this.faceId = 0;
  35160. this.subMeshId = 0;
  35161. }
  35162. return IntersectionInfo;
  35163. }());
  35164. BABYLON.IntersectionInfo = IntersectionInfo;
  35165. var PickingInfo = (function () {
  35166. function PickingInfo() {
  35167. this.hit = false;
  35168. this.distance = 0;
  35169. this.pickedPoint = null;
  35170. this.pickedMesh = null;
  35171. this.bu = 0;
  35172. this.bv = 0;
  35173. this.faceId = -1;
  35174. this.subMeshId = 0;
  35175. this.pickedSprite = null;
  35176. }
  35177. // Methods
  35178. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  35179. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  35180. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  35181. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  35182. return null;
  35183. }
  35184. var indices = this.pickedMesh.getIndices();
  35185. var result;
  35186. if (useVerticesNormals) {
  35187. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  35188. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  35189. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  35190. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  35191. normal0 = normal0.scale(this.bu);
  35192. normal1 = normal1.scale(this.bv);
  35193. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  35194. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  35195. }
  35196. else {
  35197. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35198. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  35199. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  35200. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  35201. var p1p2 = vertex1.subtract(vertex2);
  35202. var p3p2 = vertex3.subtract(vertex2);
  35203. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  35204. }
  35205. if (useWorldCoordinates) {
  35206. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  35207. }
  35208. return BABYLON.Vector3.Normalize(result);
  35209. };
  35210. PickingInfo.prototype.getTextureCoordinates = function () {
  35211. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  35212. return null;
  35213. }
  35214. var indices = this.pickedMesh.getIndices();
  35215. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  35216. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  35217. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  35218. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  35219. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  35220. uv1 = uv1.scale(this.bu);
  35221. uv2 = uv2.scale(this.bv);
  35222. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  35223. };
  35224. return PickingInfo;
  35225. }());
  35226. BABYLON.PickingInfo = PickingInfo;
  35227. })(BABYLON || (BABYLON = {}));
  35228. //# sourceMappingURL=babylon.pickingInfo.js.map
  35229. var BABYLON;
  35230. (function (BABYLON) {
  35231. var Ray = (function () {
  35232. function Ray(origin, direction, length) {
  35233. if (length === void 0) { length = Number.MAX_VALUE; }
  35234. this.origin = origin;
  35235. this.direction = direction;
  35236. this.length = length;
  35237. }
  35238. // Methods
  35239. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  35240. var d = 0.0;
  35241. var maxValue = Number.MAX_VALUE;
  35242. var inv;
  35243. var min;
  35244. var max;
  35245. var temp;
  35246. if (Math.abs(this.direction.x) < 0.0000001) {
  35247. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  35248. return false;
  35249. }
  35250. }
  35251. else {
  35252. inv = 1.0 / this.direction.x;
  35253. min = (minimum.x - this.origin.x) * inv;
  35254. max = (maximum.x - this.origin.x) * inv;
  35255. if (max === -Infinity) {
  35256. max = Infinity;
  35257. }
  35258. if (min > max) {
  35259. temp = min;
  35260. min = max;
  35261. max = temp;
  35262. }
  35263. d = Math.max(min, d);
  35264. maxValue = Math.min(max, maxValue);
  35265. if (d > maxValue) {
  35266. return false;
  35267. }
  35268. }
  35269. if (Math.abs(this.direction.y) < 0.0000001) {
  35270. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  35271. return false;
  35272. }
  35273. }
  35274. else {
  35275. inv = 1.0 / this.direction.y;
  35276. min = (minimum.y - this.origin.y) * inv;
  35277. max = (maximum.y - this.origin.y) * inv;
  35278. if (max === -Infinity) {
  35279. max = Infinity;
  35280. }
  35281. if (min > max) {
  35282. temp = min;
  35283. min = max;
  35284. max = temp;
  35285. }
  35286. d = Math.max(min, d);
  35287. maxValue = Math.min(max, maxValue);
  35288. if (d > maxValue) {
  35289. return false;
  35290. }
  35291. }
  35292. if (Math.abs(this.direction.z) < 0.0000001) {
  35293. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  35294. return false;
  35295. }
  35296. }
  35297. else {
  35298. inv = 1.0 / this.direction.z;
  35299. min = (minimum.z - this.origin.z) * inv;
  35300. max = (maximum.z - this.origin.z) * inv;
  35301. if (max === -Infinity) {
  35302. max = Infinity;
  35303. }
  35304. if (min > max) {
  35305. temp = min;
  35306. min = max;
  35307. max = temp;
  35308. }
  35309. d = Math.max(min, d);
  35310. maxValue = Math.min(max, maxValue);
  35311. if (d > maxValue) {
  35312. return false;
  35313. }
  35314. }
  35315. return true;
  35316. };
  35317. Ray.prototype.intersectsBox = function (box) {
  35318. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  35319. };
  35320. Ray.prototype.intersectsSphere = function (sphere) {
  35321. var x = sphere.center.x - this.origin.x;
  35322. var y = sphere.center.y - this.origin.y;
  35323. var z = sphere.center.z - this.origin.z;
  35324. var pyth = (x * x) + (y * y) + (z * z);
  35325. var rr = sphere.radius * sphere.radius;
  35326. if (pyth <= rr) {
  35327. return true;
  35328. }
  35329. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  35330. if (dot < 0.0) {
  35331. return false;
  35332. }
  35333. var temp = pyth - (dot * dot);
  35334. return temp <= rr;
  35335. };
  35336. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  35337. if (!this._edge1) {
  35338. this._edge1 = BABYLON.Vector3.Zero();
  35339. this._edge2 = BABYLON.Vector3.Zero();
  35340. this._pvec = BABYLON.Vector3.Zero();
  35341. this._tvec = BABYLON.Vector3.Zero();
  35342. this._qvec = BABYLON.Vector3.Zero();
  35343. }
  35344. vertex1.subtractToRef(vertex0, this._edge1);
  35345. vertex2.subtractToRef(vertex0, this._edge2);
  35346. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  35347. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  35348. if (det === 0) {
  35349. return null;
  35350. }
  35351. var invdet = 1 / det;
  35352. this.origin.subtractToRef(vertex0, this._tvec);
  35353. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  35354. if (bu < 0 || bu > 1.0) {
  35355. return null;
  35356. }
  35357. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  35358. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  35359. if (bv < 0 || bu + bv > 1.0) {
  35360. return null;
  35361. }
  35362. //check if the distance is longer than the predefined length.
  35363. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  35364. if (distance > this.length) {
  35365. return null;
  35366. }
  35367. return new BABYLON.IntersectionInfo(bu, bv, distance);
  35368. };
  35369. Ray.prototype.intersectsPlane = function (plane) {
  35370. var distance;
  35371. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  35372. if (Math.abs(result1) < 9.99999997475243E-07) {
  35373. return null;
  35374. }
  35375. else {
  35376. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  35377. distance = (-plane.d - result2) / result1;
  35378. if (distance < 0.0) {
  35379. if (distance < -9.99999997475243E-07) {
  35380. return null;
  35381. }
  35382. else {
  35383. return 0;
  35384. }
  35385. }
  35386. return distance;
  35387. }
  35388. };
  35389. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  35390. var tm = BABYLON.Tmp.Matrix[0];
  35391. mesh.getWorldMatrix().invertToRef(tm);
  35392. if (this._tmpRay) {
  35393. Ray.TransformToRef(this, tm, this._tmpRay);
  35394. }
  35395. else {
  35396. this._tmpRay = Ray.Transform(this, tm);
  35397. }
  35398. return mesh.intersects(this._tmpRay, fastCheck);
  35399. };
  35400. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  35401. if (results) {
  35402. results.length = 0;
  35403. }
  35404. else {
  35405. results = [];
  35406. }
  35407. for (var i = 0; i < meshes.length; i++) {
  35408. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  35409. if (pickInfo.hit) {
  35410. results.push(pickInfo);
  35411. }
  35412. }
  35413. results.sort(this._comparePickingInfo);
  35414. return results;
  35415. };
  35416. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  35417. if (pickingInfoA.distance < pickingInfoB.distance) {
  35418. return -1;
  35419. }
  35420. else if (pickingInfoA.distance > pickingInfoB.distance) {
  35421. return 1;
  35422. }
  35423. else {
  35424. return 0;
  35425. }
  35426. };
  35427. /**
  35428. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  35429. * @param sega the first point of the segment to test the intersection against
  35430. * @param segb the second point of the segment to test the intersection against
  35431. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  35432. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  35433. */
  35434. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  35435. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  35436. var u = segb.subtract(sega);
  35437. var v = rsegb.subtract(this.origin);
  35438. var w = sega.subtract(this.origin);
  35439. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  35440. var b = BABYLON.Vector3.Dot(u, v);
  35441. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  35442. var d = BABYLON.Vector3.Dot(u, w);
  35443. var e = BABYLON.Vector3.Dot(v, w);
  35444. var D = a * c - b * b; // always >= 0
  35445. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  35446. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  35447. // compute the line parameters of the two closest points
  35448. if (D < Ray.smallnum) {
  35449. sN = 0.0; // force using point P0 on segment S1
  35450. sD = 1.0; // to prevent possible division by 0.0 later
  35451. tN = e;
  35452. tD = c;
  35453. }
  35454. else {
  35455. sN = (b * e - c * d);
  35456. tN = (a * e - b * d);
  35457. if (sN < 0.0) {
  35458. sN = 0.0;
  35459. tN = e;
  35460. tD = c;
  35461. }
  35462. else if (sN > sD) {
  35463. sN = sD;
  35464. tN = e + b;
  35465. tD = c;
  35466. }
  35467. }
  35468. if (tN < 0.0) {
  35469. tN = 0.0;
  35470. // recompute sc for this edge
  35471. if (-d < 0.0) {
  35472. sN = 0.0;
  35473. }
  35474. else if (-d > a)
  35475. sN = sD;
  35476. else {
  35477. sN = -d;
  35478. sD = a;
  35479. }
  35480. }
  35481. else if (tN > tD) {
  35482. tN = tD;
  35483. // recompute sc for this edge
  35484. if ((-d + b) < 0.0) {
  35485. sN = 0;
  35486. }
  35487. else if ((-d + b) > a) {
  35488. sN = sD;
  35489. }
  35490. else {
  35491. sN = (-d + b);
  35492. sD = a;
  35493. }
  35494. }
  35495. // finally do the division to get sc and tc
  35496. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  35497. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  35498. // get the difference of the two closest points
  35499. var qtc = v.multiplyByFloats(tc, tc, tc);
  35500. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  35501. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  35502. if (isIntersected) {
  35503. return qtc.length();
  35504. }
  35505. return -1;
  35506. };
  35507. // Statics
  35508. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  35509. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  35510. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  35511. var direction = end.subtract(start);
  35512. direction.normalize();
  35513. return new Ray(start, direction);
  35514. };
  35515. /**
  35516. * 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
  35517. * transformed to the given world matrix.
  35518. * @param origin The origin point
  35519. * @param end The end point
  35520. * @param world a matrix to transform the ray to. Default is the identity matrix.
  35521. */
  35522. Ray.CreateNewFromTo = function (origin, end, world) {
  35523. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  35524. var direction = end.subtract(origin);
  35525. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  35526. direction.normalize();
  35527. return Ray.Transform(new Ray(origin, direction, length), world);
  35528. };
  35529. Ray.Transform = function (ray, matrix) {
  35530. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  35531. Ray.TransformToRef(ray, matrix, result);
  35532. return result;
  35533. };
  35534. Ray.TransformToRef = function (ray, matrix, result) {
  35535. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  35536. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  35537. result.length = ray.length;
  35538. var dir = result.direction;
  35539. var len = dir.length();
  35540. if (!(len === 0 || len === 1)) {
  35541. var num = 1.0 / len;
  35542. dir.x *= num;
  35543. dir.y *= num;
  35544. dir.z *= num;
  35545. result.length *= len;
  35546. }
  35547. };
  35548. return Ray;
  35549. }());
  35550. Ray.smallnum = 0.00000001;
  35551. Ray.rayl = 10e8;
  35552. BABYLON.Ray = Ray;
  35553. })(BABYLON || (BABYLON = {}));
  35554. //# sourceMappingURL=babylon.ray.js.map
  35555. var BABYLON;
  35556. (function (BABYLON) {
  35557. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  35558. if (boxMin.x > sphereCenter.x + sphereRadius)
  35559. return false;
  35560. if (sphereCenter.x - sphereRadius > boxMax.x)
  35561. return false;
  35562. if (boxMin.y > sphereCenter.y + sphereRadius)
  35563. return false;
  35564. if (sphereCenter.y - sphereRadius > boxMax.y)
  35565. return false;
  35566. if (boxMin.z > sphereCenter.z + sphereRadius)
  35567. return false;
  35568. if (sphereCenter.z - sphereRadius > boxMax.z)
  35569. return false;
  35570. return true;
  35571. };
  35572. var getLowestRoot = (function () {
  35573. var result = { root: 0, found: false };
  35574. return function (a, b, c, maxR) {
  35575. result.root = 0;
  35576. result.found = false;
  35577. var determinant = b * b - 4.0 * a * c;
  35578. if (determinant < 0)
  35579. return result;
  35580. var sqrtD = Math.sqrt(determinant);
  35581. var r1 = (-b - sqrtD) / (2.0 * a);
  35582. var r2 = (-b + sqrtD) / (2.0 * a);
  35583. if (r1 > r2) {
  35584. var temp = r2;
  35585. r2 = r1;
  35586. r1 = temp;
  35587. }
  35588. if (r1 > 0 && r1 < maxR) {
  35589. result.root = r1;
  35590. result.found = true;
  35591. return result;
  35592. }
  35593. if (r2 > 0 && r2 < maxR) {
  35594. result.root = r2;
  35595. result.found = true;
  35596. return result;
  35597. }
  35598. return result;
  35599. };
  35600. })();
  35601. var Collider = (function () {
  35602. function Collider() {
  35603. this.radius = new BABYLON.Vector3(1, 1, 1);
  35604. this.retry = 0;
  35605. this.basePointWorld = BABYLON.Vector3.Zero();
  35606. this.velocityWorld = BABYLON.Vector3.Zero();
  35607. this.normalizedVelocity = BABYLON.Vector3.Zero();
  35608. this._collisionPoint = BABYLON.Vector3.Zero();
  35609. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  35610. this._tempVector = BABYLON.Vector3.Zero();
  35611. this._tempVector2 = BABYLON.Vector3.Zero();
  35612. this._tempVector3 = BABYLON.Vector3.Zero();
  35613. this._tempVector4 = BABYLON.Vector3.Zero();
  35614. this._edge = BABYLON.Vector3.Zero();
  35615. this._baseToVertex = BABYLON.Vector3.Zero();
  35616. this._destinationPoint = BABYLON.Vector3.Zero();
  35617. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  35618. this._displacementVector = BABYLON.Vector3.Zero();
  35619. this._collisionMask = -1;
  35620. }
  35621. Object.defineProperty(Collider.prototype, "collisionMask", {
  35622. get: function () {
  35623. return this._collisionMask;
  35624. },
  35625. set: function (mask) {
  35626. this._collisionMask = !isNaN(mask) ? mask : -1;
  35627. },
  35628. enumerable: true,
  35629. configurable: true
  35630. });
  35631. // Methods
  35632. Collider.prototype._initialize = function (source, dir, e) {
  35633. this.velocity = dir;
  35634. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  35635. this.basePoint = source;
  35636. source.multiplyToRef(this.radius, this.basePointWorld);
  35637. dir.multiplyToRef(this.radius, this.velocityWorld);
  35638. this.velocityWorldLength = this.velocityWorld.length();
  35639. this.epsilon = e;
  35640. this.collisionFound = false;
  35641. };
  35642. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  35643. pa.subtractToRef(point, this._tempVector);
  35644. pb.subtractToRef(point, this._tempVector2);
  35645. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  35646. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  35647. if (d < 0)
  35648. return false;
  35649. pc.subtractToRef(point, this._tempVector3);
  35650. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  35651. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  35652. if (d < 0)
  35653. return false;
  35654. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  35655. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  35656. return d >= 0;
  35657. };
  35658. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  35659. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  35660. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  35661. if (distance > this.velocityWorldLength + max + sphereRadius) {
  35662. return false;
  35663. }
  35664. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  35665. return false;
  35666. return true;
  35667. };
  35668. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  35669. var t0;
  35670. var embeddedInPlane = false;
  35671. //defensive programming, actually not needed.
  35672. if (!trianglePlaneArray) {
  35673. trianglePlaneArray = [];
  35674. }
  35675. if (!trianglePlaneArray[faceIndex]) {
  35676. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  35677. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  35678. }
  35679. var trianglePlane = trianglePlaneArray[faceIndex];
  35680. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  35681. return;
  35682. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  35683. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  35684. if (normalDotVelocity == 0) {
  35685. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  35686. return;
  35687. embeddedInPlane = true;
  35688. t0 = 0;
  35689. }
  35690. else {
  35691. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  35692. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  35693. if (t0 > t1) {
  35694. var temp = t1;
  35695. t1 = t0;
  35696. t0 = temp;
  35697. }
  35698. if (t0 > 1.0 || t1 < 0.0)
  35699. return;
  35700. if (t0 < 0)
  35701. t0 = 0;
  35702. if (t0 > 1.0)
  35703. t0 = 1.0;
  35704. }
  35705. this._collisionPoint.copyFromFloats(0, 0, 0);
  35706. var found = false;
  35707. var t = 1.0;
  35708. if (!embeddedInPlane) {
  35709. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  35710. this.velocity.scaleToRef(t0, this._tempVector);
  35711. this._planeIntersectionPoint.addInPlace(this._tempVector);
  35712. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  35713. found = true;
  35714. t = t0;
  35715. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  35716. }
  35717. }
  35718. if (!found) {
  35719. var velocitySquaredLength = this.velocity.lengthSquared();
  35720. var a = velocitySquaredLength;
  35721. this.basePoint.subtractToRef(p1, this._tempVector);
  35722. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  35723. var c = this._tempVector.lengthSquared() - 1.0;
  35724. var lowestRoot = getLowestRoot(a, b, c, t);
  35725. if (lowestRoot.found) {
  35726. t = lowestRoot.root;
  35727. found = true;
  35728. this._collisionPoint.copyFrom(p1);
  35729. }
  35730. this.basePoint.subtractToRef(p2, this._tempVector);
  35731. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  35732. c = this._tempVector.lengthSquared() - 1.0;
  35733. lowestRoot = getLowestRoot(a, b, c, t);
  35734. if (lowestRoot.found) {
  35735. t = lowestRoot.root;
  35736. found = true;
  35737. this._collisionPoint.copyFrom(p2);
  35738. }
  35739. this.basePoint.subtractToRef(p3, this._tempVector);
  35740. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  35741. c = this._tempVector.lengthSquared() - 1.0;
  35742. lowestRoot = getLowestRoot(a, b, c, t);
  35743. if (lowestRoot.found) {
  35744. t = lowestRoot.root;
  35745. found = true;
  35746. this._collisionPoint.copyFrom(p3);
  35747. }
  35748. p2.subtractToRef(p1, this._edge);
  35749. p1.subtractToRef(this.basePoint, this._baseToVertex);
  35750. var edgeSquaredLength = this._edge.lengthSquared();
  35751. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  35752. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  35753. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  35754. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  35755. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  35756. lowestRoot = getLowestRoot(a, b, c, t);
  35757. if (lowestRoot.found) {
  35758. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  35759. if (f >= 0.0 && f <= 1.0) {
  35760. t = lowestRoot.root;
  35761. found = true;
  35762. this._edge.scaleInPlace(f);
  35763. p1.addToRef(this._edge, this._collisionPoint);
  35764. }
  35765. }
  35766. p3.subtractToRef(p2, this._edge);
  35767. p2.subtractToRef(this.basePoint, this._baseToVertex);
  35768. edgeSquaredLength = this._edge.lengthSquared();
  35769. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  35770. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  35771. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  35772. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  35773. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  35774. lowestRoot = getLowestRoot(a, b, c, t);
  35775. if (lowestRoot.found) {
  35776. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  35777. if (f >= 0.0 && f <= 1.0) {
  35778. t = lowestRoot.root;
  35779. found = true;
  35780. this._edge.scaleInPlace(f);
  35781. p2.addToRef(this._edge, this._collisionPoint);
  35782. }
  35783. }
  35784. p1.subtractToRef(p3, this._edge);
  35785. p3.subtractToRef(this.basePoint, this._baseToVertex);
  35786. edgeSquaredLength = this._edge.lengthSquared();
  35787. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  35788. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  35789. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  35790. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  35791. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  35792. lowestRoot = getLowestRoot(a, b, c, t);
  35793. if (lowestRoot.found) {
  35794. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  35795. if (f >= 0.0 && f <= 1.0) {
  35796. t = lowestRoot.root;
  35797. found = true;
  35798. this._edge.scaleInPlace(f);
  35799. p3.addToRef(this._edge, this._collisionPoint);
  35800. }
  35801. }
  35802. }
  35803. if (found) {
  35804. var distToCollision = t * this.velocity.length();
  35805. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  35806. if (!this.intersectionPoint) {
  35807. this.intersectionPoint = this._collisionPoint.clone();
  35808. }
  35809. else {
  35810. this.intersectionPoint.copyFrom(this._collisionPoint);
  35811. }
  35812. this.nearestDistance = distToCollision;
  35813. this.collisionFound = true;
  35814. }
  35815. }
  35816. };
  35817. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  35818. for (var i = indexStart; i < indexEnd; i += 3) {
  35819. var p1 = pts[indices[i] - decal];
  35820. var p2 = pts[indices[i + 1] - decal];
  35821. var p3 = pts[indices[i + 2] - decal];
  35822. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  35823. }
  35824. };
  35825. Collider.prototype._getResponse = function (pos, vel) {
  35826. pos.addToRef(vel, this._destinationPoint);
  35827. vel.scaleInPlace((this.nearestDistance / vel.length()));
  35828. this.basePoint.addToRef(vel, pos);
  35829. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  35830. this._slidePlaneNormal.normalize();
  35831. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  35832. pos.addInPlace(this._displacementVector);
  35833. this.intersectionPoint.addInPlace(this._displacementVector);
  35834. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  35835. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  35836. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  35837. };
  35838. return Collider;
  35839. }());
  35840. BABYLON.Collider = Collider;
  35841. })(BABYLON || (BABYLON = {}));
  35842. //# sourceMappingURL=babylon.collider.js.map
  35843. var BABYLON;
  35844. (function (BABYLON) {
  35845. //WebWorker code will be inserted to this variable.
  35846. BABYLON.CollisionWorker = "";
  35847. var WorkerTaskType;
  35848. (function (WorkerTaskType) {
  35849. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  35850. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  35851. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  35852. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  35853. var WorkerReplyType;
  35854. (function (WorkerReplyType) {
  35855. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  35856. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  35857. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  35858. var CollisionCoordinatorWorker = (function () {
  35859. function CollisionCoordinatorWorker() {
  35860. var _this = this;
  35861. this._scaledPosition = BABYLON.Vector3.Zero();
  35862. this._scaledVelocity = BABYLON.Vector3.Zero();
  35863. this.onMeshUpdated = function (mesh) {
  35864. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  35865. };
  35866. this.onGeometryUpdated = function (geometry) {
  35867. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  35868. };
  35869. this._afterRender = function () {
  35870. if (!_this._init)
  35871. return;
  35872. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  35873. return;
  35874. }
  35875. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  35876. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  35877. if (_this._runningUpdated > 4) {
  35878. return;
  35879. }
  35880. ++_this._runningUpdated;
  35881. var payload = {
  35882. updatedMeshes: _this._addUpdateMeshesList,
  35883. updatedGeometries: _this._addUpdateGeometriesList,
  35884. removedGeometries: _this._toRemoveGeometryArray,
  35885. removedMeshes: _this._toRemoveMeshesArray
  35886. };
  35887. var message = {
  35888. payload: payload,
  35889. taskType: WorkerTaskType.UPDATE
  35890. };
  35891. var serializable = [];
  35892. for (var id in payload.updatedGeometries) {
  35893. if (payload.updatedGeometries.hasOwnProperty(id)) {
  35894. //prepare transferables
  35895. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  35896. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  35897. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  35898. }
  35899. }
  35900. _this._worker.postMessage(message, serializable);
  35901. _this._addUpdateMeshesList = {};
  35902. _this._addUpdateGeometriesList = {};
  35903. _this._toRemoveGeometryArray = [];
  35904. _this._toRemoveMeshesArray = [];
  35905. };
  35906. this._onMessageFromWorker = function (e) {
  35907. var returnData = e.data;
  35908. if (returnData.error != WorkerReplyType.SUCCESS) {
  35909. //TODO what errors can be returned from the worker?
  35910. BABYLON.Tools.Warn("error returned from worker!");
  35911. return;
  35912. }
  35913. switch (returnData.taskType) {
  35914. case WorkerTaskType.INIT:
  35915. _this._init = true;
  35916. //Update the worked with ALL of the scene's current state
  35917. _this._scene.meshes.forEach(function (mesh) {
  35918. _this.onMeshAdded(mesh);
  35919. });
  35920. _this._scene.getGeometries().forEach(function (geometry) {
  35921. _this.onGeometryAdded(geometry);
  35922. });
  35923. break;
  35924. case WorkerTaskType.UPDATE:
  35925. _this._runningUpdated--;
  35926. break;
  35927. case WorkerTaskType.COLLIDE:
  35928. _this._runningCollisionTask = false;
  35929. var returnPayload = returnData.payload;
  35930. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  35931. return;
  35932. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  35933. //cleanup
  35934. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  35935. break;
  35936. }
  35937. };
  35938. this._collisionsCallbackArray = [];
  35939. this._init = false;
  35940. this._runningUpdated = 0;
  35941. this._runningCollisionTask = false;
  35942. this._addUpdateMeshesList = {};
  35943. this._addUpdateGeometriesList = {};
  35944. this._toRemoveGeometryArray = [];
  35945. this._toRemoveMeshesArray = [];
  35946. }
  35947. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  35948. if (!this._init)
  35949. return;
  35950. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  35951. return;
  35952. position.divideToRef(collider.radius, this._scaledPosition);
  35953. velocity.divideToRef(collider.radius, this._scaledVelocity);
  35954. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  35955. var payload = {
  35956. collider: {
  35957. position: this._scaledPosition.asArray(),
  35958. velocity: this._scaledVelocity.asArray(),
  35959. radius: collider.radius.asArray()
  35960. },
  35961. collisionId: collisionIndex,
  35962. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  35963. maximumRetry: maximumRetry
  35964. };
  35965. var message = {
  35966. payload: payload,
  35967. taskType: WorkerTaskType.COLLIDE
  35968. };
  35969. this._worker.postMessage(message);
  35970. };
  35971. CollisionCoordinatorWorker.prototype.init = function (scene) {
  35972. this._scene = scene;
  35973. this._scene.registerAfterRender(this._afterRender);
  35974. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  35975. this._worker = new Worker(workerUrl);
  35976. this._worker.onmessage = this._onMessageFromWorker;
  35977. var message = {
  35978. payload: {},
  35979. taskType: WorkerTaskType.INIT
  35980. };
  35981. this._worker.postMessage(message);
  35982. };
  35983. CollisionCoordinatorWorker.prototype.destroy = function () {
  35984. this._scene.unregisterAfterRender(this._afterRender);
  35985. this._worker.terminate();
  35986. };
  35987. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  35988. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  35989. this.onMeshUpdated(mesh);
  35990. };
  35991. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  35992. this._toRemoveMeshesArray.push(mesh.uniqueId);
  35993. };
  35994. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  35995. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  35996. geometry.onGeometryUpdated = this.onGeometryUpdated;
  35997. this.onGeometryUpdated(geometry);
  35998. };
  35999. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  36000. this._toRemoveGeometryArray.push(geometry.id);
  36001. };
  36002. return CollisionCoordinatorWorker;
  36003. }());
  36004. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  36005. var submeshes = [];
  36006. if (mesh.subMeshes) {
  36007. submeshes = mesh.subMeshes.map(function (sm, idx) {
  36008. return {
  36009. position: idx,
  36010. verticesStart: sm.verticesStart,
  36011. verticesCount: sm.verticesCount,
  36012. indexStart: sm.indexStart,
  36013. indexCount: sm.indexCount,
  36014. hasMaterial: !!sm.getMaterial(),
  36015. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  36016. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  36017. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  36018. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  36019. };
  36020. });
  36021. }
  36022. var geometryId = null;
  36023. if (mesh instanceof BABYLON.Mesh) {
  36024. geometryId = mesh.geometry ? mesh.geometry.id : null;
  36025. }
  36026. else if (mesh instanceof BABYLON.InstancedMesh) {
  36027. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  36028. }
  36029. return {
  36030. uniqueId: mesh.uniqueId,
  36031. id: mesh.id,
  36032. name: mesh.name,
  36033. geometryId: geometryId,
  36034. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  36035. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  36036. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  36037. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  36038. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  36039. subMeshes: submeshes,
  36040. checkCollisions: mesh.checkCollisions
  36041. };
  36042. };
  36043. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  36044. return {
  36045. id: geometry.id,
  36046. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  36047. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  36048. indices: new Uint32Array(geometry.getIndices() || []),
  36049. };
  36050. };
  36051. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  36052. var CollisionCoordinatorLegacy = (function () {
  36053. function CollisionCoordinatorLegacy() {
  36054. this._scaledPosition = BABYLON.Vector3.Zero();
  36055. this._scaledVelocity = BABYLON.Vector3.Zero();
  36056. this._finalPosition = BABYLON.Vector3.Zero();
  36057. }
  36058. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  36059. position.divideToRef(collider.radius, this._scaledPosition);
  36060. velocity.divideToRef(collider.radius, this._scaledVelocity);
  36061. collider.collidedMesh = null;
  36062. collider.retry = 0;
  36063. collider.initialVelocity = this._scaledVelocity;
  36064. collider.initialPosition = this._scaledPosition;
  36065. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  36066. this._finalPosition.multiplyInPlace(collider.radius);
  36067. //run the callback
  36068. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  36069. };
  36070. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  36071. this._scene = scene;
  36072. };
  36073. CollisionCoordinatorLegacy.prototype.destroy = function () {
  36074. //Legacy need no destruction method.
  36075. };
  36076. //No update in legacy mode
  36077. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  36078. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  36079. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  36080. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  36081. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  36082. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  36083. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  36084. if (excludedMesh === void 0) { excludedMesh = null; }
  36085. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  36086. if (collider.retry >= maximumRetry) {
  36087. finalPosition.copyFrom(position);
  36088. return;
  36089. }
  36090. // Check if this is a mesh else camera or -1
  36091. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  36092. collider._initialize(position, velocity, closeDistance);
  36093. // Check all meshes
  36094. for (var index = 0; index < this._scene.meshes.length; index++) {
  36095. var mesh = this._scene.meshes[index];
  36096. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  36097. mesh._checkCollision(collider);
  36098. }
  36099. }
  36100. if (!collider.collisionFound) {
  36101. position.addToRef(velocity, finalPosition);
  36102. return;
  36103. }
  36104. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  36105. collider._getResponse(position, velocity);
  36106. }
  36107. if (velocity.length() <= closeDistance) {
  36108. finalPosition.copyFrom(position);
  36109. return;
  36110. }
  36111. collider.retry++;
  36112. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  36113. };
  36114. return CollisionCoordinatorLegacy;
  36115. }());
  36116. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  36117. })(BABYLON || (BABYLON = {}));
  36118. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  36119. var BABYLON;
  36120. (function (BABYLON) {
  36121. var Particle = (function () {
  36122. function Particle() {
  36123. this.position = BABYLON.Vector3.Zero();
  36124. this.direction = BABYLON.Vector3.Zero();
  36125. this.color = new BABYLON.Color4(0, 0, 0, 0);
  36126. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  36127. this.lifeTime = 1.0;
  36128. this.age = 0;
  36129. this.size = 0;
  36130. this.angle = 0;
  36131. this.angularSpeed = 0;
  36132. }
  36133. Particle.prototype.copyTo = function (other) {
  36134. other.position.copyFrom(this.position);
  36135. other.direction.copyFrom(this.direction);
  36136. other.color.copyFrom(this.color);
  36137. other.colorStep.copyFrom(this.colorStep);
  36138. other.lifeTime = this.lifeTime;
  36139. other.age = this.age;
  36140. other.size = this.size;
  36141. other.angle = this.angle;
  36142. other.angularSpeed = this.angularSpeed;
  36143. };
  36144. return Particle;
  36145. }());
  36146. BABYLON.Particle = Particle;
  36147. })(BABYLON || (BABYLON = {}));
  36148. //# sourceMappingURL=babylon.particle.js.map
  36149. var BABYLON;
  36150. (function (BABYLON) {
  36151. var randomNumber = function (min, max) {
  36152. if (min === max) {
  36153. return (min);
  36154. }
  36155. var random = Math.random();
  36156. return ((random * (max - min)) + min);
  36157. };
  36158. var ParticleSystem = (function () {
  36159. function ParticleSystem(name, capacity, scene, customEffect) {
  36160. var _this = this;
  36161. this.name = name;
  36162. // Members
  36163. this.animations = [];
  36164. this.renderingGroupId = 0;
  36165. this.emitter = null;
  36166. this.emitRate = 10;
  36167. this.manualEmitCount = -1;
  36168. this.updateSpeed = 0.01;
  36169. this.targetStopDuration = 0;
  36170. this.disposeOnStop = false;
  36171. this.minEmitPower = 1;
  36172. this.maxEmitPower = 1;
  36173. this.minLifeTime = 1;
  36174. this.maxLifeTime = 1;
  36175. this.minSize = 1;
  36176. this.maxSize = 1;
  36177. this.minAngularSpeed = 0;
  36178. this.maxAngularSpeed = 0;
  36179. this.layerMask = 0x0FFFFFFF;
  36180. this.customShader = null;
  36181. this.preventAutoStart = false;
  36182. /**
  36183. * An event triggered when the system is disposed.
  36184. * @type {BABYLON.Observable}
  36185. */
  36186. this.onDisposeObservable = new BABYLON.Observable();
  36187. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  36188. this.forceDepthWrite = false;
  36189. this.gravity = BABYLON.Vector3.Zero();
  36190. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  36191. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  36192. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  36193. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  36194. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  36195. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  36196. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  36197. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  36198. this.particles = new Array();
  36199. this._stockParticles = new Array();
  36200. this._newPartsExcess = 0;
  36201. this._vertexBuffers = {};
  36202. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  36203. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  36204. this._scaledDirection = BABYLON.Vector3.Zero();
  36205. this._scaledGravity = BABYLON.Vector3.Zero();
  36206. this._currentRenderId = -1;
  36207. this._started = false;
  36208. this._stopped = false;
  36209. this._actualFrame = 0;
  36210. this.id = name;
  36211. this._capacity = capacity;
  36212. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  36213. this._customEffect = customEffect;
  36214. scene.particleSystems.push(this);
  36215. var indices = [];
  36216. var index = 0;
  36217. for (var count = 0; count < capacity; count++) {
  36218. indices.push(index);
  36219. indices.push(index + 1);
  36220. indices.push(index + 2);
  36221. indices.push(index);
  36222. indices.push(index + 2);
  36223. indices.push(index + 3);
  36224. index += 4;
  36225. }
  36226. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  36227. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  36228. this._vertexData = new Float32Array(capacity * 11 * 4);
  36229. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 11);
  36230. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  36231. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  36232. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  36233. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  36234. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  36235. this._vertexBuffers["options"] = options;
  36236. // Default behaviors
  36237. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  36238. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  36239. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  36240. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  36241. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  36242. };
  36243. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  36244. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  36245. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  36246. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  36247. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  36248. };
  36249. this.updateFunction = function (particles) {
  36250. for (var index = 0; index < particles.length; index++) {
  36251. var particle = particles[index];
  36252. particle.age += _this._scaledUpdateSpeed;
  36253. if (particle.age >= particle.lifeTime) {
  36254. _this.recycleParticle(particle);
  36255. index--;
  36256. continue;
  36257. }
  36258. else {
  36259. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  36260. particle.color.addInPlace(_this._scaledColorStep);
  36261. if (particle.color.a < 0)
  36262. particle.color.a = 0;
  36263. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  36264. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  36265. particle.position.addInPlace(_this._scaledDirection);
  36266. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  36267. particle.direction.addInPlace(_this._scaledGravity);
  36268. }
  36269. }
  36270. };
  36271. }
  36272. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  36273. set: function (callback) {
  36274. if (this._onDisposeObserver) {
  36275. this.onDisposeObservable.remove(this._onDisposeObserver);
  36276. }
  36277. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  36278. },
  36279. enumerable: true,
  36280. configurable: true
  36281. });
  36282. ParticleSystem.prototype.recycleParticle = function (particle) {
  36283. var lastParticle = this.particles.pop();
  36284. if (lastParticle !== particle) {
  36285. lastParticle.copyTo(particle);
  36286. this._stockParticles.push(lastParticle);
  36287. }
  36288. };
  36289. ParticleSystem.prototype.getCapacity = function () {
  36290. return this._capacity;
  36291. };
  36292. ParticleSystem.prototype.isAlive = function () {
  36293. return this._alive;
  36294. };
  36295. ParticleSystem.prototype.isStarted = function () {
  36296. return this._started;
  36297. };
  36298. ParticleSystem.prototype.start = function () {
  36299. this._started = true;
  36300. this._stopped = false;
  36301. this._actualFrame = 0;
  36302. };
  36303. ParticleSystem.prototype.stop = function () {
  36304. this._stopped = true;
  36305. };
  36306. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  36307. var offset = index * 11;
  36308. this._vertexData[offset] = particle.position.x;
  36309. this._vertexData[offset + 1] = particle.position.y;
  36310. this._vertexData[offset + 2] = particle.position.z;
  36311. this._vertexData[offset + 3] = particle.color.r;
  36312. this._vertexData[offset + 4] = particle.color.g;
  36313. this._vertexData[offset + 5] = particle.color.b;
  36314. this._vertexData[offset + 6] = particle.color.a;
  36315. this._vertexData[offset + 7] = particle.angle;
  36316. this._vertexData[offset + 8] = particle.size;
  36317. this._vertexData[offset + 9] = offsetX;
  36318. this._vertexData[offset + 10] = offsetY;
  36319. };
  36320. ParticleSystem.prototype._update = function (newParticles) {
  36321. // Update current
  36322. this._alive = this.particles.length > 0;
  36323. this.updateFunction(this.particles);
  36324. // Add new ones
  36325. var worldMatrix;
  36326. if (this.emitter.position) {
  36327. worldMatrix = this.emitter.getWorldMatrix();
  36328. }
  36329. else {
  36330. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  36331. }
  36332. var particle;
  36333. for (var index = 0; index < newParticles; index++) {
  36334. if (this.particles.length === this._capacity) {
  36335. break;
  36336. }
  36337. if (this._stockParticles.length !== 0) {
  36338. particle = this._stockParticles.pop();
  36339. particle.age = 0;
  36340. }
  36341. else {
  36342. particle = new BABYLON.Particle();
  36343. }
  36344. this.particles.push(particle);
  36345. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  36346. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  36347. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  36348. particle.size = randomNumber(this.minSize, this.maxSize);
  36349. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  36350. this.startPositionFunction(worldMatrix, particle.position, particle);
  36351. var step = randomNumber(0, 1.0);
  36352. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  36353. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  36354. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  36355. }
  36356. };
  36357. ParticleSystem.prototype._getEffect = function () {
  36358. if (this._customEffect) {
  36359. return this._customEffect;
  36360. }
  36361. ;
  36362. var defines = [];
  36363. if (this._scene.clipPlane) {
  36364. defines.push("#define CLIPPLANE");
  36365. }
  36366. // Effect
  36367. var join = defines.join("\n");
  36368. if (this._cachedDefines !== join) {
  36369. this._cachedDefines = join;
  36370. this._effect = this._scene.getEngine().createEffect("particles", [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  36371. }
  36372. return this._effect;
  36373. };
  36374. ParticleSystem.prototype.animate = function () {
  36375. if (!this._started)
  36376. return;
  36377. var effect = this._getEffect();
  36378. // Check
  36379. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  36380. return;
  36381. if (this._currentRenderId === this._scene.getRenderId()) {
  36382. return;
  36383. }
  36384. this._currentRenderId = this._scene.getRenderId();
  36385. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  36386. // determine the number of particles we need to create
  36387. var newParticles;
  36388. if (this.manualEmitCount > -1) {
  36389. newParticles = this.manualEmitCount;
  36390. this._newPartsExcess = 0;
  36391. this.manualEmitCount = 0;
  36392. }
  36393. else {
  36394. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  36395. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  36396. }
  36397. if (this._newPartsExcess > 1.0) {
  36398. newParticles += this._newPartsExcess >> 0;
  36399. this._newPartsExcess -= this._newPartsExcess >> 0;
  36400. }
  36401. this._alive = false;
  36402. if (!this._stopped) {
  36403. this._actualFrame += this._scaledUpdateSpeed;
  36404. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  36405. this.stop();
  36406. }
  36407. else {
  36408. newParticles = 0;
  36409. }
  36410. this._update(newParticles);
  36411. // Stopped?
  36412. if (this._stopped) {
  36413. if (!this._alive) {
  36414. this._started = false;
  36415. if (this.disposeOnStop) {
  36416. this._scene._toBeDisposed.push(this);
  36417. }
  36418. }
  36419. }
  36420. // Update VBO
  36421. var offset = 0;
  36422. for (var index = 0; index < this.particles.length; index++) {
  36423. var particle = this.particles[index];
  36424. this._appendParticleVertex(offset++, particle, 0, 0);
  36425. this._appendParticleVertex(offset++, particle, 1, 0);
  36426. this._appendParticleVertex(offset++, particle, 1, 1);
  36427. this._appendParticleVertex(offset++, particle, 0, 1);
  36428. }
  36429. this._vertexBuffer.update(this._vertexData);
  36430. };
  36431. ParticleSystem.prototype.render = function () {
  36432. var effect = this._getEffect();
  36433. // Check
  36434. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  36435. return 0;
  36436. var engine = this._scene.getEngine();
  36437. // Render
  36438. engine.enableEffect(effect);
  36439. engine.setState(false);
  36440. var viewMatrix = this._scene.getViewMatrix();
  36441. effect.setTexture("diffuseSampler", this.particleTexture);
  36442. effect.setMatrix("view", viewMatrix);
  36443. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  36444. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  36445. if (this._scene.clipPlane) {
  36446. var clipPlane = this._scene.clipPlane;
  36447. var invView = viewMatrix.clone();
  36448. invView.invert();
  36449. effect.setMatrix("invView", invView);
  36450. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  36451. }
  36452. // VBOs
  36453. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  36454. // Draw order
  36455. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  36456. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  36457. }
  36458. else {
  36459. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  36460. }
  36461. if (this.forceDepthWrite) {
  36462. engine.setDepthWrite(true);
  36463. }
  36464. engine.draw(true, 0, this.particles.length * 6);
  36465. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  36466. return this.particles.length;
  36467. };
  36468. ParticleSystem.prototype.dispose = function () {
  36469. if (this._vertexBuffer) {
  36470. this._vertexBuffer.dispose();
  36471. this._vertexBuffer = null;
  36472. }
  36473. if (this._indexBuffer) {
  36474. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  36475. this._indexBuffer = null;
  36476. }
  36477. if (this.particleTexture) {
  36478. this.particleTexture.dispose();
  36479. this.particleTexture = null;
  36480. }
  36481. // Remove from scene
  36482. var index = this._scene.particleSystems.indexOf(this);
  36483. this._scene.particleSystems.splice(index, 1);
  36484. // Callback
  36485. this.onDisposeObservable.notifyObservers(this);
  36486. this.onDisposeObservable.clear();
  36487. };
  36488. // Clone
  36489. ParticleSystem.prototype.clone = function (name, newEmitter) {
  36490. var custom = null;
  36491. var program = null;
  36492. if (this.customShader != null) {
  36493. program = this.customShader;
  36494. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  36495. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  36496. }
  36497. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  36498. result.customShader = program;
  36499. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  36500. if (newEmitter === undefined) {
  36501. newEmitter = this.emitter;
  36502. }
  36503. result.emitter = newEmitter;
  36504. if (this.particleTexture) {
  36505. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  36506. }
  36507. if (!this.preventAutoStart) {
  36508. result.start();
  36509. }
  36510. return result;
  36511. };
  36512. ParticleSystem.prototype.serialize = function () {
  36513. var serializationObject = {};
  36514. serializationObject.name = this.name;
  36515. serializationObject.id = this.id;
  36516. // Emitter
  36517. if (this.emitter.position) {
  36518. serializationObject.emitterId = this.emitter.id;
  36519. }
  36520. else {
  36521. serializationObject.emitter = this.emitter.asArray();
  36522. }
  36523. serializationObject.capacity = this.getCapacity();
  36524. if (this.particleTexture) {
  36525. serializationObject.textureName = this.particleTexture.name;
  36526. }
  36527. // Animations
  36528. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  36529. // Particle system
  36530. serializationObject.minAngularSpeed = this.minAngularSpeed;
  36531. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  36532. serializationObject.minSize = this.minSize;
  36533. serializationObject.maxSize = this.maxSize;
  36534. serializationObject.minEmitPower = this.minEmitPower;
  36535. serializationObject.maxEmitPower = this.maxEmitPower;
  36536. serializationObject.minLifeTime = this.minLifeTime;
  36537. serializationObject.maxLifeTime = this.maxLifeTime;
  36538. serializationObject.emitRate = this.emitRate;
  36539. serializationObject.minEmitBox = this.minEmitBox.asArray();
  36540. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  36541. serializationObject.gravity = this.gravity.asArray();
  36542. serializationObject.direction1 = this.direction1.asArray();
  36543. serializationObject.direction2 = this.direction2.asArray();
  36544. serializationObject.color1 = this.color1.asArray();
  36545. serializationObject.color2 = this.color2.asArray();
  36546. serializationObject.colorDead = this.colorDead.asArray();
  36547. serializationObject.updateSpeed = this.updateSpeed;
  36548. serializationObject.targetStopDuration = this.targetStopDuration;
  36549. serializationObject.textureMask = this.textureMask.asArray();
  36550. serializationObject.blendMode = this.blendMode;
  36551. serializationObject.customShader = this.customShader;
  36552. serializationObject.preventAutoStart = this.preventAutoStart;
  36553. return serializationObject;
  36554. };
  36555. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  36556. var name = parsedParticleSystem.name;
  36557. var custom = null;
  36558. var program = null;
  36559. if (parsedParticleSystem.customShader) {
  36560. program = parsedParticleSystem.customShader;
  36561. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  36562. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  36563. }
  36564. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom);
  36565. particleSystem.customShader = program;
  36566. if (parsedParticleSystem.id) {
  36567. particleSystem.id = parsedParticleSystem.id;
  36568. }
  36569. // Auto start
  36570. if (parsedParticleSystem.preventAutoStart) {
  36571. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  36572. }
  36573. // Texture
  36574. if (parsedParticleSystem.textureName) {
  36575. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  36576. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  36577. }
  36578. // Emitter
  36579. if (parsedParticleSystem.emitterId) {
  36580. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  36581. }
  36582. else {
  36583. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  36584. }
  36585. // Animations
  36586. if (parsedParticleSystem.animations) {
  36587. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  36588. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  36589. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  36590. }
  36591. }
  36592. if (parsedParticleSystem.autoAnimate) {
  36593. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  36594. }
  36595. // Particle system
  36596. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  36597. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  36598. particleSystem.minSize = parsedParticleSystem.minSize;
  36599. particleSystem.maxSize = parsedParticleSystem.maxSize;
  36600. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  36601. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  36602. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  36603. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  36604. particleSystem.emitRate = parsedParticleSystem.emitRate;
  36605. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  36606. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  36607. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  36608. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  36609. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  36610. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  36611. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  36612. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  36613. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  36614. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  36615. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  36616. particleSystem.blendMode = parsedParticleSystem.blendMode;
  36617. if (!particleSystem.preventAutoStart) {
  36618. particleSystem.start();
  36619. }
  36620. return particleSystem;
  36621. };
  36622. return ParticleSystem;
  36623. }());
  36624. // Statics
  36625. ParticleSystem.BLENDMODE_ONEONE = 0;
  36626. ParticleSystem.BLENDMODE_STANDARD = 1;
  36627. BABYLON.ParticleSystem = ParticleSystem;
  36628. })(BABYLON || (BABYLON = {}));
  36629. //# sourceMappingURL=babylon.particleSystem.js.map
  36630. var BABYLON;
  36631. (function (BABYLON) {
  36632. var SolidParticle = (function () {
  36633. /**
  36634. * Creates a Solid Particle object.
  36635. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  36636. * `particleIndex` (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  36637. * `positionIndex` (integer) is the starting index of the particle vertices in the SPS "positions" array.
  36638. * `model` (ModelShape) is a reference to the model shape on what the particle is designed.
  36639. * `shapeId` (integer) is the model shape identifier in the SPS.
  36640. * `idxInShape` (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  36641. * `modelBoundingInfo` is the reference to the model BoundingInfo used for intersection computations.
  36642. */
  36643. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  36644. this.idx = 0; // particle global index
  36645. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); // color
  36646. this.position = BABYLON.Vector3.Zero(); // position
  36647. this.rotation = BABYLON.Vector3.Zero(); // rotation
  36648. this.scaling = new BABYLON.Vector3(1.0, 1.0, 1.0); // scaling
  36649. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0); // uvs
  36650. this.velocity = BABYLON.Vector3.Zero(); // velocity
  36651. this.alive = true; // alive
  36652. this.isVisible = true; // visibility
  36653. this._pos = 0; // index of this particle in the global "positions" array
  36654. this.shapeId = 0; // model shape id
  36655. this.idxInShape = 0; // index of the particle in its shape id
  36656. this.idx = particleIndex;
  36657. this._pos = positionIndex;
  36658. this._model = model;
  36659. this.shapeId = shapeId;
  36660. this.idxInShape = idxInShape;
  36661. this._sps = sps;
  36662. if (modelBoundingInfo) {
  36663. this._modelBoundingInfo = modelBoundingInfo;
  36664. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  36665. }
  36666. }
  36667. Object.defineProperty(SolidParticle.prototype, "scale", {
  36668. /**
  36669. * legacy support, changed scale to scaling
  36670. */
  36671. get: function () {
  36672. return this.scaling;
  36673. },
  36674. set: function (scale) {
  36675. this.scaling = scale;
  36676. },
  36677. enumerable: true,
  36678. configurable: true
  36679. });
  36680. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  36681. /**
  36682. * legacy support, changed quaternion to rotationQuaternion
  36683. */
  36684. get: function () {
  36685. return this.rotationQuaternion;
  36686. },
  36687. set: function (q) {
  36688. this.rotationQuaternion = q;
  36689. },
  36690. enumerable: true,
  36691. configurable: true
  36692. });
  36693. /**
  36694. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  36695. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  36696. * `target` is the object (solid particle or mesh) what the intersection is computed against.
  36697. */
  36698. SolidParticle.prototype.intersectsMesh = function (target) {
  36699. if (!this._boundingInfo || !target._boundingInfo) {
  36700. return false;
  36701. }
  36702. if (this._sps._bSphereOnly) {
  36703. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  36704. }
  36705. return this._boundingInfo.intersects(target._boundingInfo, false);
  36706. };
  36707. return SolidParticle;
  36708. }());
  36709. BABYLON.SolidParticle = SolidParticle;
  36710. var ModelShape = (function () {
  36711. /**
  36712. * 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.
  36713. * SPS internal tool, don't use it manually.
  36714. */
  36715. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  36716. this.shapeID = id;
  36717. this._shape = shape;
  36718. this._shapeUV = shapeUV;
  36719. this._positionFunction = posFunction;
  36720. this._vertexFunction = vtxFunction;
  36721. }
  36722. return ModelShape;
  36723. }());
  36724. BABYLON.ModelShape = ModelShape;
  36725. })(BABYLON || (BABYLON = {}));
  36726. //# sourceMappingURL=babylon.solidParticle.js.map
  36727. var BABYLON;
  36728. (function (BABYLON) {
  36729. /**
  36730. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  36731. */
  36732. var SolidParticleSystem = (function () {
  36733. /**
  36734. * Creates a SPS (Solid Particle System) object.
  36735. * `name` (String) is the SPS name, this will be the underlying mesh name.
  36736. * `scene` (Scene) is the scene in which the SPS is added.
  36737. * `updatable` (optional boolean, default true) : if the SPS must be updatable or immutable.
  36738. * `isPickable` (optional boolean, default false) : if the solid particles must be pickable.
  36739. * `particleIntersection` (optional boolean, default false) : if the solid particle intersections must be computed.
  36740. * `boundingSphereOnly` (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  36741. * `bSphereRadiusFactor` (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  36742. * Example : bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  36743. */
  36744. function SolidParticleSystem(name, scene, options) {
  36745. // public members
  36746. /**
  36747. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  36748. * Example : var p = SPS.particles[i];
  36749. */
  36750. this.particles = new Array();
  36751. /**
  36752. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  36753. */
  36754. this.nbParticles = 0;
  36755. /**
  36756. * If the particles must ever face the camera (default false). Useful for planar particles.
  36757. */
  36758. this.billboard = false;
  36759. /**
  36760. * Recompute normals when adding a shape
  36761. */
  36762. this.recomputeNormals = true;
  36763. /**
  36764. * This a counter ofr your own usage. It's not set by any SPS functions.
  36765. */
  36766. this.counter = 0;
  36767. /**
  36768. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  36769. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  36770. */
  36771. this.vars = {};
  36772. this._positions = new Array();
  36773. this._indices = new Array();
  36774. this._normals = new Array();
  36775. this._colors = new Array();
  36776. this._uvs = new Array();
  36777. this._index = 0; // indices index
  36778. this._updatable = true;
  36779. this._pickable = false;
  36780. this._isVisibilityBoxLocked = false;
  36781. this._alwaysVisible = false;
  36782. this._shapeCounter = 0;
  36783. this._copy = new BABYLON.SolidParticle(null, null, null, null, null, null);
  36784. this._color = new BABYLON.Color4(0, 0, 0, 0);
  36785. this._computeParticleColor = true;
  36786. this._computeParticleTexture = true;
  36787. this._computeParticleRotation = true;
  36788. this._computeParticleVertex = false;
  36789. this._computeBoundingBox = false;
  36790. this._cam_axisZ = BABYLON.Vector3.Zero();
  36791. this._cam_axisY = BABYLON.Vector3.Zero();
  36792. this._cam_axisX = BABYLON.Vector3.Zero();
  36793. this._axisX = BABYLON.Axis.X;
  36794. this._axisY = BABYLON.Axis.Y;
  36795. this._axisZ = BABYLON.Axis.Z;
  36796. this._camDir = BABYLON.Vector3.Zero();
  36797. this._rotMatrix = new BABYLON.Matrix();
  36798. this._invertMatrix = new BABYLON.Matrix();
  36799. this._rotated = BABYLON.Vector3.Zero();
  36800. this._quaternion = new BABYLON.Quaternion();
  36801. this._vertex = BABYLON.Vector3.Zero();
  36802. this._normal = BABYLON.Vector3.Zero();
  36803. this._yaw = 0.0;
  36804. this._pitch = 0.0;
  36805. this._roll = 0.0;
  36806. this._halfroll = 0.0;
  36807. this._halfpitch = 0.0;
  36808. this._halfyaw = 0.0;
  36809. this._sinRoll = 0.0;
  36810. this._cosRoll = 0.0;
  36811. this._sinPitch = 0.0;
  36812. this._cosPitch = 0.0;
  36813. this._sinYaw = 0.0;
  36814. this._cosYaw = 0.0;
  36815. this._w = 0.0;
  36816. this._mustUnrotateFixedNormals = false;
  36817. this._minimum = BABYLON.Tmp.Vector3[0];
  36818. this._maximum = BABYLON.Tmp.Vector3[1];
  36819. this._scale = BABYLON.Tmp.Vector3[2];
  36820. this._translation = BABYLON.Tmp.Vector3[3];
  36821. this._minBbox = BABYLON.Tmp.Vector3[4];
  36822. this._maxBbox = BABYLON.Tmp.Vector3[5];
  36823. this._particlesIntersect = false;
  36824. this._bSphereOnly = false;
  36825. this._bSphereRadiusFactor = 1.0;
  36826. this.name = name;
  36827. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  36828. this._camera = scene.activeCamera;
  36829. this._pickable = options ? options.isPickable : false;
  36830. this._particlesIntersect = options ? options.particleIntersection : false;
  36831. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  36832. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  36833. if (options && options.updatable) {
  36834. this._updatable = options.updatable;
  36835. }
  36836. else {
  36837. this._updatable = true;
  36838. }
  36839. if (this._pickable) {
  36840. this.pickedParticles = [];
  36841. }
  36842. }
  36843. /**
  36844. * Builds the SPS underlying mesh. Returns a standard Mesh.
  36845. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  36846. */
  36847. SolidParticleSystem.prototype.buildMesh = function () {
  36848. if (this.nbParticles === 0) {
  36849. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  36850. this.addShape(triangle, 1);
  36851. triangle.dispose();
  36852. }
  36853. this._positions32 = new Float32Array(this._positions);
  36854. this._uvs32 = new Float32Array(this._uvs);
  36855. this._colors32 = new Float32Array(this._colors);
  36856. if (this.recomputeNormals) {
  36857. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  36858. }
  36859. this._normals32 = new Float32Array(this._normals);
  36860. this._fixedNormal32 = new Float32Array(this._normals);
  36861. if (this._mustUnrotateFixedNormals) {
  36862. this._unrotateFixedNormals();
  36863. }
  36864. var vertexData = new BABYLON.VertexData();
  36865. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  36866. vertexData.indices = this._indices;
  36867. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  36868. if (this._uvs32) {
  36869. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  36870. ;
  36871. }
  36872. if (this._colors32) {
  36873. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  36874. }
  36875. var mesh = new BABYLON.Mesh(this.name, this._scene);
  36876. vertexData.applyToMesh(mesh, this._updatable);
  36877. this.mesh = mesh;
  36878. this.mesh.isPickable = this._pickable;
  36879. // free memory
  36880. this._positions = null;
  36881. this._normals = null;
  36882. this._uvs = null;
  36883. this._colors = null;
  36884. if (!this._updatable) {
  36885. this.particles.length = 0;
  36886. }
  36887. return mesh;
  36888. };
  36889. /**
  36890. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  36891. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  36892. * Thus the particles generated from `digest()` have their property `position` set yet.
  36893. * `mesh` ( Mesh ) is the mesh to be digested
  36894. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  36895. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  36896. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  36897. */
  36898. SolidParticleSystem.prototype.digest = function (mesh, options) {
  36899. var size = (options && options.facetNb) || 1;
  36900. var number = (options && options.number);
  36901. var delta = (options && options.delta) || 0;
  36902. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  36903. var meshInd = mesh.getIndices();
  36904. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  36905. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  36906. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  36907. var f = 0; // facet counter
  36908. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  36909. // compute size from number
  36910. if (number) {
  36911. number = (number > totalFacets) ? totalFacets : number;
  36912. size = Math.round(totalFacets / number);
  36913. delta = 0;
  36914. }
  36915. else {
  36916. size = (size > totalFacets) ? totalFacets : size;
  36917. }
  36918. var facetPos = []; // submesh positions
  36919. var facetInd = []; // submesh indices
  36920. var facetUV = []; // submesh UV
  36921. var facetCol = []; // submesh colors
  36922. var barycenter = BABYLON.Tmp.Vector3[0];
  36923. var rand;
  36924. var sizeO = size;
  36925. while (f < totalFacets) {
  36926. size = sizeO + Math.floor((1 + delta) * Math.random());
  36927. if (f > totalFacets - size) {
  36928. size = totalFacets - f;
  36929. }
  36930. // reset temp arrays
  36931. facetPos.length = 0;
  36932. facetInd.length = 0;
  36933. facetUV.length = 0;
  36934. facetCol.length = 0;
  36935. // iterate over "size" facets
  36936. var fi = 0;
  36937. for (var j = f * 3; j < (f + size) * 3; j++) {
  36938. facetInd.push(fi);
  36939. var i = meshInd[j];
  36940. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  36941. if (meshUV) {
  36942. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  36943. }
  36944. if (meshCol) {
  36945. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  36946. }
  36947. fi++;
  36948. }
  36949. // create a model shape for each single particle
  36950. var idx = this.nbParticles;
  36951. var shape = this._posToShape(facetPos);
  36952. var shapeUV = this._uvsToShapeUV(facetUV);
  36953. // compute the barycenter of the shape
  36954. var v;
  36955. for (v = 0; v < shape.length; v++) {
  36956. barycenter.addInPlace(shape[v]);
  36957. }
  36958. barycenter.scaleInPlace(1 / shape.length);
  36959. // shift the shape from its barycenter to the origin
  36960. for (v = 0; v < shape.length; v++) {
  36961. shape[v].subtractInPlace(barycenter);
  36962. }
  36963. var bInfo;
  36964. if (this._particlesIntersect) {
  36965. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  36966. }
  36967. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  36968. // add the particle in the SPS
  36969. var currentPos = this._positions.length;
  36970. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  36971. this._addParticle(idx, currentPos, modelShape, this._shapeCounter, 0, bInfo);
  36972. // initialize the particle position
  36973. this.particles[this.nbParticles].position.addInPlace(barycenter);
  36974. this._index += shape.length;
  36975. idx++;
  36976. this.nbParticles++;
  36977. this._shapeCounter++;
  36978. f += size;
  36979. }
  36980. return this;
  36981. };
  36982. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  36983. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  36984. var index = 0;
  36985. var idx = 0;
  36986. for (var p = 0; p < this.particles.length; p++) {
  36987. this._particle = this.particles[p];
  36988. this._shape = this._particle._model._shape;
  36989. if (this._particle.rotationQuaternion) {
  36990. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  36991. }
  36992. else {
  36993. this._yaw = this._particle.rotation.y;
  36994. this._pitch = this._particle.rotation.x;
  36995. this._roll = this._particle.rotation.z;
  36996. this._quaternionRotationYPR();
  36997. }
  36998. this._quaternionToRotationMatrix();
  36999. this._rotMatrix.invertToRef(this._invertMatrix);
  37000. for (var pt = 0; pt < this._shape.length; pt++) {
  37001. idx = index + pt * 3;
  37002. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  37003. this._fixedNormal32[idx] = this._normal.x;
  37004. this._fixedNormal32[idx + 1] = this._normal.y;
  37005. this._fixedNormal32[idx + 2] = this._normal.z;
  37006. }
  37007. index = idx + 3;
  37008. }
  37009. };
  37010. //reset copy
  37011. SolidParticleSystem.prototype._resetCopy = function () {
  37012. this._copy.position.x = 0;
  37013. this._copy.position.y = 0;
  37014. this._copy.position.z = 0;
  37015. this._copy.rotation.x = 0;
  37016. this._copy.rotation.y = 0;
  37017. this._copy.rotation.z = 0;
  37018. this._copy.rotationQuaternion = null;
  37019. this._copy.scaling.x = 1;
  37020. this._copy.scaling.y = 1;
  37021. this._copy.scaling.z = 1;
  37022. this._copy.uvs.x = 0;
  37023. this._copy.uvs.y = 0;
  37024. this._copy.uvs.z = 1;
  37025. this._copy.uvs.w = 1;
  37026. this._copy.color = null;
  37027. };
  37028. // _meshBuilder : inserts the shape model in the global SPS mesh
  37029. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  37030. var i;
  37031. var u = 0;
  37032. var c = 0;
  37033. var n = 0;
  37034. this._resetCopy();
  37035. if (options && options.positionFunction) {
  37036. options.positionFunction(this._copy, idx, idxInShape);
  37037. this._mustUnrotateFixedNormals = true;
  37038. }
  37039. if (this._copy.rotationQuaternion) {
  37040. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  37041. }
  37042. else {
  37043. this._yaw = this._copy.rotation.y;
  37044. this._pitch = this._copy.rotation.x;
  37045. this._roll = this._copy.rotation.z;
  37046. this._quaternionRotationYPR();
  37047. }
  37048. this._quaternionToRotationMatrix();
  37049. for (i = 0; i < shape.length; i++) {
  37050. this._vertex.x = shape[i].x;
  37051. this._vertex.y = shape[i].y;
  37052. this._vertex.z = shape[i].z;
  37053. if (options && options.vertexFunction) {
  37054. options.vertexFunction(this._copy, this._vertex, i);
  37055. }
  37056. this._vertex.x *= this._copy.scaling.x;
  37057. this._vertex.y *= this._copy.scaling.y;
  37058. this._vertex.z *= this._copy.scaling.z;
  37059. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  37060. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  37061. if (meshUV) {
  37062. 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);
  37063. u += 2;
  37064. }
  37065. if (this._copy.color) {
  37066. this._color = this._copy.color;
  37067. }
  37068. else if (meshCol && meshCol[c] !== undefined) {
  37069. this._color.r = meshCol[c];
  37070. this._color.g = meshCol[c + 1];
  37071. this._color.b = meshCol[c + 2];
  37072. this._color.a = meshCol[c + 3];
  37073. }
  37074. else {
  37075. this._color.r = 1;
  37076. this._color.g = 1;
  37077. this._color.b = 1;
  37078. this._color.a = 1;
  37079. }
  37080. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  37081. c += 4;
  37082. if (!this.recomputeNormals && meshNor) {
  37083. this._normal.x = meshNor[n];
  37084. this._normal.y = meshNor[n + 1];
  37085. this._normal.z = meshNor[n + 2];
  37086. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  37087. normals.push(this._normal.x, this._normal.y, this._normal.z);
  37088. n += 3;
  37089. }
  37090. }
  37091. for (i = 0; i < meshInd.length; i++) {
  37092. indices.push(p + meshInd[i]);
  37093. }
  37094. if (this._pickable) {
  37095. var nbfaces = meshInd.length / 3;
  37096. for (i = 0; i < nbfaces; i++) {
  37097. this.pickedParticles.push({ idx: idx, faceId: i });
  37098. }
  37099. }
  37100. return this._copy;
  37101. };
  37102. // returns a shape array from positions array
  37103. SolidParticleSystem.prototype._posToShape = function (positions) {
  37104. var shape = [];
  37105. for (var i = 0; i < positions.length; i += 3) {
  37106. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  37107. }
  37108. return shape;
  37109. };
  37110. // returns a shapeUV array from a Vector4 uvs
  37111. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  37112. var shapeUV = [];
  37113. if (uvs) {
  37114. for (var i = 0; i < uvs.length; i++)
  37115. shapeUV.push(uvs[i]);
  37116. }
  37117. return shapeUV;
  37118. };
  37119. // adds a new particle object in the particles array
  37120. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape, bInfo) {
  37121. var sp = new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape, this, bInfo);
  37122. this.particles.push(sp);
  37123. return sp;
  37124. };
  37125. /**
  37126. * Adds some particles to the SPS from the model shape. Returns the shape id.
  37127. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  37128. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  37129. * `nb` (positive integer) the number of particles to be created from this model
  37130. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  37131. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  37132. */
  37133. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  37134. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37135. var meshInd = mesh.getIndices();
  37136. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37137. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  37138. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  37139. var bbInfo;
  37140. if (this._particlesIntersect) {
  37141. bbInfo = mesh.getBoundingInfo();
  37142. }
  37143. var shape = this._posToShape(meshPos);
  37144. var shapeUV = this._uvsToShapeUV(meshUV);
  37145. var posfunc = options ? options.positionFunction : null;
  37146. var vtxfunc = options ? options.vertexFunction : null;
  37147. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  37148. // particles
  37149. var sp;
  37150. var currentCopy;
  37151. var idx = this.nbParticles;
  37152. for (var i = 0; i < nb; i++) {
  37153. var currentPos = this._positions.length;
  37154. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  37155. if (this._updatable) {
  37156. sp = this._addParticle(idx, currentPos, modelShape, this._shapeCounter, i, bbInfo);
  37157. sp.position.copyFrom(currentCopy.position);
  37158. sp.rotation.copyFrom(currentCopy.rotation);
  37159. if (currentCopy.rotationQuaternion) {
  37160. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  37161. }
  37162. if (currentCopy.color) {
  37163. sp.color.copyFrom(currentCopy.color);
  37164. }
  37165. sp.scaling.copyFrom(currentCopy.scaling);
  37166. sp.uvs.copyFrom(currentCopy.uvs);
  37167. }
  37168. this._index += shape.length;
  37169. idx++;
  37170. }
  37171. this.nbParticles += nb;
  37172. this._shapeCounter++;
  37173. return this._shapeCounter - 1;
  37174. };
  37175. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  37176. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  37177. this._resetCopy();
  37178. if (particle._model._positionFunction) {
  37179. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  37180. }
  37181. if (this._copy.rotationQuaternion) {
  37182. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  37183. }
  37184. else {
  37185. this._yaw = this._copy.rotation.y;
  37186. this._pitch = this._copy.rotation.x;
  37187. this._roll = this._copy.rotation.z;
  37188. this._quaternionRotationYPR();
  37189. }
  37190. this._quaternionToRotationMatrix();
  37191. this._shape = particle._model._shape;
  37192. for (var pt = 0; pt < this._shape.length; pt++) {
  37193. this._vertex.x = this._shape[pt].x;
  37194. this._vertex.y = this._shape[pt].y;
  37195. this._vertex.z = this._shape[pt].z;
  37196. if (particle._model._vertexFunction) {
  37197. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  37198. }
  37199. this._vertex.x *= this._copy.scaling.x;
  37200. this._vertex.y *= this._copy.scaling.y;
  37201. this._vertex.z *= this._copy.scaling.z;
  37202. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  37203. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  37204. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  37205. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  37206. }
  37207. particle.position.x = 0.0;
  37208. particle.position.y = 0.0;
  37209. particle.position.z = 0.0;
  37210. particle.rotation.x = 0.0;
  37211. particle.rotation.y = 0.0;
  37212. particle.rotation.z = 0.0;
  37213. particle.rotationQuaternion = null;
  37214. particle.scaling.x = 1.0;
  37215. particle.scaling.y = 1.0;
  37216. particle.scaling.z = 1.0;
  37217. };
  37218. /**
  37219. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  37220. * Returns the SPS.
  37221. */
  37222. SolidParticleSystem.prototype.rebuildMesh = function () {
  37223. for (var p = 0; p < this.particles.length; p++) {
  37224. this._rebuildParticle(this.particles[p]);
  37225. }
  37226. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  37227. return this;
  37228. };
  37229. /**
  37230. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  37231. * This method calls `updateParticle()` for each particle of the SPS.
  37232. * For an animated SPS, it is usually called within the render loop.
  37233. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  37234. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  37235. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  37236. * Returns the SPS.
  37237. */
  37238. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  37239. if (start === void 0) { start = 0; }
  37240. if (end === void 0) { end = this.nbParticles - 1; }
  37241. if (update === void 0) { update = true; }
  37242. if (!this._updatable) {
  37243. return;
  37244. }
  37245. // custom beforeUpdate
  37246. this.beforeUpdateParticles(start, end, update);
  37247. this._cam_axisX.x = 1.0;
  37248. this._cam_axisX.y = 0.0;
  37249. this._cam_axisX.z = 0.0;
  37250. this._cam_axisY.x = 0.0;
  37251. this._cam_axisY.y = 1.0;
  37252. this._cam_axisY.z = 0.0;
  37253. this._cam_axisZ.x = 0.0;
  37254. this._cam_axisZ.y = 0.0;
  37255. this._cam_axisZ.z = 1.0;
  37256. // if the particles will always face the camera
  37257. if (this.billboard) {
  37258. this.mesh.computeWorldMatrix(true);
  37259. // compute the camera position and un-rotate it by the current mesh rotation
  37260. if (this.mesh._worldMatrix.decompose(this._scale, this._quaternion, this._translation)) {
  37261. this._quaternionToRotationMatrix();
  37262. this._rotMatrix.invertToRef(this._invertMatrix);
  37263. this._camera._currentTarget.subtractToRef(this._camera.globalPosition, this._camDir);
  37264. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  37265. this._cam_axisZ.normalize();
  37266. // same for camera up vector extracted from the cam view matrix
  37267. var view = this._camera.getViewMatrix(true);
  37268. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  37269. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  37270. this._cam_axisY.normalize();
  37271. this._cam_axisX.normalize();
  37272. }
  37273. }
  37274. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  37275. var idx = 0; // current position index in the global array positions32
  37276. var index = 0; // position start index in the global array positions32 of the current particle
  37277. var colidx = 0; // current color index in the global array colors32
  37278. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  37279. var uvidx = 0; // current uv index in the global array uvs32
  37280. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  37281. var pt = 0; // current index in the particle model shape
  37282. if (this.mesh.isFacetDataEnabled) {
  37283. this._computeBoundingBox = true;
  37284. }
  37285. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  37286. if (this._computeBoundingBox) {
  37287. if (start == 0 && end == this.nbParticles - 1) {
  37288. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  37289. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  37290. }
  37291. else {
  37292. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  37293. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  37294. }
  37295. }
  37296. // particle loop
  37297. index = this.particles[start]._pos;
  37298. var vpos = (index / 3) | 0;
  37299. colorIndex = vpos * 4;
  37300. uvIndex = vpos * 2;
  37301. for (var p = start; p <= end; p++) {
  37302. this._particle = this.particles[p];
  37303. this._shape = this._particle._model._shape;
  37304. this._shapeUV = this._particle._model._shapeUV;
  37305. // call to custom user function to update the particle properties
  37306. this.updateParticle(this._particle);
  37307. if (this._particle.isVisible) {
  37308. // particle rotation matrix
  37309. if (this.billboard) {
  37310. this._particle.rotation.x = 0.0;
  37311. this._particle.rotation.y = 0.0;
  37312. }
  37313. if (this._computeParticleRotation || this.billboard) {
  37314. if (this._particle.rotationQuaternion) {
  37315. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  37316. }
  37317. else {
  37318. this._yaw = this._particle.rotation.y;
  37319. this._pitch = this._particle.rotation.x;
  37320. this._roll = this._particle.rotation.z;
  37321. this._quaternionRotationYPR();
  37322. }
  37323. this._quaternionToRotationMatrix();
  37324. }
  37325. // particle vertex loop
  37326. for (pt = 0; pt < this._shape.length; pt++) {
  37327. idx = index + pt * 3;
  37328. colidx = colorIndex + pt * 4;
  37329. uvidx = uvIndex + pt * 2;
  37330. this._vertex.x = this._shape[pt].x;
  37331. this._vertex.y = this._shape[pt].y;
  37332. this._vertex.z = this._shape[pt].z;
  37333. if (this._computeParticleVertex) {
  37334. this.updateParticleVertex(this._particle, this._vertex, pt);
  37335. }
  37336. // positions
  37337. this._vertex.x *= this._particle.scaling.x;
  37338. this._vertex.y *= this._particle.scaling.y;
  37339. this._vertex.z *= this._particle.scaling.z;
  37340. 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];
  37341. 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;
  37342. 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;
  37343. 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;
  37344. 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;
  37345. 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;
  37346. 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;
  37347. if (this._computeBoundingBox) {
  37348. if (this._positions32[idx] < this._minimum.x) {
  37349. this._minimum.x = this._positions32[idx];
  37350. }
  37351. if (this._positions32[idx] > this._maximum.x) {
  37352. this._maximum.x = this._positions32[idx];
  37353. }
  37354. if (this._positions32[idx + 1] < this._minimum.y) {
  37355. this._minimum.y = this._positions32[idx + 1];
  37356. }
  37357. if (this._positions32[idx + 1] > this._maximum.y) {
  37358. this._maximum.y = this._positions32[idx + 1];
  37359. }
  37360. if (this._positions32[idx + 2] < this._minimum.z) {
  37361. this._minimum.z = this._positions32[idx + 2];
  37362. }
  37363. if (this._positions32[idx + 2] > this._maximum.z) {
  37364. this._maximum.z = this._positions32[idx + 2];
  37365. }
  37366. }
  37367. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  37368. if (!this._computeParticleVertex) {
  37369. this._normal.x = this._fixedNormal32[idx];
  37370. this._normal.y = this._fixedNormal32[idx + 1];
  37371. this._normal.z = this._fixedNormal32[idx + 2];
  37372. 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]);
  37373. 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]);
  37374. 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]);
  37375. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  37376. 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;
  37377. 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;
  37378. }
  37379. if (this._computeParticleColor) {
  37380. this._colors32[colidx] = this._particle.color.r;
  37381. this._colors32[colidx + 1] = this._particle.color.g;
  37382. this._colors32[colidx + 2] = this._particle.color.b;
  37383. this._colors32[colidx + 3] = this._particle.color.a;
  37384. }
  37385. if (this._computeParticleTexture) {
  37386. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  37387. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  37388. }
  37389. }
  37390. }
  37391. else {
  37392. for (pt = 0; pt < this._shape.length; pt++) {
  37393. idx = index + pt * 3;
  37394. colidx = colorIndex + pt * 4;
  37395. uvidx = uvIndex + pt * 2;
  37396. this._positions32[idx] = this._camera.position.x;
  37397. this._positions32[idx + 1] = this._camera.position.y;
  37398. this._positions32[idx + 2] = this._camera.position.z;
  37399. this._normals32[idx] = 0.0;
  37400. this._normals32[idx + 1] = 0.0;
  37401. this._normals32[idx + 2] = 0.0;
  37402. if (this._computeParticleColor) {
  37403. this._colors32[colidx] = this._particle.color.r;
  37404. this._colors32[colidx + 1] = this._particle.color.g;
  37405. this._colors32[colidx + 2] = this._particle.color.b;
  37406. this._colors32[colidx + 3] = this._particle.color.a;
  37407. }
  37408. if (this._computeParticleTexture) {
  37409. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  37410. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  37411. }
  37412. }
  37413. }
  37414. // if the particle intersections must be computed : update the bbInfo
  37415. if (this._particlesIntersect) {
  37416. var bInfo = this._particle._boundingInfo;
  37417. var bBox = bInfo.boundingBox;
  37418. var bSphere = bInfo.boundingSphere;
  37419. if (!this._bSphereOnly) {
  37420. // place, scale and rotate the particle bbox within the SPS local system, then update it
  37421. for (var b = 0; b < bBox.vectors.length; b++) {
  37422. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  37423. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  37424. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  37425. 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];
  37426. 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;
  37427. 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;
  37428. 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;
  37429. 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;
  37430. 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;
  37431. 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;
  37432. }
  37433. bBox._update(this.mesh._worldMatrix);
  37434. }
  37435. // place and scale the particle bouding sphere in the SPS local system, then update it
  37436. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  37437. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  37438. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  37439. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  37440. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  37441. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  37442. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  37443. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  37444. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  37445. 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));
  37446. bSphere._update(this.mesh._worldMatrix);
  37447. }
  37448. // increment indexes for the next particle
  37449. index = idx + 3;
  37450. colorIndex = colidx + 4;
  37451. uvIndex = uvidx + 2;
  37452. }
  37453. // if the VBO must be updated
  37454. if (update) {
  37455. if (this._computeParticleColor) {
  37456. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  37457. }
  37458. if (this._computeParticleTexture) {
  37459. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  37460. }
  37461. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  37462. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  37463. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  37464. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  37465. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  37466. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32, params);
  37467. for (var i = 0; i < this._normals32.length; i++) {
  37468. this._fixedNormal32[i] = this._normals32[i];
  37469. }
  37470. }
  37471. if (!this.mesh.areNormalsFrozen) {
  37472. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  37473. }
  37474. }
  37475. }
  37476. if (this._computeBoundingBox) {
  37477. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  37478. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  37479. }
  37480. this.afterUpdateParticles(start, end, update);
  37481. return this;
  37482. };
  37483. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  37484. this._halfroll = this._roll * 0.5;
  37485. this._halfpitch = this._pitch * 0.5;
  37486. this._halfyaw = this._yaw * 0.5;
  37487. this._sinRoll = Math.sin(this._halfroll);
  37488. this._cosRoll = Math.cos(this._halfroll);
  37489. this._sinPitch = Math.sin(this._halfpitch);
  37490. this._cosPitch = Math.cos(this._halfpitch);
  37491. this._sinYaw = Math.sin(this._halfyaw);
  37492. this._cosYaw = Math.cos(this._halfyaw);
  37493. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  37494. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  37495. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  37496. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  37497. };
  37498. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  37499. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  37500. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  37501. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  37502. this._rotMatrix.m[3] = 0;
  37503. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  37504. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  37505. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  37506. this._rotMatrix.m[7] = 0;
  37507. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  37508. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  37509. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  37510. this._rotMatrix.m[11] = 0;
  37511. this._rotMatrix.m[12] = 0;
  37512. this._rotMatrix.m[13] = 0;
  37513. this._rotMatrix.m[14] = 0;
  37514. this._rotMatrix.m[15] = 1.0;
  37515. };
  37516. /**
  37517. * Disposes the SPS.
  37518. * Returns nothing.
  37519. */
  37520. SolidParticleSystem.prototype.dispose = function () {
  37521. this.mesh.dispose();
  37522. this.vars = null;
  37523. // drop references to internal big arrays for the GC
  37524. this._positions = null;
  37525. this._indices = null;
  37526. this._normals = null;
  37527. this._uvs = null;
  37528. this._colors = null;
  37529. this._positions32 = null;
  37530. this._normals32 = null;
  37531. this._fixedNormal32 = null;
  37532. this._uvs32 = null;
  37533. this._colors32 = null;
  37534. this.pickedParticles = null;
  37535. };
  37536. /**
  37537. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  37538. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  37539. * Returns the SPS.
  37540. */
  37541. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  37542. if (!this._isVisibilityBoxLocked) {
  37543. this.mesh.refreshBoundingInfo();
  37544. }
  37545. return this;
  37546. };
  37547. /**
  37548. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  37549. * @param size the size (float) of the visibility box
  37550. * note : this doesn't lock the SPS mesh bounding box.
  37551. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  37552. */
  37553. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  37554. var vis = size / 2;
  37555. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  37556. };
  37557. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  37558. // getter and setter
  37559. get: function () {
  37560. return this._alwaysVisible;
  37561. },
  37562. /**
  37563. * Sets the SPS as always visible or not
  37564. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  37565. */
  37566. set: function (val) {
  37567. this._alwaysVisible = val;
  37568. this.mesh.alwaysSelectAsActiveMesh = val;
  37569. },
  37570. enumerable: true,
  37571. configurable: true
  37572. });
  37573. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  37574. get: function () {
  37575. return this._isVisibilityBoxLocked;
  37576. },
  37577. /**
  37578. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  37579. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  37580. */
  37581. set: function (val) {
  37582. this._isVisibilityBoxLocked = val;
  37583. this.mesh.getBoundingInfo().isLocked = val;
  37584. },
  37585. enumerable: true,
  37586. configurable: true
  37587. });
  37588. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  37589. // getters
  37590. get: function () {
  37591. return this._computeParticleRotation;
  37592. },
  37593. // Optimizer setters
  37594. /**
  37595. * Tells to `setParticles()` to compute the particle rotations or not.
  37596. * Default value : true. The SPS is faster when it's set to false.
  37597. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  37598. */
  37599. set: function (val) {
  37600. this._computeParticleRotation = val;
  37601. },
  37602. enumerable: true,
  37603. configurable: true
  37604. });
  37605. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  37606. get: function () {
  37607. return this._computeParticleColor;
  37608. },
  37609. /**
  37610. * Tells to `setParticles()` to compute the particle colors or not.
  37611. * Default value : true. The SPS is faster when it's set to false.
  37612. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  37613. */
  37614. set: function (val) {
  37615. this._computeParticleColor = val;
  37616. },
  37617. enumerable: true,
  37618. configurable: true
  37619. });
  37620. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  37621. get: function () {
  37622. return this._computeParticleTexture;
  37623. },
  37624. /**
  37625. * Tells to `setParticles()` to compute the particle textures or not.
  37626. * Default value : true. The SPS is faster when it's set to false.
  37627. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  37628. */
  37629. set: function (val) {
  37630. this._computeParticleTexture = val;
  37631. },
  37632. enumerable: true,
  37633. configurable: true
  37634. });
  37635. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  37636. get: function () {
  37637. return this._computeParticleVertex;
  37638. },
  37639. /**
  37640. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  37641. * Default value : false. The SPS is faster when it's set to false.
  37642. * Note : the particle custom vertex positions aren't stored values.
  37643. */
  37644. set: function (val) {
  37645. this._computeParticleVertex = val;
  37646. },
  37647. enumerable: true,
  37648. configurable: true
  37649. });
  37650. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  37651. get: function () {
  37652. return this._computeBoundingBox;
  37653. },
  37654. /**
  37655. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  37656. */
  37657. set: function (val) {
  37658. this._computeBoundingBox = val;
  37659. },
  37660. enumerable: true,
  37661. configurable: true
  37662. });
  37663. // =======================================================================
  37664. // Particle behavior logic
  37665. // these following methods may be overwritten by the user to fit his needs
  37666. /**
  37667. * This function does nothing. It may be overwritten to set all the particle first values.
  37668. * The SPS doesn't call this function, you may have to call it by your own.
  37669. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  37670. */
  37671. SolidParticleSystem.prototype.initParticles = function () {
  37672. };
  37673. /**
  37674. * This function does nothing. It may be overwritten to recycle a particle.
  37675. * The SPS doesn't call this function, you may have to call it by your own.
  37676. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  37677. */
  37678. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  37679. return particle;
  37680. };
  37681. /**
  37682. * Updates a particle : this function should be overwritten by the user.
  37683. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  37684. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  37685. * ex : just set a particle position or velocity and recycle conditions
  37686. */
  37687. SolidParticleSystem.prototype.updateParticle = function (particle) {
  37688. return particle;
  37689. };
  37690. /**
  37691. * Updates a vertex of a particle : it can be overwritten by the user.
  37692. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  37693. * @param particle the current particle
  37694. * @param vertex the current index of the current particle
  37695. * @param pt the index of the current vertex in the particle shape
  37696. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  37697. * ex : just set a vertex particle position
  37698. */
  37699. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  37700. return vertex;
  37701. };
  37702. /**
  37703. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  37704. * This does nothing and may be overwritten by the user.
  37705. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  37706. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  37707. * @param update the boolean update value actually passed to setParticles()
  37708. */
  37709. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  37710. };
  37711. /**
  37712. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  37713. * This will be passed three parameters.
  37714. * This does nothing and may be overwritten by the user.
  37715. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  37716. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  37717. * @param update the boolean update value actually passed to setParticles()
  37718. */
  37719. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  37720. };
  37721. return SolidParticleSystem;
  37722. }());
  37723. BABYLON.SolidParticleSystem = SolidParticleSystem;
  37724. })(BABYLON || (BABYLON = {}));
  37725. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  37726. /// <reference path="babylon.mesh.ts" />
  37727. var BABYLON;
  37728. (function (BABYLON) {
  37729. var GroundMesh = (function (_super) {
  37730. __extends(GroundMesh, _super);
  37731. function GroundMesh(name, scene) {
  37732. var _this = _super.call(this, name, scene) || this;
  37733. _this.generateOctree = false;
  37734. _this._worldInverse = new BABYLON.Matrix();
  37735. return _this;
  37736. }
  37737. GroundMesh.prototype.getClassName = function () {
  37738. return "GroundMesh";
  37739. };
  37740. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  37741. get: function () {
  37742. return Math.min(this._subdivisionsX, this._subdivisionsY);
  37743. },
  37744. enumerable: true,
  37745. configurable: true
  37746. });
  37747. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  37748. get: function () {
  37749. return this._subdivisionsX;
  37750. },
  37751. enumerable: true,
  37752. configurable: true
  37753. });
  37754. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  37755. get: function () {
  37756. return this._subdivisionsY;
  37757. },
  37758. enumerable: true,
  37759. configurable: true
  37760. });
  37761. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  37762. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  37763. this._subdivisionsX = chunksCount;
  37764. this._subdivisionsY = chunksCount;
  37765. this.subdivide(chunksCount);
  37766. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  37767. };
  37768. /**
  37769. * Returns a height (y) value in the Worl system :
  37770. * the ground altitude at the coordinates (x, z) expressed in the World system.
  37771. * Returns the ground y position if (x, z) are outside the ground surface.
  37772. */
  37773. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  37774. var world = this.getWorldMatrix();
  37775. var invMat = BABYLON.Tmp.Matrix[5];
  37776. world.invertToRef(invMat);
  37777. var tmpVect = BABYLON.Tmp.Vector3[8];
  37778. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  37779. x = tmpVect.x;
  37780. z = tmpVect.z;
  37781. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  37782. return this.position.y;
  37783. }
  37784. if (!this._heightQuads || this._heightQuads.length == 0) {
  37785. this._initHeightQuads();
  37786. this._computeHeightQuads();
  37787. }
  37788. var facet = this._getFacetAt(x, z);
  37789. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  37790. // return y in the World system
  37791. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  37792. return tmpVect.y;
  37793. };
  37794. /**
  37795. * Returns a normalized vector (Vector3) orthogonal to the ground
  37796. * at the ground coordinates (x, z) expressed in the World system.
  37797. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  37798. */
  37799. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  37800. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  37801. this.getNormalAtCoordinatesToRef(x, z, normal);
  37802. return normal;
  37803. };
  37804. /**
  37805. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  37806. * at the ground coordinates (x, z) expressed in the World system.
  37807. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  37808. * Returns the GroundMesh.
  37809. */
  37810. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  37811. var world = this.getWorldMatrix();
  37812. var tmpMat = BABYLON.Tmp.Matrix[5];
  37813. world.invertToRef(tmpMat);
  37814. var tmpVect = BABYLON.Tmp.Vector3[8];
  37815. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  37816. x = tmpVect.x;
  37817. z = tmpVect.z;
  37818. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  37819. return this;
  37820. }
  37821. if (!this._heightQuads || this._heightQuads.length == 0) {
  37822. this._initHeightQuads();
  37823. this._computeHeightQuads();
  37824. }
  37825. var facet = this._getFacetAt(x, z);
  37826. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  37827. return this;
  37828. };
  37829. /**
  37830. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  37831. * if the ground has been updated.
  37832. * This can be used in the render loop.
  37833. * Returns the GroundMesh.
  37834. */
  37835. GroundMesh.prototype.updateCoordinateHeights = function () {
  37836. if (!this._heightQuads || this._heightQuads.length == 0) {
  37837. this._initHeightQuads();
  37838. }
  37839. this._computeHeightQuads();
  37840. return this;
  37841. };
  37842. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  37843. GroundMesh.prototype._getFacetAt = function (x, z) {
  37844. // retrieve col and row from x, z coordinates in the ground local system
  37845. var subdivisionsX = this._subdivisionsX;
  37846. var subdivisionsY = this._subdivisionsY;
  37847. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  37848. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  37849. var quad = this._heightQuads[row * this._subdivisionsX + col];
  37850. var facet;
  37851. if (z < quad.slope.x * x + quad.slope.y) {
  37852. facet = quad.facet1;
  37853. }
  37854. else {
  37855. facet = quad.facet2;
  37856. }
  37857. return facet;
  37858. };
  37859. // Creates and populates the heightMap array with "facet" elements :
  37860. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  37861. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  37862. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  37863. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  37864. // Returns the GroundMesh.
  37865. GroundMesh.prototype._initHeightQuads = function () {
  37866. var subdivisionsX = this._subdivisionsX;
  37867. var subdivisionsY = this._subdivisionsY;
  37868. this._heightQuads = new Array();
  37869. for (var row = 0; row < subdivisionsY; row++) {
  37870. for (var col = 0; col < subdivisionsX; col++) {
  37871. 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) };
  37872. this._heightQuads[row * subdivisionsX + col] = quad;
  37873. }
  37874. }
  37875. return this;
  37876. };
  37877. // Compute each quad element values and update the the heightMap array :
  37878. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  37879. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  37880. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  37881. // Returns the GroundMesh.
  37882. GroundMesh.prototype._computeHeightQuads = function () {
  37883. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37884. var v1 = BABYLON.Tmp.Vector3[3];
  37885. var v2 = BABYLON.Tmp.Vector3[2];
  37886. var v3 = BABYLON.Tmp.Vector3[1];
  37887. var v4 = BABYLON.Tmp.Vector3[0];
  37888. var v1v2 = BABYLON.Tmp.Vector3[4];
  37889. var v1v3 = BABYLON.Tmp.Vector3[5];
  37890. var v1v4 = BABYLON.Tmp.Vector3[6];
  37891. var norm1 = BABYLON.Tmp.Vector3[7];
  37892. var norm2 = BABYLON.Tmp.Vector3[8];
  37893. var i = 0;
  37894. var j = 0;
  37895. var k = 0;
  37896. var cd = 0; // 2D slope coefficient : z = cd * x + h
  37897. var h = 0;
  37898. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  37899. var d2 = 0;
  37900. var subdivisionsX = this._subdivisionsX;
  37901. var subdivisionsY = this._subdivisionsY;
  37902. for (var row = 0; row < subdivisionsY; row++) {
  37903. for (var col = 0; col < subdivisionsX; col++) {
  37904. i = col * 3;
  37905. j = row * (subdivisionsX + 1) * 3;
  37906. k = (row + 1) * (subdivisionsX + 1) * 3;
  37907. v1.x = positions[j + i];
  37908. v1.y = positions[j + i + 1];
  37909. v1.z = positions[j + i + 2];
  37910. v2.x = positions[j + i + 3];
  37911. v2.y = positions[j + i + 4];
  37912. v2.z = positions[j + i + 5];
  37913. v3.x = positions[k + i];
  37914. v3.y = positions[k + i + 1];
  37915. v3.z = positions[k + i + 2];
  37916. v4.x = positions[k + i + 3];
  37917. v4.y = positions[k + i + 4];
  37918. v4.z = positions[k + i + 5];
  37919. // 2D slope V1V4
  37920. cd = (v4.z - v1.z) / (v4.x - v1.x);
  37921. h = v1.z - cd * v1.x; // v1 belongs to the slope
  37922. // facet equations :
  37923. // we compute each facet normal vector
  37924. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  37925. // we compute the value d by applying the equation to v1 which belongs to the plane
  37926. // then we store the facet equation in a Vector4
  37927. v2.subtractToRef(v1, v1v2);
  37928. v3.subtractToRef(v1, v1v3);
  37929. v4.subtractToRef(v1, v1v4);
  37930. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  37931. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  37932. norm1.normalize();
  37933. norm2.normalize();
  37934. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  37935. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  37936. var quad = this._heightQuads[row * subdivisionsX + col];
  37937. quad.slope.copyFromFloats(cd, h);
  37938. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  37939. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  37940. }
  37941. }
  37942. return this;
  37943. };
  37944. GroundMesh.prototype.serialize = function (serializationObject) {
  37945. _super.prototype.serialize.call(this, serializationObject);
  37946. serializationObject.subdivisionsX = this._subdivisionsX;
  37947. serializationObject.subdivisionsY = this._subdivisionsY;
  37948. serializationObject.minX = this._minX;
  37949. serializationObject.maxX = this._maxX;
  37950. serializationObject.minZ = this._minZ;
  37951. serializationObject.maxZ = this._maxZ;
  37952. serializationObject.width = this._width;
  37953. serializationObject.height = this._height;
  37954. };
  37955. GroundMesh.Parse = function (parsedMesh, scene) {
  37956. var result = new GroundMesh(parsedMesh.name, scene);
  37957. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  37958. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  37959. result._minX = parsedMesh.minX;
  37960. result._maxX = parsedMesh.maxX;
  37961. result._minZ = parsedMesh.minZ;
  37962. result._maxZ = parsedMesh.maxZ;
  37963. result._width = parsedMesh.width;
  37964. result._height = parsedMesh.height;
  37965. return result;
  37966. };
  37967. return GroundMesh;
  37968. }(BABYLON.Mesh));
  37969. BABYLON.GroundMesh = GroundMesh;
  37970. })(BABYLON || (BABYLON = {}));
  37971. //# sourceMappingURL=babylon.groundMesh.js.map
  37972. var BABYLON;
  37973. (function (BABYLON) {
  37974. /**
  37975. * Creates an instance based on a source mesh.
  37976. */
  37977. var InstancedMesh = (function (_super) {
  37978. __extends(InstancedMesh, _super);
  37979. function InstancedMesh(name, source) {
  37980. var _this = _super.call(this, name, source.getScene()) || this;
  37981. source.instances.push(_this);
  37982. _this._sourceMesh = source;
  37983. _this.position.copyFrom(source.position);
  37984. _this.rotation.copyFrom(source.rotation);
  37985. _this.scaling.copyFrom(source.scaling);
  37986. if (source.rotationQuaternion) {
  37987. _this.rotationQuaternion = source.rotationQuaternion.clone();
  37988. }
  37989. _this.infiniteDistance = source.infiniteDistance;
  37990. _this.setPivotMatrix(source.getPivotMatrix());
  37991. _this.refreshBoundingInfo();
  37992. _this._syncSubMeshes();
  37993. return _this;
  37994. }
  37995. /**
  37996. * Returns the string "InstancedMesh".
  37997. */
  37998. InstancedMesh.prototype.getClassName = function () {
  37999. return "InstancedMesh";
  38000. };
  38001. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  38002. // Methods
  38003. get: function () {
  38004. return this._sourceMesh.receiveShadows;
  38005. },
  38006. enumerable: true,
  38007. configurable: true
  38008. });
  38009. Object.defineProperty(InstancedMesh.prototype, "material", {
  38010. get: function () {
  38011. return this._sourceMesh.material;
  38012. },
  38013. enumerable: true,
  38014. configurable: true
  38015. });
  38016. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  38017. get: function () {
  38018. return this._sourceMesh.visibility;
  38019. },
  38020. enumerable: true,
  38021. configurable: true
  38022. });
  38023. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  38024. get: function () {
  38025. return this._sourceMesh.skeleton;
  38026. },
  38027. enumerable: true,
  38028. configurable: true
  38029. });
  38030. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  38031. get: function () {
  38032. return this._sourceMesh.renderingGroupId;
  38033. },
  38034. enumerable: true,
  38035. configurable: true
  38036. });
  38037. /**
  38038. * Returns the total number of vertices (integer).
  38039. */
  38040. InstancedMesh.prototype.getTotalVertices = function () {
  38041. return this._sourceMesh.getTotalVertices();
  38042. };
  38043. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  38044. get: function () {
  38045. return this._sourceMesh;
  38046. },
  38047. enumerable: true,
  38048. configurable: true
  38049. });
  38050. /**
  38051. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  38052. */
  38053. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  38054. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  38055. };
  38056. /**
  38057. * Sets the vertex data of the mesh geometry for the requested `kind`.
  38058. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  38059. * The `data` are either a numeric array either a Float32Array.
  38060. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  38061. * 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).
  38062. * Note that a new underlying VertexBuffer object is created each call.
  38063. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  38064. *
  38065. * Possible `kind` values :
  38066. * - BABYLON.VertexBuffer.PositionKind
  38067. * - BABYLON.VertexBuffer.UVKind
  38068. * - BABYLON.VertexBuffer.UV2Kind
  38069. * - BABYLON.VertexBuffer.UV3Kind
  38070. * - BABYLON.VertexBuffer.UV4Kind
  38071. * - BABYLON.VertexBuffer.UV5Kind
  38072. * - BABYLON.VertexBuffer.UV6Kind
  38073. * - BABYLON.VertexBuffer.ColorKind
  38074. * - BABYLON.VertexBuffer.MatricesIndicesKind
  38075. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  38076. * - BABYLON.VertexBuffer.MatricesWeightsKind
  38077. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  38078. *
  38079. * Returns the Mesh.
  38080. */
  38081. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  38082. if (this.sourceMesh) {
  38083. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  38084. }
  38085. return this.sourceMesh;
  38086. };
  38087. /**
  38088. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  38089. * If the mesh has no geometry, it is simply returned as it is.
  38090. * The `data` are either a numeric array either a Float32Array.
  38091. * No new underlying VertexBuffer object is created.
  38092. * 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.
  38093. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  38094. *
  38095. * Possible `kind` values :
  38096. * - BABYLON.VertexBuffer.PositionKind
  38097. * - BABYLON.VertexBuffer.UVKind
  38098. * - BABYLON.VertexBuffer.UV2Kind
  38099. * - BABYLON.VertexBuffer.UV3Kind
  38100. * - BABYLON.VertexBuffer.UV4Kind
  38101. * - BABYLON.VertexBuffer.UV5Kind
  38102. * - BABYLON.VertexBuffer.UV6Kind
  38103. * - BABYLON.VertexBuffer.ColorKind
  38104. * - BABYLON.VertexBuffer.MatricesIndicesKind
  38105. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  38106. * - BABYLON.VertexBuffer.MatricesWeightsKind
  38107. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  38108. *
  38109. * Returns the Mesh.
  38110. */
  38111. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  38112. if (this.sourceMesh) {
  38113. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  38114. }
  38115. return this.sourceMesh;
  38116. };
  38117. /**
  38118. * Sets the mesh indices.
  38119. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  38120. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  38121. * This method creates a new index buffer each call.
  38122. * Returns the Mesh.
  38123. */
  38124. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  38125. if (this.sourceMesh) {
  38126. this.sourceMesh.setIndices(indices, totalVertices);
  38127. }
  38128. return this.sourceMesh;
  38129. };
  38130. /**
  38131. * Boolean : True if the mesh owns the requested kind of data.
  38132. */
  38133. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  38134. return this._sourceMesh.isVerticesDataPresent(kind);
  38135. };
  38136. /**
  38137. * Returns an array of indices (IndicesArray).
  38138. */
  38139. InstancedMesh.prototype.getIndices = function () {
  38140. return this._sourceMesh.getIndices();
  38141. };
  38142. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  38143. get: function () {
  38144. return this._sourceMesh._positions;
  38145. },
  38146. enumerable: true,
  38147. configurable: true
  38148. });
  38149. /**
  38150. * Sets a new updated BoundingInfo to the mesh.
  38151. * Returns the mesh.
  38152. */
  38153. InstancedMesh.prototype.refreshBoundingInfo = function () {
  38154. var meshBB = this._sourceMesh.getBoundingInfo();
  38155. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  38156. this._updateBoundingInfo();
  38157. return this;
  38158. };
  38159. InstancedMesh.prototype._preActivate = function () {
  38160. if (this._currentLOD) {
  38161. this._currentLOD._preActivate();
  38162. }
  38163. return this;
  38164. };
  38165. InstancedMesh.prototype._activate = function (renderId) {
  38166. if (this._currentLOD) {
  38167. this._currentLOD._registerInstanceForRenderId(this, renderId);
  38168. }
  38169. return this;
  38170. };
  38171. /**
  38172. * Returns the current associated LOD AbstractMesh.
  38173. */
  38174. InstancedMesh.prototype.getLOD = function (camera) {
  38175. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  38176. if (this._currentLOD === this.sourceMesh) {
  38177. return this;
  38178. }
  38179. return this._currentLOD;
  38180. };
  38181. InstancedMesh.prototype._syncSubMeshes = function () {
  38182. this.releaseSubMeshes();
  38183. if (this._sourceMesh.subMeshes) {
  38184. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  38185. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  38186. }
  38187. }
  38188. return this;
  38189. };
  38190. InstancedMesh.prototype._generatePointsArray = function () {
  38191. return this._sourceMesh._generatePointsArray();
  38192. };
  38193. /**
  38194. * Creates a new InstancedMesh from the current mesh.
  38195. * - name (string) : the cloned mesh name
  38196. * - newParent (optional Node) : the optional Node to parent the clone to.
  38197. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  38198. *
  38199. * Returns the clone.
  38200. */
  38201. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  38202. var result = this._sourceMesh.createInstance(name);
  38203. // Deep copy
  38204. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  38205. // Bounding info
  38206. this.refreshBoundingInfo();
  38207. // Parent
  38208. if (newParent) {
  38209. result.parent = newParent;
  38210. }
  38211. if (!doNotCloneChildren) {
  38212. // Children
  38213. for (var index = 0; index < this.getScene().meshes.length; index++) {
  38214. var mesh = this.getScene().meshes[index];
  38215. if (mesh.parent === this) {
  38216. mesh.clone(mesh.name, result);
  38217. }
  38218. }
  38219. }
  38220. result.computeWorldMatrix(true);
  38221. return result;
  38222. };
  38223. /**
  38224. * Disposes the InstancedMesh.
  38225. * Returns nothing.
  38226. */
  38227. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  38228. // Remove from mesh
  38229. var index = this._sourceMesh.instances.indexOf(this);
  38230. this._sourceMesh.instances.splice(index, 1);
  38231. _super.prototype.dispose.call(this, doNotRecurse);
  38232. };
  38233. return InstancedMesh;
  38234. }(BABYLON.AbstractMesh));
  38235. BABYLON.InstancedMesh = InstancedMesh;
  38236. })(BABYLON || (BABYLON = {}));
  38237. //# sourceMappingURL=babylon.instancedMesh.js.map
  38238. /// <reference path="babylon.mesh.ts" />
  38239. var BABYLON;
  38240. (function (BABYLON) {
  38241. var LinesMesh = (function (_super) {
  38242. __extends(LinesMesh, _super);
  38243. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor) {
  38244. if (parent === void 0) { parent = null; }
  38245. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  38246. _this.useVertexColor = useVertexColor;
  38247. _this.color = new BABYLON.Color3(1, 1, 1);
  38248. _this.alpha = 1;
  38249. if (source) {
  38250. _this.color = source.color.clone();
  38251. _this.alpha = source.alpha;
  38252. _this.useVertexColor = source.useVertexColor;
  38253. }
  38254. _this._intersectionThreshold = 0.1;
  38255. var options = {
  38256. attributes: [BABYLON.VertexBuffer.PositionKind],
  38257. uniforms: ["world", "viewProjection"],
  38258. needAlphaBlending: false,
  38259. };
  38260. if (!useVertexColor) {
  38261. options.uniforms.push("color");
  38262. options.needAlphaBlending = true;
  38263. }
  38264. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", options);
  38265. return _this;
  38266. }
  38267. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  38268. /**
  38269. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  38270. * This margin is expressed in world space coordinates, so its value may vary.
  38271. * Default value is 0.1
  38272. * @returns the intersection Threshold value.
  38273. */
  38274. get: function () {
  38275. return this._intersectionThreshold;
  38276. },
  38277. /**
  38278. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  38279. * This margin is expressed in world space coordinates, so its value may vary.
  38280. * @param value the new threshold to apply
  38281. */
  38282. set: function (value) {
  38283. if (this._intersectionThreshold === value) {
  38284. return;
  38285. }
  38286. this._intersectionThreshold = value;
  38287. if (this.geometry) {
  38288. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  38289. }
  38290. },
  38291. enumerable: true,
  38292. configurable: true
  38293. });
  38294. /**
  38295. * Returns the string "LineMesh"
  38296. */
  38297. LinesMesh.prototype.getClassName = function () {
  38298. return "LinesMesh";
  38299. };
  38300. Object.defineProperty(LinesMesh.prototype, "material", {
  38301. get: function () {
  38302. return this._colorShader;
  38303. },
  38304. enumerable: true,
  38305. configurable: true
  38306. });
  38307. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  38308. get: function () {
  38309. return false;
  38310. },
  38311. enumerable: true,
  38312. configurable: true
  38313. });
  38314. LinesMesh.prototype.createInstance = function (name) {
  38315. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  38316. return null;
  38317. };
  38318. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  38319. // VBOs
  38320. this._geometry._bind(this._colorShader.getEffect());
  38321. // Color
  38322. if (!this.useVertexColor) {
  38323. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  38324. }
  38325. return this;
  38326. };
  38327. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  38328. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  38329. return this;
  38330. }
  38331. var engine = this.getScene().getEngine();
  38332. // Draw order
  38333. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  38334. return this;
  38335. };
  38336. LinesMesh.prototype.dispose = function (doNotRecurse) {
  38337. this._colorShader.dispose();
  38338. _super.prototype.dispose.call(this, doNotRecurse);
  38339. };
  38340. /**
  38341. * Returns a new LineMesh object cloned from the current one.
  38342. */
  38343. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  38344. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  38345. };
  38346. return LinesMesh;
  38347. }(BABYLON.Mesh));
  38348. BABYLON.LinesMesh = LinesMesh;
  38349. })(BABYLON || (BABYLON = {}));
  38350. //# sourceMappingURL=babylon.linesMesh.js.map
  38351. var BABYLON;
  38352. (function (BABYLON) {
  38353. var ShaderMaterial = (function (_super) {
  38354. __extends(ShaderMaterial, _super);
  38355. function ShaderMaterial(name, scene, shaderPath, options) {
  38356. var _this = _super.call(this, name, scene) || this;
  38357. _this._textures = {};
  38358. _this._textureArrays = {};
  38359. _this._floats = {};
  38360. _this._floatsArrays = {};
  38361. _this._colors3 = {};
  38362. _this._colors4 = {};
  38363. _this._vectors2 = {};
  38364. _this._vectors3 = {};
  38365. _this._vectors4 = {};
  38366. _this._matrices = {};
  38367. _this._matrices3x3 = {};
  38368. _this._matrices2x2 = {};
  38369. _this._vectors3Arrays = {};
  38370. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  38371. _this._shaderPath = shaderPath;
  38372. options.needAlphaBlending = options.needAlphaBlending || false;
  38373. options.needAlphaTesting = options.needAlphaTesting || false;
  38374. options.attributes = options.attributes || ["position", "normal", "uv"];
  38375. options.uniforms = options.uniforms || ["worldViewProjection"];
  38376. options.uniformBuffers = options.uniformBuffers || [];
  38377. options.samplers = options.samplers || [];
  38378. options.defines = options.defines || [];
  38379. _this._options = options;
  38380. return _this;
  38381. }
  38382. ShaderMaterial.prototype.getClassName = function () {
  38383. return "ShaderMaterial";
  38384. };
  38385. ShaderMaterial.prototype.needAlphaBlending = function () {
  38386. return this._options.needAlphaBlending;
  38387. };
  38388. ShaderMaterial.prototype.needAlphaTesting = function () {
  38389. return this._options.needAlphaTesting;
  38390. };
  38391. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  38392. if (this._options.uniforms.indexOf(uniformName) === -1) {
  38393. this._options.uniforms.push(uniformName);
  38394. }
  38395. };
  38396. ShaderMaterial.prototype.setTexture = function (name, texture) {
  38397. if (this._options.samplers.indexOf(name) === -1) {
  38398. this._options.samplers.push(name);
  38399. }
  38400. this._textures[name] = texture;
  38401. return this;
  38402. };
  38403. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  38404. if (this._options.samplers.indexOf(name) === -1) {
  38405. this._options.samplers.push(name);
  38406. }
  38407. this._checkUniform(name);
  38408. this._textureArrays[name] = textures;
  38409. return this;
  38410. };
  38411. ShaderMaterial.prototype.setFloat = function (name, value) {
  38412. this._checkUniform(name);
  38413. this._floats[name] = value;
  38414. return this;
  38415. };
  38416. ShaderMaterial.prototype.setFloats = function (name, value) {
  38417. this._checkUniform(name);
  38418. this._floatsArrays[name] = value;
  38419. return this;
  38420. };
  38421. ShaderMaterial.prototype.setColor3 = function (name, value) {
  38422. this._checkUniform(name);
  38423. this._colors3[name] = value;
  38424. return this;
  38425. };
  38426. ShaderMaterial.prototype.setColor4 = function (name, value) {
  38427. this._checkUniform(name);
  38428. this._colors4[name] = value;
  38429. return this;
  38430. };
  38431. ShaderMaterial.prototype.setVector2 = function (name, value) {
  38432. this._checkUniform(name);
  38433. this._vectors2[name] = value;
  38434. return this;
  38435. };
  38436. ShaderMaterial.prototype.setVector3 = function (name, value) {
  38437. this._checkUniform(name);
  38438. this._vectors3[name] = value;
  38439. return this;
  38440. };
  38441. ShaderMaterial.prototype.setVector4 = function (name, value) {
  38442. this._checkUniform(name);
  38443. this._vectors4[name] = value;
  38444. return this;
  38445. };
  38446. ShaderMaterial.prototype.setMatrix = function (name, value) {
  38447. this._checkUniform(name);
  38448. this._matrices[name] = value;
  38449. return this;
  38450. };
  38451. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  38452. this._checkUniform(name);
  38453. this._matrices3x3[name] = value;
  38454. return this;
  38455. };
  38456. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  38457. this._checkUniform(name);
  38458. this._matrices2x2[name] = value;
  38459. return this;
  38460. };
  38461. ShaderMaterial.prototype.setArray3 = function (name, value) {
  38462. this._checkUniform(name);
  38463. this._vectors3Arrays[name] = value;
  38464. return this;
  38465. };
  38466. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  38467. if (!mesh) {
  38468. return true;
  38469. }
  38470. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  38471. return false;
  38472. }
  38473. return false;
  38474. };
  38475. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  38476. var scene = this.getScene();
  38477. var engine = scene.getEngine();
  38478. if (!this.checkReadyOnEveryCall) {
  38479. if (this._renderId === scene.getRenderId()) {
  38480. if (this._checkCache(scene, mesh, useInstances)) {
  38481. return true;
  38482. }
  38483. }
  38484. }
  38485. // Instances
  38486. var defines = [];
  38487. var attribs = [];
  38488. var fallbacks = new BABYLON.EffectFallbacks();
  38489. if (useInstances) {
  38490. defines.push("#define INSTANCES");
  38491. }
  38492. for (var index = 0; index < this._options.defines.length; index++) {
  38493. defines.push(this._options.defines[index]);
  38494. }
  38495. for (var index = 0; index < this._options.attributes.length; index++) {
  38496. attribs.push(this._options.attributes[index]);
  38497. }
  38498. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  38499. attribs.push(BABYLON.VertexBuffer.ColorKind);
  38500. defines.push("#define VERTEXCOLOR");
  38501. }
  38502. // Bones
  38503. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  38504. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  38505. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  38506. if (mesh.numBoneInfluencers > 4) {
  38507. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  38508. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  38509. }
  38510. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  38511. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  38512. fallbacks.addCPUSkinningFallback(0, mesh);
  38513. }
  38514. else {
  38515. defines.push("#define NUM_BONE_INFLUENCERS 0");
  38516. }
  38517. // Textures
  38518. for (var name in this._textures) {
  38519. if (!this._textures[name].isReady()) {
  38520. return false;
  38521. }
  38522. }
  38523. // Alpha test
  38524. if (engine.getAlphaTesting()) {
  38525. defines.push("#define ALPHATEST");
  38526. }
  38527. var previousEffect = this._effect;
  38528. var join = defines.join("\n");
  38529. this._effect = engine.createEffect(this._shaderPath, {
  38530. attributes: attribs,
  38531. uniformsNames: this._options.uniforms,
  38532. uniformBuffersNames: this._options.uniformBuffers,
  38533. samplers: this._options.samplers,
  38534. defines: join,
  38535. fallbacks: fallbacks,
  38536. onCompiled: this.onCompiled,
  38537. onError: this.onError
  38538. }, engine);
  38539. if (!this._effect.isReady()) {
  38540. return false;
  38541. }
  38542. if (previousEffect !== this._effect) {
  38543. scene.resetCachedMaterial();
  38544. }
  38545. this._renderId = scene.getRenderId();
  38546. return true;
  38547. };
  38548. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  38549. var scene = this.getScene();
  38550. if (this._options.uniforms.indexOf("world") !== -1) {
  38551. this._effect.setMatrix("world", world);
  38552. }
  38553. if (this._options.uniforms.indexOf("worldView") !== -1) {
  38554. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  38555. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  38556. }
  38557. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  38558. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  38559. }
  38560. };
  38561. ShaderMaterial.prototype.bind = function (world, mesh) {
  38562. // Std values
  38563. this.bindOnlyWorldMatrix(world);
  38564. if (this.getScene().getCachedMaterial() !== this) {
  38565. if (this._options.uniforms.indexOf("view") !== -1) {
  38566. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  38567. }
  38568. if (this._options.uniforms.indexOf("projection") !== -1) {
  38569. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  38570. }
  38571. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  38572. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  38573. }
  38574. // Bones
  38575. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  38576. var name;
  38577. // Texture
  38578. for (name in this._textures) {
  38579. this._effect.setTexture(name, this._textures[name]);
  38580. }
  38581. // Texture arrays
  38582. for (name in this._textureArrays) {
  38583. this._effect.setTextureArray(name, this._textureArrays[name]);
  38584. }
  38585. // Float
  38586. for (name in this._floats) {
  38587. this._effect.setFloat(name, this._floats[name]);
  38588. }
  38589. // Float s
  38590. for (name in this._floatsArrays) {
  38591. this._effect.setArray(name, this._floatsArrays[name]);
  38592. }
  38593. // Color3
  38594. for (name in this._colors3) {
  38595. this._effect.setColor3(name, this._colors3[name]);
  38596. }
  38597. // Color4
  38598. for (name in this._colors4) {
  38599. var color = this._colors4[name];
  38600. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  38601. }
  38602. // Vector2
  38603. for (name in this._vectors2) {
  38604. this._effect.setVector2(name, this._vectors2[name]);
  38605. }
  38606. // Vector3
  38607. for (name in this._vectors3) {
  38608. this._effect.setVector3(name, this._vectors3[name]);
  38609. }
  38610. // Vector4
  38611. for (name in this._vectors4) {
  38612. this._effect.setVector4(name, this._vectors4[name]);
  38613. }
  38614. // Matrix
  38615. for (name in this._matrices) {
  38616. this._effect.setMatrix(name, this._matrices[name]);
  38617. }
  38618. // Matrix 3x3
  38619. for (name in this._matrices3x3) {
  38620. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  38621. }
  38622. // Matrix 2x2
  38623. for (name in this._matrices2x2) {
  38624. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  38625. }
  38626. // Vector3Array
  38627. for (name in this._vectors3Arrays) {
  38628. this._effect.setArray3(name, this._vectors3Arrays[name]);
  38629. }
  38630. }
  38631. this._afterBind(mesh);
  38632. };
  38633. ShaderMaterial.prototype.clone = function (name) {
  38634. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  38635. return newShaderMaterial;
  38636. };
  38637. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  38638. if (forceDisposeTextures) {
  38639. var name;
  38640. for (name in this._textures) {
  38641. this._textures[name].dispose();
  38642. }
  38643. for (name in this._textureArrays) {
  38644. var array = this._textureArrays[name];
  38645. for (var index = 0; index < array.length; index++) {
  38646. array[index].dispose();
  38647. }
  38648. }
  38649. }
  38650. this._textures = {};
  38651. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  38652. };
  38653. ShaderMaterial.prototype.serialize = function () {
  38654. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  38655. serializationObject.customType = "BABYLON.ShaderMaterial";
  38656. serializationObject.options = this._options;
  38657. serializationObject.shaderPath = this._shaderPath;
  38658. var name;
  38659. // Texture
  38660. serializationObject.textures = {};
  38661. for (name in this._textures) {
  38662. serializationObject.textures[name] = this._textures[name].serialize();
  38663. }
  38664. // Texture arrays
  38665. serializationObject.textureArrays = {};
  38666. for (name in this._textureArrays) {
  38667. serializationObject.textureArrays[name] = [];
  38668. var array = this._textureArrays[name];
  38669. for (var index = 0; index < array.length; index++) {
  38670. serializationObject.textureArrays[name].push(array[index].serialize());
  38671. }
  38672. }
  38673. // Float
  38674. serializationObject.floats = {};
  38675. for (name in this._floats) {
  38676. serializationObject.floats[name] = this._floats[name];
  38677. }
  38678. // Float s
  38679. serializationObject.floatArrays = {};
  38680. for (name in this._floatsArrays) {
  38681. serializationObject.floatArrays[name] = this._floatsArrays[name];
  38682. }
  38683. // Color3
  38684. serializationObject.colors3 = {};
  38685. for (name in this._colors3) {
  38686. serializationObject.colors3[name] = this._colors3[name].asArray();
  38687. }
  38688. // Color4
  38689. serializationObject.colors4 = {};
  38690. for (name in this._colors4) {
  38691. serializationObject.colors4[name] = this._colors4[name].asArray();
  38692. }
  38693. // Vector2
  38694. serializationObject.vectors2 = {};
  38695. for (name in this._vectors2) {
  38696. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  38697. }
  38698. // Vector3
  38699. serializationObject.vectors3 = {};
  38700. for (name in this._vectors3) {
  38701. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  38702. }
  38703. // Vector4
  38704. serializationObject.vectors4 = {};
  38705. for (name in this._vectors4) {
  38706. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  38707. }
  38708. // Matrix
  38709. serializationObject.matrices = {};
  38710. for (name in this._matrices) {
  38711. serializationObject.matrices[name] = this._matrices[name].asArray();
  38712. }
  38713. // Matrix 3x3
  38714. serializationObject.matrices3x3 = {};
  38715. for (name in this._matrices3x3) {
  38716. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  38717. }
  38718. // Matrix 2x2
  38719. serializationObject.matrices2x2 = {};
  38720. for (name in this._matrices2x2) {
  38721. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  38722. }
  38723. // Vector3Array
  38724. serializationObject.vectors3Arrays = {};
  38725. for (name in this._vectors3Arrays) {
  38726. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  38727. }
  38728. return serializationObject;
  38729. };
  38730. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  38731. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  38732. var name;
  38733. // Texture
  38734. for (name in source.textures) {
  38735. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  38736. }
  38737. // Texture arrays
  38738. for (name in source.textureArrays) {
  38739. var array = source.textureArrays[name];
  38740. var textureArray = new Array();
  38741. for (var index = 0; index < array.length; index++) {
  38742. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  38743. }
  38744. material.setTextureArray(name, textureArray);
  38745. }
  38746. // Float
  38747. for (name in source.floats) {
  38748. material.setFloat(name, source.floats[name]);
  38749. }
  38750. // Float s
  38751. for (name in source.floatsArrays) {
  38752. material.setFloats(name, source.floatsArrays[name]);
  38753. }
  38754. // Color3
  38755. for (name in source.colors3) {
  38756. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  38757. }
  38758. // Color4
  38759. for (name in source.colors4) {
  38760. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  38761. }
  38762. // Vector2
  38763. for (name in source.vectors2) {
  38764. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  38765. }
  38766. // Vector3
  38767. for (name in source.vectors3) {
  38768. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  38769. }
  38770. // Vector4
  38771. for (name in source.vectors4) {
  38772. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  38773. }
  38774. // Matrix
  38775. for (name in source.matrices) {
  38776. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  38777. }
  38778. // Matrix 3x3
  38779. for (name in source.matrices3x3) {
  38780. material.setMatrix3x3(name, source.matrices3x3[name]);
  38781. }
  38782. // Matrix 2x2
  38783. for (name in source.matrices2x2) {
  38784. material.setMatrix2x2(name, source.matrices2x2[name]);
  38785. }
  38786. // Vector3Array
  38787. for (name in source.vectors3Arrays) {
  38788. material.setArray3(name, source.vectors3Arrays[name]);
  38789. }
  38790. return material;
  38791. };
  38792. return ShaderMaterial;
  38793. }(BABYLON.Material));
  38794. BABYLON.ShaderMaterial = ShaderMaterial;
  38795. })(BABYLON || (BABYLON = {}));
  38796. //# sourceMappingURL=babylon.shaderMaterial.js.map
  38797. var BABYLON;
  38798. (function (BABYLON) {
  38799. var MeshBuilder = (function () {
  38800. function MeshBuilder() {
  38801. }
  38802. MeshBuilder.updateSideOrientation = function (orientation, scene) {
  38803. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  38804. return BABYLON.Mesh.DOUBLESIDE;
  38805. }
  38806. if (orientation === undefined || orientation === null) {
  38807. return BABYLON.Mesh.FRONTSIDE;
  38808. }
  38809. return orientation;
  38810. };
  38811. /**
  38812. * Creates a box mesh.
  38813. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  38814. * The parameter `size` sets the size (float) of each box side (default 1).
  38815. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  38816. * 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).
  38817. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  38818. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38819. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  38820. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  38821. */
  38822. MeshBuilder.CreateBox = function (name, options, scene) {
  38823. var box = new BABYLON.Mesh(name, scene);
  38824. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  38825. box.sideOrientation = options.sideOrientation;
  38826. var vertexData = BABYLON.VertexData.CreateBox(options);
  38827. vertexData.applyToMesh(box, options.updatable);
  38828. return box;
  38829. };
  38830. /**
  38831. * Creates a sphere mesh.
  38832. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  38833. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  38834. * 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`).
  38835. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  38836. * 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
  38837. * 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).
  38838. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38839. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  38840. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  38841. */
  38842. MeshBuilder.CreateSphere = function (name, options, scene) {
  38843. var sphere = new BABYLON.Mesh(name, scene);
  38844. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  38845. sphere.sideOrientation = options.sideOrientation;
  38846. var vertexData = BABYLON.VertexData.CreateSphere(options);
  38847. vertexData.applyToMesh(sphere, options.updatable);
  38848. return sphere;
  38849. };
  38850. /**
  38851. * Creates a plane polygonal mesh. By default, this is a disc.
  38852. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  38853. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  38854. * 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.
  38855. * 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
  38856. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38857. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  38858. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  38859. */
  38860. MeshBuilder.CreateDisc = function (name, options, scene) {
  38861. var disc = new BABYLON.Mesh(name, scene);
  38862. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  38863. disc.sideOrientation = options.sideOrientation;
  38864. var vertexData = BABYLON.VertexData.CreateDisc(options);
  38865. vertexData.applyToMesh(disc, options.updatable);
  38866. return disc;
  38867. };
  38868. /**
  38869. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  38870. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  38871. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  38872. * 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`).
  38873. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  38874. * 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.
  38875. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38876. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  38877. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  38878. */
  38879. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  38880. var sphere = new BABYLON.Mesh(name, scene);
  38881. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  38882. sphere.sideOrientation = options.sideOrientation;
  38883. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  38884. vertexData.applyToMesh(sphere, options.updatable);
  38885. return sphere;
  38886. };
  38887. ;
  38888. /**
  38889. * Creates a ribbon mesh.
  38890. * 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.
  38891. *
  38892. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  38893. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  38894. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  38895. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  38896. * 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.
  38897. * 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.
  38898. * 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
  38899. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38900. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  38901. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  38902. * 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.
  38903. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  38904. * 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
  38905. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  38906. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  38907. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  38908. */
  38909. MeshBuilder.CreateRibbon = function (name, options, scene) {
  38910. var pathArray = options.pathArray;
  38911. var closeArray = options.closeArray;
  38912. var closePath = options.closePath;
  38913. var offset = options.offset;
  38914. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  38915. var instance = options.instance;
  38916. var updatable = options.updatable;
  38917. if (instance) {
  38918. // positionFunction : ribbon case
  38919. // only pathArray and sideOrientation parameters are taken into account for positions update
  38920. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  38921. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  38922. var positionFunction = function (positions) {
  38923. var minlg = pathArray[0].length;
  38924. var i = 0;
  38925. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  38926. for (var si = 1; si <= ns; si++) {
  38927. for (var p = 0; p < pathArray.length; p++) {
  38928. var path = pathArray[p];
  38929. var l = path.length;
  38930. minlg = (minlg < l) ? minlg : l;
  38931. var j = 0;
  38932. while (j < minlg) {
  38933. positions[i] = path[j].x;
  38934. positions[i + 1] = path[j].y;
  38935. positions[i + 2] = path[j].z;
  38936. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  38937. BABYLON.Tmp.Vector3[0].x = path[j].x;
  38938. }
  38939. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  38940. BABYLON.Tmp.Vector3[1].x = path[j].x;
  38941. }
  38942. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  38943. BABYLON.Tmp.Vector3[0].y = path[j].y;
  38944. }
  38945. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  38946. BABYLON.Tmp.Vector3[1].y = path[j].y;
  38947. }
  38948. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  38949. BABYLON.Tmp.Vector3[0].z = path[j].z;
  38950. }
  38951. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  38952. BABYLON.Tmp.Vector3[1].z = path[j].z;
  38953. }
  38954. j++;
  38955. i += 3;
  38956. }
  38957. if (instance._closePath) {
  38958. positions[i] = path[0].x;
  38959. positions[i + 1] = path[0].y;
  38960. positions[i + 2] = path[0].z;
  38961. i += 3;
  38962. }
  38963. }
  38964. }
  38965. };
  38966. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38967. positionFunction(positions);
  38968. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  38969. instance._boundingInfo.update(instance._worldMatrix);
  38970. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  38971. if (options.colors) {
  38972. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  38973. for (var c = 0; c < options.colors.length; c++) {
  38974. colors[c * 4] = options.colors[c].r;
  38975. colors[c * 4 + 1] = options.colors[c].g;
  38976. colors[c * 4 + 2] = options.colors[c].b;
  38977. colors[c * 4 + 3] = options.colors[c].a;
  38978. }
  38979. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  38980. }
  38981. if (options.uvs) {
  38982. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  38983. for (var i = 0; i < options.uvs.length; i++) {
  38984. uvs[i * 2] = options.uvs[i].x;
  38985. uvs[i * 2 + 1] = options.uvs[i].y;
  38986. }
  38987. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  38988. }
  38989. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  38990. var indices = instance.getIndices();
  38991. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  38992. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  38993. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  38994. if (instance._closePath) {
  38995. var indexFirst = 0;
  38996. var indexLast = 0;
  38997. for (var p = 0; p < pathArray.length; p++) {
  38998. indexFirst = instance._idx[p] * 3;
  38999. if (p + 1 < pathArray.length) {
  39000. indexLast = (instance._idx[p + 1] - 1) * 3;
  39001. }
  39002. else {
  39003. indexLast = normals.length - 3;
  39004. }
  39005. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  39006. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  39007. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  39008. normals[indexLast] = normals[indexFirst];
  39009. normals[indexLast + 1] = normals[indexFirst + 1];
  39010. normals[indexLast + 2] = normals[indexFirst + 2];
  39011. }
  39012. }
  39013. if (!(instance.areNormalsFrozen)) {
  39014. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  39015. }
  39016. }
  39017. return instance;
  39018. }
  39019. else {
  39020. var ribbon = new BABYLON.Mesh(name, scene);
  39021. ribbon.sideOrientation = sideOrientation;
  39022. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  39023. if (closePath) {
  39024. ribbon._idx = vertexData._idx;
  39025. }
  39026. ribbon._closePath = closePath;
  39027. ribbon._closeArray = closeArray;
  39028. vertexData.applyToMesh(ribbon, updatable);
  39029. return ribbon;
  39030. }
  39031. };
  39032. /**
  39033. * Creates a cylinder or a cone mesh.
  39034. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  39035. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  39036. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  39037. * 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.
  39038. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  39039. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  39040. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  39041. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  39042. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  39043. * 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).
  39044. * 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
  39045. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  39046. * 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
  39047. * 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.
  39048. * If `enclose` is false, a ring surface is one element.
  39049. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  39050. * 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
  39051. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39052. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39053. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39054. */
  39055. MeshBuilder.CreateCylinder = function (name, options, scene) {
  39056. var cylinder = new BABYLON.Mesh(name, scene);
  39057. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39058. cylinder.sideOrientation = options.sideOrientation;
  39059. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  39060. vertexData.applyToMesh(cylinder, options.updatable);
  39061. return cylinder;
  39062. };
  39063. /**
  39064. * Creates a torus mesh.
  39065. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  39066. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  39067. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  39068. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  39069. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39070. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39071. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39072. */
  39073. MeshBuilder.CreateTorus = function (name, options, scene) {
  39074. var torus = new BABYLON.Mesh(name, scene);
  39075. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39076. torus.sideOrientation = options.sideOrientation;
  39077. var vertexData = BABYLON.VertexData.CreateTorus(options);
  39078. vertexData.applyToMesh(torus, options.updatable);
  39079. return torus;
  39080. };
  39081. /**
  39082. * Creates a torus knot mesh.
  39083. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  39084. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  39085. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  39086. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  39087. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  39088. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39089. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39090. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39091. */
  39092. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  39093. var torusKnot = new BABYLON.Mesh(name, scene);
  39094. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39095. torusKnot.sideOrientation = options.sideOrientation;
  39096. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  39097. vertexData.applyToMesh(torusKnot, options.updatable);
  39098. return torusKnot;
  39099. };
  39100. /**
  39101. * Creates a line system mesh.
  39102. * A line system is a pool of many lines gathered in a single mesh.
  39103. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  39104. * 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.
  39105. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  39106. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  39107. * 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
  39108. * 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
  39109. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  39110. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39111. */
  39112. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  39113. var instance = options.instance;
  39114. var lines = options.lines;
  39115. if (instance) {
  39116. var positionFunction = function (positions) {
  39117. var i = 0;
  39118. for (var l = 0; l < lines.length; l++) {
  39119. var points = lines[l];
  39120. for (var p = 0; p < points.length; p++) {
  39121. positions[i] = points[p].x;
  39122. positions[i + 1] = points[p].y;
  39123. positions[i + 2] = points[p].z;
  39124. i += 3;
  39125. }
  39126. }
  39127. };
  39128. instance.updateMeshPositions(positionFunction, false);
  39129. return instance;
  39130. }
  39131. // line system creation
  39132. var lineSystem = new BABYLON.LinesMesh(name, scene);
  39133. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  39134. vertexData.applyToMesh(lineSystem, options.updatable);
  39135. return lineSystem;
  39136. };
  39137. /**
  39138. * Creates a line mesh.
  39139. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  39140. * 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.
  39141. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  39142. * The parameter `points` is an array successive Vector3.
  39143. * 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
  39144. * When updating an instance, remember that only point positions can change, not the number of points.
  39145. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39146. */
  39147. MeshBuilder.CreateLines = function (name, options, scene) {
  39148. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  39149. return lines;
  39150. };
  39151. /**
  39152. * Creates a dashed line mesh.
  39153. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  39154. * 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.
  39155. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  39156. * The parameter `points` is an array successive Vector3.
  39157. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  39158. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  39159. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  39160. * 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
  39161. * When updating an instance, remember that only point positions can change, not the number of points.
  39162. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39163. */
  39164. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  39165. var points = options.points;
  39166. var instance = options.instance;
  39167. var gapSize = options.gapSize;
  39168. var dashNb = options.dashNb;
  39169. var dashSize = options.dashSize;
  39170. if (instance) {
  39171. var positionFunction = function (positions) {
  39172. var curvect = BABYLON.Vector3.Zero();
  39173. var nbSeg = positions.length / 6;
  39174. var lg = 0;
  39175. var nb = 0;
  39176. var shft = 0;
  39177. var dashshft = 0;
  39178. var curshft = 0;
  39179. var p = 0;
  39180. var i = 0;
  39181. var j = 0;
  39182. for (i = 0; i < points.length - 1; i++) {
  39183. points[i + 1].subtractToRef(points[i], curvect);
  39184. lg += curvect.length();
  39185. }
  39186. shft = lg / nbSeg;
  39187. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  39188. for (i = 0; i < points.length - 1; i++) {
  39189. points[i + 1].subtractToRef(points[i], curvect);
  39190. nb = Math.floor(curvect.length() / shft);
  39191. curvect.normalize();
  39192. j = 0;
  39193. while (j < nb && p < positions.length) {
  39194. curshft = shft * j;
  39195. positions[p] = points[i].x + curshft * curvect.x;
  39196. positions[p + 1] = points[i].y + curshft * curvect.y;
  39197. positions[p + 2] = points[i].z + curshft * curvect.z;
  39198. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  39199. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  39200. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  39201. p += 6;
  39202. j++;
  39203. }
  39204. }
  39205. while (p < positions.length) {
  39206. positions[p] = points[i].x;
  39207. positions[p + 1] = points[i].y;
  39208. positions[p + 2] = points[i].z;
  39209. p += 3;
  39210. }
  39211. };
  39212. instance.updateMeshPositions(positionFunction, false);
  39213. return instance;
  39214. }
  39215. // dashed lines creation
  39216. var dashedLines = new BABYLON.LinesMesh(name, scene);
  39217. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  39218. vertexData.applyToMesh(dashedLines, options.updatable);
  39219. dashedLines.dashSize = dashSize;
  39220. dashedLines.gapSize = gapSize;
  39221. return dashedLines;
  39222. };
  39223. /**
  39224. * Creates an extruded shape mesh.
  39225. * 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.
  39226. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  39227. *
  39228. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  39229. * 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
  39230. * extruded along the Z axis.
  39231. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  39232. * 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.
  39233. * The parameter `scale` (float, default 1) is the value to scale the shape.
  39234. * 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
  39235. * 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
  39236. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  39237. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39238. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39239. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  39240. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39241. */
  39242. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  39243. var path = options.path;
  39244. var shape = options.shape;
  39245. var scale = options.scale || 1;
  39246. var rotation = options.rotation || 0;
  39247. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  39248. var updatable = options.updatable;
  39249. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39250. var instance = options.instance;
  39251. var invertUV = options.invertUV || false;
  39252. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance, invertUV);
  39253. };
  39254. /**
  39255. * Creates an custom extruded shape mesh.
  39256. * 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.
  39257. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  39258. *
  39259. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  39260. * 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
  39261. * extruded along the Z axis.
  39262. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  39263. * 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
  39264. * and the distance of this point from the begining of the path :
  39265. * ```javascript
  39266. * var rotationFunction = function(i, distance) {
  39267. * // do things
  39268. * return rotationValue; }
  39269. * ```
  39270. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  39271. * 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
  39272. * and the distance of this point from the begining of the path :
  39273. * ```javascript
  39274. * var scaleFunction = function(i, distance) {
  39275. * // do things
  39276. * return scaleValue;}
  39277. * ```
  39278. * It must returns a float value that will be the scale value applied to the shape on each path point.
  39279. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  39280. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  39281. * 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
  39282. * 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
  39283. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  39284. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39285. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39286. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  39287. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39288. */
  39289. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  39290. var path = options.path;
  39291. var shape = options.shape;
  39292. var scaleFunction = options.scaleFunction || (function () { return 1; });
  39293. var rotationFunction = options.rotationFunction || (function () { return 0; });
  39294. var ribbonCloseArray = options.ribbonCloseArray || false;
  39295. var ribbonClosePath = options.ribbonClosePath || false;
  39296. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  39297. var updatable = options.updatable;
  39298. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39299. var instance = options.instance;
  39300. var invertUV = options.invertUV || false;
  39301. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance, invertUV);
  39302. };
  39303. /**
  39304. * Creates lathe mesh.
  39305. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  39306. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  39307. *
  39308. * 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
  39309. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  39310. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  39311. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  39312. * 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.
  39313. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  39314. * 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
  39315. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39316. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39317. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  39318. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39319. */
  39320. MeshBuilder.CreateLathe = function (name, options, scene) {
  39321. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  39322. var closed = (options.closed === undefined) ? true : options.closed;
  39323. var shape = options.shape;
  39324. var radius = options.radius || 1;
  39325. var tessellation = options.tessellation || 64;
  39326. var updatable = options.updatable;
  39327. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39328. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  39329. var pi2 = Math.PI * 2;
  39330. var paths = new Array();
  39331. var invertUV = options.invertUV || false;
  39332. var i = 0;
  39333. var p = 0;
  39334. var step = pi2 / tessellation * arc;
  39335. var rotated;
  39336. var path = new Array();
  39337. ;
  39338. for (i = 0; i <= tessellation; i++) {
  39339. var path = [];
  39340. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  39341. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  39342. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  39343. }
  39344. for (p = 0; p < shape.length; p++) {
  39345. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  39346. path.push(rotated);
  39347. }
  39348. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  39349. 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));
  39350. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  39351. }
  39352. paths.push(path);
  39353. }
  39354. // lathe ribbon
  39355. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV }, scene);
  39356. return lathe;
  39357. };
  39358. /**
  39359. * Creates a plane mesh.
  39360. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  39361. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  39362. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  39363. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  39364. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39365. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39366. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39367. */
  39368. MeshBuilder.CreatePlane = function (name, options, scene) {
  39369. var plane = new BABYLON.Mesh(name, scene);
  39370. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39371. plane.sideOrientation = options.sideOrientation;
  39372. var vertexData = BABYLON.VertexData.CreatePlane(options);
  39373. vertexData.applyToMesh(plane, options.updatable);
  39374. if (options.sourcePlane) {
  39375. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  39376. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  39377. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  39378. plane.rotate(vectorProduct, product);
  39379. }
  39380. return plane;
  39381. };
  39382. /**
  39383. * Creates a ground mesh.
  39384. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  39385. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  39386. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  39387. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39388. */
  39389. MeshBuilder.CreateGround = function (name, options, scene) {
  39390. var ground = new BABYLON.GroundMesh(name, scene);
  39391. ground._setReady(false);
  39392. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  39393. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  39394. ground._width = options.width || 1;
  39395. ground._height = options.height || 1;
  39396. ground._maxX = ground._width / 2;
  39397. ground._maxZ = ground._height / 2;
  39398. ground._minX = -ground._maxX;
  39399. ground._minZ = -ground._maxZ;
  39400. var vertexData = BABYLON.VertexData.CreateGround(options);
  39401. vertexData.applyToMesh(ground, options.updatable);
  39402. ground._setReady(true);
  39403. return ground;
  39404. };
  39405. /**
  39406. * Creates a tiled ground mesh.
  39407. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  39408. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  39409. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  39410. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  39411. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  39412. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  39413. * numbers of subdivisions on the ground width and height of each tile.
  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.CreateTiledGround = function (name, options, scene) {
  39417. var tiledGround = new BABYLON.Mesh(name, scene);
  39418. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  39419. vertexData.applyToMesh(tiledGround, options.updatable);
  39420. return tiledGround;
  39421. };
  39422. /**
  39423. * Creates a ground mesh from a height map.
  39424. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  39425. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  39426. * The parameter `url` sets the URL of the height map image resource.
  39427. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  39428. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  39429. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  39430. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  39431. * 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.
  39432. * 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).
  39433. * This function is passed the newly built mesh :
  39434. * ```javascript
  39435. * function(mesh) { // do things
  39436. * return; }
  39437. * ```
  39438. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39439. */
  39440. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  39441. var width = options.width || 10.0;
  39442. var height = options.height || 10.0;
  39443. var subdivisions = options.subdivisions || 1 | 0;
  39444. var minHeight = options.minHeight || 0.0;
  39445. var maxHeight = options.maxHeight || 10.0;
  39446. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  39447. var updatable = options.updatable;
  39448. var onReady = options.onReady;
  39449. var ground = new BABYLON.GroundMesh(name, scene);
  39450. ground._subdivisionsX = subdivisions;
  39451. ground._subdivisionsY = subdivisions;
  39452. ground._width = width;
  39453. ground._height = height;
  39454. ground._maxX = ground._width / 2.0;
  39455. ground._maxZ = ground._height / 2.0;
  39456. ground._minX = -ground._maxX;
  39457. ground._minZ = -ground._maxZ;
  39458. ground._setReady(false);
  39459. var onload = function (img) {
  39460. // Getting height map data
  39461. var canvas = document.createElement("canvas");
  39462. var context = canvas.getContext("2d");
  39463. var bufferWidth = img.width;
  39464. var bufferHeight = img.height;
  39465. canvas.width = bufferWidth;
  39466. canvas.height = bufferHeight;
  39467. context.drawImage(img, 0, 0);
  39468. // Create VertexData from map data
  39469. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  39470. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  39471. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  39472. width: width, height: height,
  39473. subdivisions: subdivisions,
  39474. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  39475. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  39476. });
  39477. vertexData.applyToMesh(ground, updatable);
  39478. ground._setReady(true);
  39479. //execute ready callback, if set
  39480. if (onReady) {
  39481. onReady(ground);
  39482. }
  39483. };
  39484. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  39485. return ground;
  39486. };
  39487. /**
  39488. * Creates a tube mesh.
  39489. * 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.
  39490. *
  39491. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  39492. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  39493. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  39494. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  39495. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  39496. * 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.
  39497. * It must return a radius value (positive float) :
  39498. * ```javascript
  39499. * var radiusFunction = function(i, distance) {
  39500. * // do things
  39501. * return radius; }
  39502. * ```
  39503. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  39504. * 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
  39505. * 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
  39506. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39507. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39508. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  39509. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39510. */
  39511. MeshBuilder.CreateTube = function (name, options, scene) {
  39512. var path = options.path;
  39513. var radius = options.radius || 1.0;
  39514. var tessellation = options.tessellation || 64 | 0;
  39515. var radiusFunction = options.radiusFunction;
  39516. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  39517. var invertUV = options.invertUV || false;
  39518. var updatable = options.updatable;
  39519. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39520. var instance = options.instance;
  39521. options.arc = (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  39522. // tube geometry
  39523. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  39524. var tangents = path3D.getTangents();
  39525. var normals = path3D.getNormals();
  39526. var distances = path3D.getDistances();
  39527. var pi2 = Math.PI * 2;
  39528. var step = pi2 / tessellation * arc;
  39529. var returnRadius = function () { return radius; };
  39530. var radiusFunctionFinal = radiusFunction || returnRadius;
  39531. var circlePath;
  39532. var rad;
  39533. var normal;
  39534. var rotated;
  39535. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  39536. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  39537. for (var i = 0; i < path.length; i++) {
  39538. rad = radiusFunctionFinal(i, distances[i]); // current radius
  39539. circlePath = Array(); // current circle array
  39540. normal = normals[i]; // current normal
  39541. for (var t = 0; t < tessellation; t++) {
  39542. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  39543. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  39544. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  39545. rotated.scaleInPlace(rad).addInPlace(path[i]);
  39546. circlePath[t] = rotated;
  39547. }
  39548. circlePaths[index] = circlePath;
  39549. index++;
  39550. }
  39551. // cap
  39552. var capPath = function (nbPoints, pathIndex) {
  39553. var pointCap = Array();
  39554. for (var i = 0; i < nbPoints; i++) {
  39555. pointCap.push(path[pathIndex]);
  39556. }
  39557. return pointCap;
  39558. };
  39559. switch (cap) {
  39560. case BABYLON.Mesh.NO_CAP:
  39561. break;
  39562. case BABYLON.Mesh.CAP_START:
  39563. circlePaths[0] = capPath(tessellation, 0);
  39564. circlePaths[1] = circlePaths[2].slice(0);
  39565. break;
  39566. case BABYLON.Mesh.CAP_END:
  39567. circlePaths[index] = circlePaths[index - 1].slice(0);
  39568. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  39569. break;
  39570. case BABYLON.Mesh.CAP_ALL:
  39571. circlePaths[0] = capPath(tessellation, 0);
  39572. circlePaths[1] = circlePaths[2].slice(0);
  39573. circlePaths[index] = circlePaths[index - 1].slice(0);
  39574. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  39575. break;
  39576. default:
  39577. break;
  39578. }
  39579. return circlePaths;
  39580. };
  39581. var path3D;
  39582. var pathArray;
  39583. if (instance) {
  39584. var arc = options.arc || instance.arc;
  39585. path3D = (instance.path3D).update(path);
  39586. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  39587. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  39588. instance.path3D = path3D;
  39589. instance.pathArray = pathArray;
  39590. instance.arc = arc;
  39591. return instance;
  39592. }
  39593. // tube creation
  39594. path3D = new BABYLON.Path3D(path);
  39595. var newPathArray = new Array();
  39596. cap = (cap < 0 || cap > 3) ? 0 : cap;
  39597. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  39598. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV }, scene);
  39599. tube.pathArray = pathArray;
  39600. tube.path3D = path3D;
  39601. tube.tessellation = tessellation;
  39602. tube.cap = cap;
  39603. tube.arc = options.arc;
  39604. return tube;
  39605. };
  39606. /**
  39607. * Creates a polyhedron mesh.
  39608. *
  39609. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  39610. * 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
  39611. * to choose the wanted type.
  39612. * The parameter `size` (positive float, default 1) sets the polygon size.
  39613. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  39614. * 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`.
  39615. * 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
  39616. * 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)`).
  39617. * 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
  39618. * 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.
  39619. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39620. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39621. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39622. */
  39623. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  39624. var polyhedron = new BABYLON.Mesh(name, scene);
  39625. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39626. polyhedron.sideOrientation = options.sideOrientation;
  39627. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  39628. vertexData.applyToMesh(polyhedron, options.updatable);
  39629. return polyhedron;
  39630. };
  39631. /**
  39632. * Creates a decal mesh.
  39633. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  39634. * 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.
  39635. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  39636. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  39637. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  39638. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  39639. */
  39640. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  39641. var indices = sourceMesh.getIndices();
  39642. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39643. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  39644. var position = options.position || BABYLON.Vector3.Zero();
  39645. var normal = options.normal || BABYLON.Vector3.Up();
  39646. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  39647. var angle = options.angle || 0;
  39648. // Getting correct rotation
  39649. if (!normal) {
  39650. var target = new BABYLON.Vector3(0, 0, 1);
  39651. var camera = sourceMesh.getScene().activeCamera;
  39652. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  39653. normal = camera.globalPosition.subtract(cameraWorldTarget);
  39654. }
  39655. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  39656. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  39657. var pitch = Math.atan2(normal.y, len);
  39658. // Matrix
  39659. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  39660. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  39661. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  39662. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  39663. var vertexData = new BABYLON.VertexData();
  39664. vertexData.indices = [];
  39665. vertexData.positions = [];
  39666. vertexData.normals = [];
  39667. vertexData.uvs = [];
  39668. var currentVertexDataIndex = 0;
  39669. var extractDecalVector3 = function (indexId) {
  39670. var vertexId = indices[indexId];
  39671. var result = new BABYLON.PositionNormalVertex();
  39672. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  39673. // Send vector to decal local world
  39674. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  39675. // Get normal
  39676. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  39677. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  39678. return result;
  39679. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  39680. var clip = function (vertices, axis) {
  39681. if (vertices.length === 0) {
  39682. return vertices;
  39683. }
  39684. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  39685. var clipVertices = function (v0, v1) {
  39686. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  39687. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  39688. };
  39689. var result = new Array();
  39690. for (var index = 0; index < vertices.length; index += 3) {
  39691. var v1Out;
  39692. var v2Out;
  39693. var v3Out;
  39694. var total = 0;
  39695. var nV1, nV2, nV3, nV4;
  39696. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  39697. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  39698. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  39699. v1Out = d1 > 0;
  39700. v2Out = d2 > 0;
  39701. v3Out = d3 > 0;
  39702. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  39703. switch (total) {
  39704. case 0:
  39705. result.push(vertices[index]);
  39706. result.push(vertices[index + 1]);
  39707. result.push(vertices[index + 2]);
  39708. break;
  39709. case 1:
  39710. if (v1Out) {
  39711. nV1 = vertices[index + 1];
  39712. nV2 = vertices[index + 2];
  39713. nV3 = clipVertices(vertices[index], nV1);
  39714. nV4 = clipVertices(vertices[index], nV2);
  39715. }
  39716. if (v2Out) {
  39717. nV1 = vertices[index];
  39718. nV2 = vertices[index + 2];
  39719. nV3 = clipVertices(vertices[index + 1], nV1);
  39720. nV4 = clipVertices(vertices[index + 1], nV2);
  39721. result.push(nV3);
  39722. result.push(nV2.clone());
  39723. result.push(nV1.clone());
  39724. result.push(nV2.clone());
  39725. result.push(nV3.clone());
  39726. result.push(nV4);
  39727. break;
  39728. }
  39729. if (v3Out) {
  39730. nV1 = vertices[index];
  39731. nV2 = vertices[index + 1];
  39732. nV3 = clipVertices(vertices[index + 2], nV1);
  39733. nV4 = clipVertices(vertices[index + 2], nV2);
  39734. }
  39735. result.push(nV1.clone());
  39736. result.push(nV2.clone());
  39737. result.push(nV3);
  39738. result.push(nV4);
  39739. result.push(nV3.clone());
  39740. result.push(nV2.clone());
  39741. break;
  39742. case 2:
  39743. if (!v1Out) {
  39744. nV1 = vertices[index].clone();
  39745. nV2 = clipVertices(nV1, vertices[index + 1]);
  39746. nV3 = clipVertices(nV1, vertices[index + 2]);
  39747. result.push(nV1);
  39748. result.push(nV2);
  39749. result.push(nV3);
  39750. }
  39751. if (!v2Out) {
  39752. nV1 = vertices[index + 1].clone();
  39753. nV2 = clipVertices(nV1, vertices[index + 2]);
  39754. nV3 = clipVertices(nV1, vertices[index]);
  39755. result.push(nV1);
  39756. result.push(nV2);
  39757. result.push(nV3);
  39758. }
  39759. if (!v3Out) {
  39760. nV1 = vertices[index + 2].clone();
  39761. nV2 = clipVertices(nV1, vertices[index]);
  39762. nV3 = clipVertices(nV1, vertices[index + 1]);
  39763. result.push(nV1);
  39764. result.push(nV2);
  39765. result.push(nV3);
  39766. }
  39767. break;
  39768. case 3:
  39769. break;
  39770. }
  39771. }
  39772. return result;
  39773. };
  39774. for (var index = 0; index < indices.length; index += 3) {
  39775. var faceVertices = new Array();
  39776. faceVertices.push(extractDecalVector3(index));
  39777. faceVertices.push(extractDecalVector3(index + 1));
  39778. faceVertices.push(extractDecalVector3(index + 2));
  39779. // Clip
  39780. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  39781. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  39782. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  39783. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  39784. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  39785. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  39786. if (faceVertices.length === 0) {
  39787. continue;
  39788. }
  39789. // Add UVs and get back to world
  39790. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  39791. var vertex = faceVertices[vIndex];
  39792. //TODO check for Int32Array | Uint32Array | Uint16Array
  39793. vertexData.indices.push(currentVertexDataIndex);
  39794. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  39795. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  39796. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  39797. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  39798. currentVertexDataIndex++;
  39799. }
  39800. }
  39801. // Return mesh
  39802. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  39803. vertexData.applyToMesh(decal);
  39804. decal.position = position.clone();
  39805. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  39806. return decal;
  39807. };
  39808. // Privates
  39809. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV) {
  39810. // extrusion geometry
  39811. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  39812. var tangents = path3D.getTangents();
  39813. var normals = path3D.getNormals();
  39814. var binormals = path3D.getBinormals();
  39815. var distances = path3D.getDistances();
  39816. var angle = 0;
  39817. var returnScale = function () { return scale; };
  39818. var returnRotation = function () { return rotation; };
  39819. var rotate = custom ? rotateFunction : returnRotation;
  39820. var scl = custom ? scaleFunction : returnScale;
  39821. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  39822. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  39823. for (var i = 0; i < curve.length; i++) {
  39824. var shapePath = new Array();
  39825. var angleStep = rotate(i, distances[i]);
  39826. var scaleRatio = scl(i, distances[i]);
  39827. for (var p = 0; p < shape.length; p++) {
  39828. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  39829. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  39830. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  39831. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  39832. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  39833. shapePath[p] = rotated;
  39834. }
  39835. shapePaths[index] = shapePath;
  39836. angle += angleStep;
  39837. index++;
  39838. }
  39839. // cap
  39840. var capPath = function (shapePath) {
  39841. var pointCap = Array();
  39842. var barycenter = BABYLON.Vector3.Zero();
  39843. var i;
  39844. for (i = 0; i < shapePath.length; i++) {
  39845. barycenter.addInPlace(shapePath[i]);
  39846. }
  39847. barycenter.scaleInPlace(1.0 / shapePath.length);
  39848. for (i = 0; i < shapePath.length; i++) {
  39849. pointCap.push(barycenter);
  39850. }
  39851. return pointCap;
  39852. };
  39853. switch (cap) {
  39854. case BABYLON.Mesh.NO_CAP:
  39855. break;
  39856. case BABYLON.Mesh.CAP_START:
  39857. shapePaths[0] = capPath(shapePaths[2]);
  39858. shapePaths[1] = shapePaths[2];
  39859. break;
  39860. case BABYLON.Mesh.CAP_END:
  39861. shapePaths[index] = shapePaths[index - 1];
  39862. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  39863. break;
  39864. case BABYLON.Mesh.CAP_ALL:
  39865. shapePaths[0] = capPath(shapePaths[2]);
  39866. shapePaths[1] = shapePaths[2];
  39867. shapePaths[index] = shapePaths[index - 1];
  39868. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  39869. break;
  39870. default:
  39871. break;
  39872. }
  39873. return shapePaths;
  39874. };
  39875. var path3D;
  39876. var pathArray;
  39877. if (instance) {
  39878. path3D = (instance.path3D).update(curve);
  39879. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  39880. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, scene, null, null, instance);
  39881. return instance;
  39882. }
  39883. // extruded shape creation
  39884. path3D = new BABYLON.Path3D(curve);
  39885. var newShapePaths = new Array();
  39886. cap = (cap < 0 || cap > 3) ? 0 : cap;
  39887. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  39888. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV }, scene);
  39889. extrudedGeneric.pathArray = pathArray;
  39890. extrudedGeneric.path3D = path3D;
  39891. extrudedGeneric.cap = cap;
  39892. return extrudedGeneric;
  39893. };
  39894. return MeshBuilder;
  39895. }());
  39896. BABYLON.MeshBuilder = MeshBuilder;
  39897. })(BABYLON || (BABYLON = {}));
  39898. //# sourceMappingURL=babylon.meshBuilder.js.map
  39899. var BABYLON;
  39900. (function (BABYLON) {
  39901. var AudioEngine = (function () {
  39902. function AudioEngine() {
  39903. this._audioContext = null;
  39904. this._audioContextInitialized = false;
  39905. this.canUseWebAudio = false;
  39906. this.WarnedWebAudioUnsupported = false;
  39907. this.unlocked = false;
  39908. this.isMP3supported = false;
  39909. this.isOGGsupported = false;
  39910. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  39911. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  39912. this.canUseWebAudio = true;
  39913. }
  39914. var audioElem = document.createElement('audio');
  39915. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  39916. this.isMP3supported = true;
  39917. }
  39918. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  39919. this.isOGGsupported = true;
  39920. }
  39921. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  39922. this._unlockiOSaudio();
  39923. }
  39924. else {
  39925. this.unlocked = true;
  39926. }
  39927. }
  39928. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  39929. get: function () {
  39930. if (!this._audioContextInitialized) {
  39931. this._initializeAudioContext();
  39932. }
  39933. return this._audioContext;
  39934. },
  39935. enumerable: true,
  39936. configurable: true
  39937. });
  39938. AudioEngine.prototype._unlockiOSaudio = function () {
  39939. var _this = this;
  39940. var unlockaudio = function () {
  39941. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  39942. var source = _this.audioContext.createBufferSource();
  39943. source.buffer = buffer;
  39944. source.connect(_this.audioContext.destination);
  39945. source.start(0);
  39946. setTimeout(function () {
  39947. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  39948. _this.unlocked = true;
  39949. window.removeEventListener('touchend', unlockaudio, false);
  39950. if (_this.onAudioUnlocked) {
  39951. _this.onAudioUnlocked();
  39952. }
  39953. }
  39954. }, 0);
  39955. };
  39956. window.addEventListener('touchend', unlockaudio, false);
  39957. };
  39958. AudioEngine.prototype._initializeAudioContext = function () {
  39959. try {
  39960. if (this.canUseWebAudio) {
  39961. this._audioContext = new AudioContext();
  39962. // create a global volume gain node
  39963. this.masterGain = this._audioContext.createGain();
  39964. this.masterGain.gain.value = 1;
  39965. this.masterGain.connect(this._audioContext.destination);
  39966. this._audioContextInitialized = true;
  39967. }
  39968. }
  39969. catch (e) {
  39970. this.canUseWebAudio = false;
  39971. BABYLON.Tools.Error("Web Audio: " + e.message);
  39972. }
  39973. };
  39974. AudioEngine.prototype.dispose = function () {
  39975. if (this.canUseWebAudio && this._audioContextInitialized) {
  39976. if (this._connectedAnalyser) {
  39977. this._connectedAnalyser.stopDebugCanvas();
  39978. this._connectedAnalyser.dispose();
  39979. this.masterGain.disconnect();
  39980. this.masterGain.connect(this._audioContext.destination);
  39981. this._connectedAnalyser = null;
  39982. }
  39983. this.masterGain.gain.value = 1;
  39984. }
  39985. this.WarnedWebAudioUnsupported = false;
  39986. };
  39987. AudioEngine.prototype.getGlobalVolume = function () {
  39988. if (this.canUseWebAudio && this._audioContextInitialized) {
  39989. return this.masterGain.gain.value;
  39990. }
  39991. else {
  39992. return -1;
  39993. }
  39994. };
  39995. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  39996. if (this.canUseWebAudio && this._audioContextInitialized) {
  39997. this.masterGain.gain.value = newVolume;
  39998. }
  39999. };
  40000. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  40001. if (this._connectedAnalyser) {
  40002. this._connectedAnalyser.stopDebugCanvas();
  40003. }
  40004. if (this.canUseWebAudio && this._audioContextInitialized) {
  40005. this._connectedAnalyser = analyser;
  40006. this.masterGain.disconnect();
  40007. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  40008. }
  40009. };
  40010. return AudioEngine;
  40011. }());
  40012. BABYLON.AudioEngine = AudioEngine;
  40013. })(BABYLON || (BABYLON = {}));
  40014. //# sourceMappingURL=babylon.audioEngine.js.map
  40015. var BABYLON;
  40016. (function (BABYLON) {
  40017. var Sound = (function () {
  40018. /**
  40019. * Create a sound and attach it to a scene
  40020. * @param name Name of your sound
  40021. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  40022. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  40023. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  40024. */
  40025. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  40026. var _this = this;
  40027. this.autoplay = false;
  40028. this.loop = false;
  40029. this.useCustomAttenuation = false;
  40030. this.spatialSound = false;
  40031. this.refDistance = 1;
  40032. this.rolloffFactor = 1;
  40033. this.maxDistance = 100;
  40034. this.distanceModel = "linear";
  40035. this._panningModel = "equalpower";
  40036. this._playbackRate = 1;
  40037. this._streaming = false;
  40038. this._startTime = 0;
  40039. this._startOffset = 0;
  40040. this._position = BABYLON.Vector3.Zero();
  40041. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  40042. this._volume = 1;
  40043. this._isLoaded = false;
  40044. this._isReadyToPlay = false;
  40045. this.isPlaying = false;
  40046. this.isPaused = false;
  40047. this._isDirectional = false;
  40048. // Used if you'd like to create a directional sound.
  40049. // If not set, the sound will be omnidirectional
  40050. this._coneInnerAngle = 360;
  40051. this._coneOuterAngle = 360;
  40052. this._coneOuterGain = 0;
  40053. this._isOutputConnected = false;
  40054. this._urlType = "Unknown";
  40055. this.name = name;
  40056. this._scene = scene;
  40057. this._readyToPlayCallback = readyToPlayCallback;
  40058. // Default custom attenuation function is a linear attenuation
  40059. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  40060. if (currentDistance < maxDistance) {
  40061. return currentVolume * (1 - currentDistance / maxDistance);
  40062. }
  40063. else {
  40064. return 0;
  40065. }
  40066. };
  40067. if (options) {
  40068. this.autoplay = options.autoplay || false;
  40069. this.loop = options.loop || false;
  40070. // if volume === 0, we need another way to check this option
  40071. if (options.volume !== undefined) {
  40072. this._volume = options.volume;
  40073. }
  40074. this.spatialSound = options.spatialSound || false;
  40075. this.maxDistance = options.maxDistance || 100;
  40076. this.useCustomAttenuation = options.useCustomAttenuation || false;
  40077. this.rolloffFactor = options.rolloffFactor || 1;
  40078. this.refDistance = options.refDistance || 1;
  40079. this.distanceModel = options.distanceModel || "linear";
  40080. this._playbackRate = options.playbackRate || 1;
  40081. this._streaming = options.streaming || false;
  40082. }
  40083. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  40084. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  40085. this._soundGain.gain.value = this._volume;
  40086. this._inputAudioNode = this._soundGain;
  40087. this._ouputAudioNode = this._soundGain;
  40088. if (this.spatialSound) {
  40089. this._createSpatialParameters();
  40090. }
  40091. this._scene.mainSoundTrack.AddSound(this);
  40092. var validParameter = true;
  40093. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  40094. if (urlOrArrayBuffer) {
  40095. if (typeof (urlOrArrayBuffer) === "string")
  40096. this._urlType = "String";
  40097. if (Array.isArray(urlOrArrayBuffer))
  40098. this._urlType = "Array";
  40099. if (urlOrArrayBuffer instanceof ArrayBuffer)
  40100. this._urlType = "ArrayBuffer";
  40101. var urls = [];
  40102. var codecSupportedFound = false;
  40103. switch (this._urlType) {
  40104. case "ArrayBuffer":
  40105. if (urlOrArrayBuffer.byteLength > 0) {
  40106. codecSupportedFound = true;
  40107. this._soundLoaded(urlOrArrayBuffer);
  40108. }
  40109. break;
  40110. case "String":
  40111. urls.push(urlOrArrayBuffer);
  40112. case "Array":
  40113. if (urls.length === 0)
  40114. urls = urlOrArrayBuffer;
  40115. // If we found a supported format, we load it immediately and stop the loop
  40116. for (var i = 0; i < urls.length; i++) {
  40117. var url = urls[i];
  40118. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  40119. codecSupportedFound = true;
  40120. }
  40121. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  40122. codecSupportedFound = true;
  40123. }
  40124. if (url.indexOf(".wav", url.length - 4) !== -1) {
  40125. codecSupportedFound = true;
  40126. }
  40127. if (codecSupportedFound) {
  40128. // Loading sound using XHR2
  40129. if (!this._streaming) {
  40130. BABYLON.Tools.LoadFile(url, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  40131. }
  40132. else {
  40133. this._htmlAudioElement = new Audio(url);
  40134. this._htmlAudioElement.controls = false;
  40135. this._htmlAudioElement.loop = this.loop;
  40136. this._htmlAudioElement.crossOrigin = "anonymous";
  40137. this._htmlAudioElement.preload = "auto";
  40138. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  40139. _this._isReadyToPlay = true;
  40140. if (_this.autoplay) {
  40141. _this.play();
  40142. }
  40143. if (_this._readyToPlayCallback) {
  40144. _this._readyToPlayCallback();
  40145. }
  40146. });
  40147. document.body.appendChild(this._htmlAudioElement);
  40148. }
  40149. break;
  40150. }
  40151. }
  40152. break;
  40153. default:
  40154. validParameter = false;
  40155. break;
  40156. }
  40157. if (!validParameter) {
  40158. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  40159. }
  40160. else {
  40161. if (!codecSupportedFound) {
  40162. this._isReadyToPlay = true;
  40163. // Simulating a ready to play event to avoid breaking code path
  40164. if (this._readyToPlayCallback) {
  40165. window.setTimeout(function () {
  40166. _this._readyToPlayCallback();
  40167. }, 1000);
  40168. }
  40169. }
  40170. }
  40171. }
  40172. }
  40173. else {
  40174. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  40175. this._scene.mainSoundTrack.AddSound(this);
  40176. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  40177. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  40178. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  40179. }
  40180. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  40181. if (this._readyToPlayCallback) {
  40182. window.setTimeout(function () {
  40183. _this._readyToPlayCallback();
  40184. }, 1000);
  40185. }
  40186. }
  40187. }
  40188. Sound.prototype.dispose = function () {
  40189. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  40190. if (this.isPlaying) {
  40191. this.stop();
  40192. }
  40193. this._isReadyToPlay = false;
  40194. if (this.soundTrackId === -1) {
  40195. this._scene.mainSoundTrack.RemoveSound(this);
  40196. }
  40197. else {
  40198. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  40199. }
  40200. if (this._soundGain) {
  40201. this._soundGain.disconnect();
  40202. this._soundGain = null;
  40203. }
  40204. if (this._soundPanner) {
  40205. this._soundPanner.disconnect();
  40206. this._soundPanner = null;
  40207. }
  40208. if (this._soundSource) {
  40209. this._soundSource.disconnect();
  40210. this._soundSource = null;
  40211. }
  40212. this._audioBuffer = null;
  40213. if (this._htmlAudioElement) {
  40214. this._htmlAudioElement.pause();
  40215. this._htmlAudioElement.src = "";
  40216. document.body.removeChild(this._htmlAudioElement);
  40217. }
  40218. if (this._connectedMesh) {
  40219. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  40220. this._connectedMesh = null;
  40221. }
  40222. }
  40223. };
  40224. Sound.prototype.isReady = function () {
  40225. return this._isReadyToPlay;
  40226. };
  40227. Sound.prototype._soundLoaded = function (audioData) {
  40228. var _this = this;
  40229. this._isLoaded = true;
  40230. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  40231. _this._audioBuffer = buffer;
  40232. _this._isReadyToPlay = true;
  40233. if (_this.autoplay) {
  40234. _this.play();
  40235. }
  40236. if (_this._readyToPlayCallback) {
  40237. _this._readyToPlayCallback();
  40238. }
  40239. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  40240. };
  40241. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  40242. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  40243. this._audioBuffer = audioBuffer;
  40244. this._isReadyToPlay = true;
  40245. }
  40246. };
  40247. Sound.prototype.updateOptions = function (options) {
  40248. if (options) {
  40249. this.loop = options.loop || this.loop;
  40250. this.maxDistance = options.maxDistance || this.maxDistance;
  40251. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  40252. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  40253. this.refDistance = options.refDistance || this.refDistance;
  40254. this.distanceModel = options.distanceModel || this.distanceModel;
  40255. this._playbackRate = options.playbackRate || this._playbackRate;
  40256. this._updateSpatialParameters();
  40257. if (this.isPlaying) {
  40258. if (this._streaming) {
  40259. this._htmlAudioElement.playbackRate = this._playbackRate;
  40260. }
  40261. else {
  40262. this._soundSource.playbackRate.value = this._playbackRate;
  40263. }
  40264. }
  40265. }
  40266. };
  40267. Sound.prototype._createSpatialParameters = function () {
  40268. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  40269. if (this._scene.headphone) {
  40270. this._panningModel = "HRTF";
  40271. }
  40272. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  40273. this._updateSpatialParameters();
  40274. this._soundPanner.connect(this._ouputAudioNode);
  40275. this._inputAudioNode = this._soundPanner;
  40276. }
  40277. };
  40278. Sound.prototype._updateSpatialParameters = function () {
  40279. if (this.spatialSound) {
  40280. if (this.useCustomAttenuation) {
  40281. // Tricks to disable in a way embedded Web Audio attenuation
  40282. this._soundPanner.distanceModel = "linear";
  40283. this._soundPanner.maxDistance = Number.MAX_VALUE;
  40284. this._soundPanner.refDistance = 1;
  40285. this._soundPanner.rolloffFactor = 1;
  40286. this._soundPanner.panningModel = this._panningModel;
  40287. }
  40288. else {
  40289. this._soundPanner.distanceModel = this.distanceModel;
  40290. this._soundPanner.maxDistance = this.maxDistance;
  40291. this._soundPanner.refDistance = this.refDistance;
  40292. this._soundPanner.rolloffFactor = this.rolloffFactor;
  40293. this._soundPanner.panningModel = this._panningModel;
  40294. }
  40295. }
  40296. };
  40297. Sound.prototype.switchPanningModelToHRTF = function () {
  40298. this._panningModel = "HRTF";
  40299. this._switchPanningModel();
  40300. };
  40301. Sound.prototype.switchPanningModelToEqualPower = function () {
  40302. this._panningModel = "equalpower";
  40303. this._switchPanningModel();
  40304. };
  40305. Sound.prototype._switchPanningModel = function () {
  40306. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  40307. this._soundPanner.panningModel = this._panningModel;
  40308. }
  40309. };
  40310. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  40311. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  40312. if (this._isOutputConnected) {
  40313. this._ouputAudioNode.disconnect();
  40314. }
  40315. this._ouputAudioNode.connect(soundTrackAudioNode);
  40316. this._isOutputConnected = true;
  40317. }
  40318. };
  40319. /**
  40320. * Transform this sound into a directional source
  40321. * @param coneInnerAngle Size of the inner cone in degree
  40322. * @param coneOuterAngle Size of the outer cone in degree
  40323. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  40324. */
  40325. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  40326. if (coneOuterAngle < coneInnerAngle) {
  40327. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  40328. return;
  40329. }
  40330. this._coneInnerAngle = coneInnerAngle;
  40331. this._coneOuterAngle = coneOuterAngle;
  40332. this._coneOuterGain = coneOuterGain;
  40333. this._isDirectional = true;
  40334. if (this.isPlaying && this.loop) {
  40335. this.stop();
  40336. this.play();
  40337. }
  40338. };
  40339. Sound.prototype.setPosition = function (newPosition) {
  40340. this._position = newPosition;
  40341. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  40342. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  40343. }
  40344. };
  40345. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  40346. this._localDirection = newLocalDirection;
  40347. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  40348. this._updateDirection();
  40349. }
  40350. };
  40351. Sound.prototype._updateDirection = function () {
  40352. var mat = this._connectedMesh.getWorldMatrix();
  40353. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  40354. direction.normalize();
  40355. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  40356. };
  40357. Sound.prototype.updateDistanceFromListener = function () {
  40358. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  40359. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  40360. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  40361. }
  40362. };
  40363. Sound.prototype.setAttenuationFunction = function (callback) {
  40364. this._customAttenuationFunction = callback;
  40365. };
  40366. /**
  40367. * Play the sound
  40368. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  40369. * @param offset (optional) Start the sound setting it at a specific time
  40370. */
  40371. Sound.prototype.play = function (time, offset) {
  40372. var _this = this;
  40373. if (this._isReadyToPlay && this._scene.audioEnabled) {
  40374. try {
  40375. if (this._startOffset < 0) {
  40376. time = -this._startOffset;
  40377. this._startOffset = 0;
  40378. }
  40379. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  40380. if (!this._soundSource || !this._streamingSource) {
  40381. if (this.spatialSound) {
  40382. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  40383. if (this._isDirectional) {
  40384. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  40385. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  40386. this._soundPanner.coneOuterGain = this._coneOuterGain;
  40387. if (this._connectedMesh) {
  40388. this._updateDirection();
  40389. }
  40390. else {
  40391. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  40392. }
  40393. }
  40394. }
  40395. }
  40396. if (this._streaming) {
  40397. if (!this._streamingSource) {
  40398. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  40399. this._htmlAudioElement.onended = function () { _this._onended(); };
  40400. this._htmlAudioElement.playbackRate = this._playbackRate;
  40401. }
  40402. this._streamingSource.disconnect();
  40403. this._streamingSource.connect(this._inputAudioNode);
  40404. this._htmlAudioElement.play();
  40405. }
  40406. else {
  40407. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  40408. this._soundSource.buffer = this._audioBuffer;
  40409. this._soundSource.connect(this._inputAudioNode);
  40410. this._soundSource.loop = this.loop;
  40411. this._soundSource.playbackRate.value = this._playbackRate;
  40412. this._soundSource.onended = function () { _this._onended(); };
  40413. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  40414. }
  40415. this._startTime = startTime;
  40416. this.isPlaying = true;
  40417. this.isPaused = false;
  40418. }
  40419. catch (ex) {
  40420. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  40421. }
  40422. }
  40423. };
  40424. Sound.prototype._onended = function () {
  40425. this.isPlaying = false;
  40426. if (this.onended) {
  40427. this.onended();
  40428. }
  40429. };
  40430. /**
  40431. * Stop the sound
  40432. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  40433. */
  40434. Sound.prototype.stop = function (time) {
  40435. if (this.isPlaying) {
  40436. if (this._streaming) {
  40437. this._htmlAudioElement.pause();
  40438. // Test needed for Firefox or it will generate an Invalid State Error
  40439. if (this._htmlAudioElement.currentTime > 0) {
  40440. this._htmlAudioElement.currentTime = 0;
  40441. }
  40442. }
  40443. else {
  40444. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  40445. this._soundSource.stop(stopTime);
  40446. this._soundSource.onended = null;
  40447. if (!this.isPaused) {
  40448. this._startOffset = 0;
  40449. }
  40450. }
  40451. this.isPlaying = false;
  40452. }
  40453. };
  40454. Sound.prototype.pause = function () {
  40455. if (this.isPlaying) {
  40456. this.isPaused = true;
  40457. if (this._streaming) {
  40458. this._htmlAudioElement.pause();
  40459. }
  40460. else {
  40461. this.stop(0);
  40462. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  40463. }
  40464. }
  40465. };
  40466. Sound.prototype.setVolume = function (newVolume, time) {
  40467. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  40468. if (time) {
  40469. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  40470. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  40471. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  40472. }
  40473. else {
  40474. this._soundGain.gain.value = newVolume;
  40475. }
  40476. }
  40477. this._volume = newVolume;
  40478. };
  40479. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  40480. this._playbackRate = newPlaybackRate;
  40481. if (this.isPlaying) {
  40482. if (this._streaming) {
  40483. this._htmlAudioElement.playbackRate = this._playbackRate;
  40484. }
  40485. else {
  40486. this._soundSource.playbackRate.value = this._playbackRate;
  40487. }
  40488. }
  40489. };
  40490. Sound.prototype.getVolume = function () {
  40491. return this._volume;
  40492. };
  40493. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  40494. var _this = this;
  40495. if (this._connectedMesh) {
  40496. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  40497. this._registerFunc = null;
  40498. }
  40499. this._connectedMesh = meshToConnectTo;
  40500. if (!this.spatialSound) {
  40501. this.spatialSound = true;
  40502. this._createSpatialParameters();
  40503. if (this.isPlaying && this.loop) {
  40504. this.stop();
  40505. this.play();
  40506. }
  40507. }
  40508. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  40509. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  40510. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  40511. };
  40512. Sound.prototype.detachFromMesh = function () {
  40513. if (this._connectedMesh) {
  40514. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  40515. this._registerFunc = null;
  40516. this._connectedMesh = null;
  40517. }
  40518. };
  40519. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  40520. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  40521. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  40522. this._updateDirection();
  40523. }
  40524. };
  40525. Sound.prototype.clone = function () {
  40526. var _this = this;
  40527. if (!this._streaming) {
  40528. var setBufferAndRun = function () {
  40529. if (_this._isReadyToPlay) {
  40530. clonedSound._audioBuffer = _this.getAudioBuffer();
  40531. clonedSound._isReadyToPlay = true;
  40532. if (clonedSound.autoplay) {
  40533. clonedSound.play();
  40534. }
  40535. }
  40536. else {
  40537. window.setTimeout(setBufferAndRun, 300);
  40538. }
  40539. };
  40540. var currentOptions = {
  40541. autoplay: this.autoplay, loop: this.loop,
  40542. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  40543. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  40544. refDistance: this.refDistance, distanceModel: this.distanceModel
  40545. };
  40546. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  40547. if (this.useCustomAttenuation) {
  40548. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  40549. }
  40550. clonedSound.setPosition(this._position);
  40551. clonedSound.setPlaybackRate(this._playbackRate);
  40552. setBufferAndRun();
  40553. return clonedSound;
  40554. }
  40555. else {
  40556. return null;
  40557. }
  40558. };
  40559. Sound.prototype.getAudioBuffer = function () {
  40560. return this._audioBuffer;
  40561. };
  40562. Sound.prototype.serialize = function () {
  40563. var serializationObject = {
  40564. name: this.name,
  40565. url: this.name,
  40566. autoplay: this.autoplay,
  40567. loop: this.loop,
  40568. volume: this._volume,
  40569. spatialSound: this.spatialSound,
  40570. maxDistance: this.maxDistance,
  40571. rolloffFactor: this.rolloffFactor,
  40572. refDistance: this.refDistance,
  40573. distanceModel: this.distanceModel,
  40574. playbackRate: this._playbackRate,
  40575. panningModel: this._panningModel,
  40576. soundTrackId: this.soundTrackId
  40577. };
  40578. if (this.spatialSound) {
  40579. if (this._connectedMesh)
  40580. serializationObject.connectedMeshId = this._connectedMesh.id;
  40581. serializationObject.position = this._position.asArray();
  40582. serializationObject.refDistance = this.refDistance;
  40583. serializationObject.distanceModel = this.distanceModel;
  40584. serializationObject.isDirectional = this._isDirectional;
  40585. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  40586. serializationObject.coneInnerAngle = this._coneInnerAngle;
  40587. serializationObject.coneOuterAngle = this._coneOuterAngle;
  40588. serializationObject.coneOuterGain = this._coneOuterGain;
  40589. }
  40590. return serializationObject;
  40591. };
  40592. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  40593. var soundName = parsedSound.name;
  40594. var soundUrl;
  40595. if (parsedSound.url) {
  40596. soundUrl = rootUrl + parsedSound.url;
  40597. }
  40598. else {
  40599. soundUrl = rootUrl + soundName;
  40600. }
  40601. var options = {
  40602. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  40603. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  40604. rolloffFactor: parsedSound.rolloffFactor,
  40605. refDistance: parsedSound.refDistance,
  40606. distanceModel: parsedSound.distanceModel,
  40607. playbackRate: parsedSound.playbackRate
  40608. };
  40609. var newSound;
  40610. if (!sourceSound) {
  40611. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  40612. scene._addPendingData(newSound);
  40613. }
  40614. else {
  40615. var setBufferAndRun = function () {
  40616. if (sourceSound._isReadyToPlay) {
  40617. newSound._audioBuffer = sourceSound.getAudioBuffer();
  40618. newSound._isReadyToPlay = true;
  40619. if (newSound.autoplay) {
  40620. newSound.play();
  40621. }
  40622. }
  40623. else {
  40624. window.setTimeout(setBufferAndRun, 300);
  40625. }
  40626. };
  40627. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  40628. setBufferAndRun();
  40629. }
  40630. if (parsedSound.position) {
  40631. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  40632. newSound.setPosition(soundPosition);
  40633. }
  40634. if (parsedSound.isDirectional) {
  40635. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  40636. if (parsedSound.localDirectionToMesh) {
  40637. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  40638. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  40639. }
  40640. }
  40641. if (parsedSound.connectedMeshId) {
  40642. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  40643. if (connectedMesh) {
  40644. newSound.attachToMesh(connectedMesh);
  40645. }
  40646. }
  40647. return newSound;
  40648. };
  40649. return Sound;
  40650. }());
  40651. BABYLON.Sound = Sound;
  40652. })(BABYLON || (BABYLON = {}));
  40653. //# sourceMappingURL=babylon.sound.js.map
  40654. var BABYLON;
  40655. (function (BABYLON) {
  40656. var SoundTrack = (function () {
  40657. function SoundTrack(scene, options) {
  40658. this.id = -1;
  40659. this._isMainTrack = false;
  40660. this._isInitialized = false;
  40661. this._scene = scene;
  40662. this.soundCollection = new Array();
  40663. this._options = options;
  40664. if (!this._isMainTrack) {
  40665. this._scene.soundTracks.push(this);
  40666. this.id = this._scene.soundTracks.length - 1;
  40667. }
  40668. }
  40669. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  40670. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  40671. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  40672. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  40673. if (this._options) {
  40674. if (this._options.volume) {
  40675. this._outputAudioNode.gain.value = this._options.volume;
  40676. }
  40677. if (this._options.mainTrack) {
  40678. this._isMainTrack = this._options.mainTrack;
  40679. }
  40680. }
  40681. this._isInitialized = true;
  40682. }
  40683. };
  40684. SoundTrack.prototype.dispose = function () {
  40685. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  40686. if (this._connectedAnalyser) {
  40687. this._connectedAnalyser.stopDebugCanvas();
  40688. }
  40689. while (this.soundCollection.length) {
  40690. this.soundCollection[0].dispose();
  40691. }
  40692. if (this._outputAudioNode) {
  40693. this._outputAudioNode.disconnect();
  40694. }
  40695. this._outputAudioNode = null;
  40696. }
  40697. };
  40698. SoundTrack.prototype.AddSound = function (sound) {
  40699. if (!this._isInitialized) {
  40700. this._initializeSoundTrackAudioGraph();
  40701. }
  40702. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  40703. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  40704. }
  40705. if (sound.soundTrackId) {
  40706. if (sound.soundTrackId === -1) {
  40707. this._scene.mainSoundTrack.RemoveSound(sound);
  40708. }
  40709. else {
  40710. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  40711. }
  40712. }
  40713. this.soundCollection.push(sound);
  40714. sound.soundTrackId = this.id;
  40715. };
  40716. SoundTrack.prototype.RemoveSound = function (sound) {
  40717. var index = this.soundCollection.indexOf(sound);
  40718. if (index !== -1) {
  40719. this.soundCollection.splice(index, 1);
  40720. }
  40721. };
  40722. SoundTrack.prototype.setVolume = function (newVolume) {
  40723. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  40724. this._outputAudioNode.gain.value = newVolume;
  40725. }
  40726. };
  40727. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  40728. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  40729. for (var i = 0; i < this.soundCollection.length; i++) {
  40730. this.soundCollection[i].switchPanningModelToHRTF();
  40731. }
  40732. }
  40733. };
  40734. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  40735. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  40736. for (var i = 0; i < this.soundCollection.length; i++) {
  40737. this.soundCollection[i].switchPanningModelToEqualPower();
  40738. }
  40739. }
  40740. };
  40741. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  40742. if (this._connectedAnalyser) {
  40743. this._connectedAnalyser.stopDebugCanvas();
  40744. }
  40745. this._connectedAnalyser = analyser;
  40746. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  40747. this._outputAudioNode.disconnect();
  40748. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  40749. }
  40750. };
  40751. return SoundTrack;
  40752. }());
  40753. BABYLON.SoundTrack = SoundTrack;
  40754. })(BABYLON || (BABYLON = {}));
  40755. //# sourceMappingURL=babylon.soundtrack.js.map
  40756. var BABYLON;
  40757. (function (BABYLON) {
  40758. var Analyser = (function () {
  40759. function Analyser(scene) {
  40760. this.SMOOTHING = 0.75;
  40761. this.FFT_SIZE = 512;
  40762. this.BARGRAPHAMPLITUDE = 256;
  40763. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  40764. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  40765. this._scene = scene;
  40766. this._audioEngine = BABYLON.Engine.audioEngine;
  40767. if (this._audioEngine.canUseWebAudio) {
  40768. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  40769. this._webAudioAnalyser.minDecibels = -140;
  40770. this._webAudioAnalyser.maxDecibels = 0;
  40771. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  40772. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  40773. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  40774. }
  40775. }
  40776. Analyser.prototype.getFrequencyBinCount = function () {
  40777. if (this._audioEngine.canUseWebAudio) {
  40778. return this._webAudioAnalyser.frequencyBinCount;
  40779. }
  40780. else {
  40781. return 0;
  40782. }
  40783. };
  40784. Analyser.prototype.getByteFrequencyData = function () {
  40785. if (this._audioEngine.canUseWebAudio) {
  40786. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  40787. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  40788. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  40789. }
  40790. return this._byteFreqs;
  40791. };
  40792. Analyser.prototype.getByteTimeDomainData = function () {
  40793. if (this._audioEngine.canUseWebAudio) {
  40794. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  40795. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  40796. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  40797. }
  40798. return this._byteTime;
  40799. };
  40800. Analyser.prototype.getFloatFrequencyData = function () {
  40801. if (this._audioEngine.canUseWebAudio) {
  40802. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  40803. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  40804. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  40805. }
  40806. return this._floatFreqs;
  40807. };
  40808. Analyser.prototype.drawDebugCanvas = function () {
  40809. var _this = this;
  40810. if (this._audioEngine.canUseWebAudio) {
  40811. if (!this._debugCanvas) {
  40812. this._debugCanvas = document.createElement("canvas");
  40813. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  40814. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  40815. this._debugCanvas.style.position = "absolute";
  40816. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  40817. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  40818. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  40819. document.body.appendChild(this._debugCanvas);
  40820. this._registerFunc = function () {
  40821. _this.drawDebugCanvas();
  40822. };
  40823. this._scene.registerBeforeRender(this._registerFunc);
  40824. }
  40825. if (this._registerFunc) {
  40826. var workingArray = this.getByteFrequencyData();
  40827. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  40828. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  40829. // Draw the frequency domain chart.
  40830. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  40831. var value = workingArray[i];
  40832. var percent = value / this.BARGRAPHAMPLITUDE;
  40833. var height = this.DEBUGCANVASSIZE.height * percent;
  40834. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  40835. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  40836. var hue = i / this.getFrequencyBinCount() * 360;
  40837. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  40838. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  40839. }
  40840. }
  40841. }
  40842. };
  40843. Analyser.prototype.stopDebugCanvas = function () {
  40844. if (this._debugCanvas) {
  40845. this._scene.unregisterBeforeRender(this._registerFunc);
  40846. this._registerFunc = null;
  40847. document.body.removeChild(this._debugCanvas);
  40848. this._debugCanvas = null;
  40849. this._debugCanvasContext = null;
  40850. }
  40851. };
  40852. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  40853. if (this._audioEngine.canUseWebAudio) {
  40854. inputAudioNode.connect(this._webAudioAnalyser);
  40855. this._webAudioAnalyser.connect(outputAudioNode);
  40856. }
  40857. };
  40858. Analyser.prototype.dispose = function () {
  40859. if (this._audioEngine.canUseWebAudio) {
  40860. this._webAudioAnalyser.disconnect();
  40861. }
  40862. };
  40863. return Analyser;
  40864. }());
  40865. BABYLON.Analyser = Analyser;
  40866. })(BABYLON || (BABYLON = {}));
  40867. //# sourceMappingURL=babylon.analyser.js.map
  40868. var BABYLON;
  40869. (function (BABYLON) {
  40870. var CubeTexture = (function (_super) {
  40871. __extends(CubeTexture, _super);
  40872. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format) {
  40873. if (onLoad === void 0) { onLoad = null; }
  40874. if (onError === void 0) { onError = null; }
  40875. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  40876. var _this = _super.call(this, scene) || this;
  40877. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  40878. _this.name = rootUrl;
  40879. _this.url = rootUrl;
  40880. _this._noMipmap = noMipmap;
  40881. _this.hasAlpha = false;
  40882. _this._format = format;
  40883. if (!rootUrl && !files) {
  40884. return _this;
  40885. }
  40886. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  40887. if (!files) {
  40888. if (!extensions) {
  40889. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  40890. }
  40891. files = [];
  40892. for (var index = 0; index < extensions.length; index++) {
  40893. files.push(rootUrl + extensions[index]);
  40894. }
  40895. _this._extensions = extensions;
  40896. }
  40897. _this._files = files;
  40898. if (!_this._texture) {
  40899. if (!scene.useDelayedTextureLoading) {
  40900. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format);
  40901. }
  40902. else {
  40903. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  40904. }
  40905. }
  40906. else if (onLoad) {
  40907. if (_this._texture.isReady) {
  40908. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  40909. }
  40910. else {
  40911. _this._texture.onLoadedCallbacks.push(onLoad);
  40912. }
  40913. }
  40914. _this.isCube = true;
  40915. _this._textureMatrix = BABYLON.Matrix.Identity();
  40916. return _this;
  40917. }
  40918. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  40919. return new CubeTexture("", scene, null, noMipmap, files);
  40920. };
  40921. // Methods
  40922. CubeTexture.prototype.delayLoad = function () {
  40923. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  40924. return;
  40925. }
  40926. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  40927. this._texture = this._getFromCache(this.url, this._noMipmap);
  40928. if (!this._texture) {
  40929. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._files, this._noMipmap, undefined, undefined, this._format);
  40930. }
  40931. };
  40932. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  40933. return this._textureMatrix;
  40934. };
  40935. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  40936. var texture = BABYLON.SerializationHelper.Parse(function () {
  40937. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  40938. }, parsedTexture, scene);
  40939. // Animations
  40940. if (parsedTexture.animations) {
  40941. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  40942. var parsedAnimation = parsedTexture.animations[animationIndex];
  40943. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  40944. }
  40945. }
  40946. return texture;
  40947. };
  40948. CubeTexture.prototype.clone = function () {
  40949. var _this = this;
  40950. return BABYLON.SerializationHelper.Clone(function () {
  40951. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  40952. }, this);
  40953. };
  40954. return CubeTexture;
  40955. }(BABYLON.BaseTexture));
  40956. BABYLON.CubeTexture = CubeTexture;
  40957. })(BABYLON || (BABYLON = {}));
  40958. //# sourceMappingURL=babylon.cubeTexture.js.map
  40959. var BABYLON;
  40960. (function (BABYLON) {
  40961. var RenderTargetTexture = (function (_super) {
  40962. __extends(RenderTargetTexture, _super);
  40963. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer) {
  40964. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  40965. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  40966. if (isCube === void 0) { isCube = false; }
  40967. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  40968. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  40969. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  40970. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  40971. _this.isCube = isCube;
  40972. /**
  40973. * Use this list to define the list of mesh you want to render.
  40974. */
  40975. _this.renderList = new Array();
  40976. _this.renderParticles = true;
  40977. _this.renderSprites = false;
  40978. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  40979. // Events
  40980. /**
  40981. * An event triggered when the texture is unbind.
  40982. * @type {BABYLON.Observable}
  40983. */
  40984. _this.onAfterUnbindObservable = new BABYLON.Observable();
  40985. /**
  40986. * An event triggered before rendering the texture
  40987. * @type {BABYLON.Observable}
  40988. */
  40989. _this.onBeforeRenderObservable = new BABYLON.Observable();
  40990. /**
  40991. * An event triggered after rendering the texture
  40992. * @type {BABYLON.Observable}
  40993. */
  40994. _this.onAfterRenderObservable = new BABYLON.Observable();
  40995. /**
  40996. * An event triggered after the texture clear
  40997. * @type {BABYLON.Observable}
  40998. */
  40999. _this.onClearObservable = new BABYLON.Observable();
  41000. _this._currentRefreshId = -1;
  41001. _this._refreshRate = 1;
  41002. _this._samples = 1;
  41003. _this.name = name;
  41004. _this.isRenderTarget = true;
  41005. _this._size = size;
  41006. _this._generateMipMaps = generateMipMaps;
  41007. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  41008. _this._renderTargetOptions = {
  41009. generateMipMaps: generateMipMaps,
  41010. type: type,
  41011. samplingMode: samplingMode,
  41012. generateDepthBuffer: generateDepthBuffer,
  41013. generateStencilBuffer: generateStencilBuffer
  41014. };
  41015. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  41016. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41017. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41018. }
  41019. if (isCube) {
  41020. _this._texture = scene.getEngine().createRenderTargetCubeTexture(size, _this._renderTargetOptions);
  41021. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  41022. _this._textureMatrix = BABYLON.Matrix.Identity();
  41023. }
  41024. else {
  41025. _this._texture = scene.getEngine().createRenderTargetTexture(size, _this._renderTargetOptions);
  41026. }
  41027. // Rendering groups
  41028. _this._renderingManager = new BABYLON.RenderingManager(scene);
  41029. return _this;
  41030. }
  41031. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  41032. get: function () {
  41033. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  41034. },
  41035. enumerable: true,
  41036. configurable: true
  41037. });
  41038. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  41039. get: function () {
  41040. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  41041. },
  41042. enumerable: true,
  41043. configurable: true
  41044. });
  41045. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  41046. get: function () {
  41047. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  41048. },
  41049. enumerable: true,
  41050. configurable: true
  41051. });
  41052. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  41053. set: function (callback) {
  41054. if (this._onAfterUnbindObserver) {
  41055. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  41056. }
  41057. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  41058. },
  41059. enumerable: true,
  41060. configurable: true
  41061. });
  41062. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  41063. set: function (callback) {
  41064. if (this._onBeforeRenderObserver) {
  41065. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  41066. }
  41067. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  41068. },
  41069. enumerable: true,
  41070. configurable: true
  41071. });
  41072. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  41073. set: function (callback) {
  41074. if (this._onAfterRenderObserver) {
  41075. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  41076. }
  41077. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  41078. },
  41079. enumerable: true,
  41080. configurable: true
  41081. });
  41082. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  41083. set: function (callback) {
  41084. if (this._onClearObserver) {
  41085. this.onClearObservable.remove(this._onClearObserver);
  41086. }
  41087. this._onClearObserver = this.onClearObservable.add(callback);
  41088. },
  41089. enumerable: true,
  41090. configurable: true
  41091. });
  41092. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  41093. get: function () {
  41094. return this._renderTargetOptions;
  41095. },
  41096. enumerable: true,
  41097. configurable: true
  41098. });
  41099. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  41100. get: function () {
  41101. return this._samples;
  41102. },
  41103. set: function (value) {
  41104. if (this._samples === value) {
  41105. return;
  41106. }
  41107. this._samples = this.getScene().getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  41108. },
  41109. enumerable: true,
  41110. configurable: true
  41111. });
  41112. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  41113. this._currentRefreshId = -1;
  41114. };
  41115. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  41116. get: function () {
  41117. return this._refreshRate;
  41118. },
  41119. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  41120. set: function (value) {
  41121. this._refreshRate = value;
  41122. this.resetRefreshCounter();
  41123. },
  41124. enumerable: true,
  41125. configurable: true
  41126. });
  41127. RenderTargetTexture.prototype._shouldRender = function () {
  41128. if (this._currentRefreshId === -1) {
  41129. this._currentRefreshId = 1;
  41130. return true;
  41131. }
  41132. if (this.refreshRate === this._currentRefreshId) {
  41133. this._currentRefreshId = 1;
  41134. return true;
  41135. }
  41136. this._currentRefreshId++;
  41137. return false;
  41138. };
  41139. RenderTargetTexture.prototype.isReady = function () {
  41140. if (!this.getScene().renderTargetsEnabled) {
  41141. return false;
  41142. }
  41143. return _super.prototype.isReady.call(this);
  41144. };
  41145. RenderTargetTexture.prototype.getRenderSize = function () {
  41146. return this._size;
  41147. };
  41148. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  41149. get: function () {
  41150. return true;
  41151. },
  41152. enumerable: true,
  41153. configurable: true
  41154. });
  41155. RenderTargetTexture.prototype.scale = function (ratio) {
  41156. var newSize = this._size * ratio;
  41157. this.resize(newSize);
  41158. };
  41159. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  41160. if (this.isCube) {
  41161. return this._textureMatrix;
  41162. }
  41163. return _super.prototype.getReflectionTextureMatrix.call(this);
  41164. };
  41165. RenderTargetTexture.prototype.resize = function (size) {
  41166. this.releaseInternalTexture();
  41167. if (this.isCube) {
  41168. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size, this._renderTargetOptions);
  41169. }
  41170. else {
  41171. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, this._renderTargetOptions);
  41172. }
  41173. };
  41174. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  41175. var scene = this.getScene();
  41176. var engine = scene.getEngine();
  41177. if (this.useCameraPostProcesses !== undefined) {
  41178. useCameraPostProcess = this.useCameraPostProcesses;
  41179. }
  41180. if (this._waitingRenderList) {
  41181. this.renderList = [];
  41182. for (var index = 0; index < this._waitingRenderList.length; index++) {
  41183. var id = this._waitingRenderList[index];
  41184. this.renderList.push(scene.getMeshByID(id));
  41185. }
  41186. delete this._waitingRenderList;
  41187. }
  41188. // Is predicate defined?
  41189. if (this.renderListPredicate) {
  41190. this.renderList.splice(0); // Clear previous renderList
  41191. var sceneMeshes = this.getScene().meshes;
  41192. for (var index = 0; index < sceneMeshes.length; index++) {
  41193. var mesh = sceneMeshes[index];
  41194. if (this.renderListPredicate(mesh)) {
  41195. this.renderList.push(mesh);
  41196. }
  41197. }
  41198. }
  41199. if (this.renderList && this.renderList.length === 0) {
  41200. return;
  41201. }
  41202. // Set custom projection.
  41203. // Needs to be before binding to prevent changing the aspect ratio.
  41204. if (this.activeCamera) {
  41205. engine.setViewport(this.activeCamera.viewport);
  41206. if (this.activeCamera !== scene.activeCamera) {
  41207. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  41208. }
  41209. }
  41210. else {
  41211. engine.setViewport(scene.activeCamera.viewport);
  41212. }
  41213. // Prepare renderingManager
  41214. this._renderingManager.reset();
  41215. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  41216. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  41217. var sceneRenderId = scene.getRenderId();
  41218. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  41219. var mesh = currentRenderList[meshIndex];
  41220. if (mesh) {
  41221. if (!mesh.isReady()) {
  41222. // Reset _currentRefreshId
  41223. this.resetRefreshCounter();
  41224. continue;
  41225. }
  41226. mesh._preActivateForIntermediateRendering(sceneRenderId);
  41227. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  41228. mesh._activate(sceneRenderId);
  41229. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  41230. var subMesh = mesh.subMeshes[subIndex];
  41231. scene._activeIndices.addCount(subMesh.indexCount, false);
  41232. this._renderingManager.dispatch(subMesh);
  41233. }
  41234. }
  41235. }
  41236. }
  41237. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  41238. var particleSystem = scene.particleSystems[particleIndex];
  41239. if (!particleSystem.isStarted() || !particleSystem.emitter || !particleSystem.emitter.position || !particleSystem.emitter.isEnabled()) {
  41240. continue;
  41241. }
  41242. if (currentRenderList.indexOf(particleSystem.emitter) >= 0) {
  41243. this._renderingManager.dispatchParticles(particleSystem);
  41244. }
  41245. }
  41246. if (this.isCube) {
  41247. for (var face = 0; face < 6; face++) {
  41248. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  41249. scene.incrementRenderId();
  41250. scene.resetCachedMaterial();
  41251. }
  41252. }
  41253. else {
  41254. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  41255. }
  41256. this.onAfterUnbindObservable.notifyObservers(this);
  41257. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  41258. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  41259. }
  41260. engine.setViewport(scene.activeCamera.viewport);
  41261. scene.resetCachedMaterial();
  41262. };
  41263. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  41264. var _this = this;
  41265. var scene = this.getScene();
  41266. var engine = scene.getEngine();
  41267. // Bind
  41268. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  41269. if (this.isCube) {
  41270. engine.bindFramebuffer(this._texture, faceIndex);
  41271. }
  41272. else {
  41273. engine.bindFramebuffer(this._texture);
  41274. }
  41275. }
  41276. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  41277. // Clear
  41278. if (this.onClearObservable.hasObservers()) {
  41279. this.onClearObservable.notifyObservers(engine);
  41280. }
  41281. else {
  41282. engine.clear(scene.clearColor, true, true, true);
  41283. }
  41284. if (!this._doNotChangeAspectRatio) {
  41285. scene.updateTransformMatrix(true);
  41286. }
  41287. // Render
  41288. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  41289. if (useCameraPostProcess) {
  41290. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  41291. }
  41292. if (!this._doNotChangeAspectRatio) {
  41293. scene.updateTransformMatrix(true);
  41294. }
  41295. // Dump ?
  41296. if (dumpForDebug) {
  41297. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  41298. }
  41299. // Unbind
  41300. if (!this.isCube || faceIndex === 5) {
  41301. if (this.isCube) {
  41302. if (faceIndex === 5) {
  41303. engine.generateMipMapsForCubemap(this._texture);
  41304. }
  41305. }
  41306. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  41307. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  41308. });
  41309. }
  41310. else {
  41311. this.onAfterRenderObservable.notifyObservers(faceIndex);
  41312. }
  41313. };
  41314. /**
  41315. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  41316. * This allowed control for front to back rendering or reversly depending of the special needs.
  41317. *
  41318. * @param renderingGroupId The rendering group id corresponding to its index
  41319. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  41320. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  41321. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  41322. */
  41323. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  41324. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  41325. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  41326. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  41327. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  41328. };
  41329. /**
  41330. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  41331. *
  41332. * @param renderingGroupId The rendering group id corresponding to its index
  41333. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  41334. */
  41335. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  41336. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  41337. };
  41338. RenderTargetTexture.prototype.clone = function () {
  41339. var textureSize = this.getSize();
  41340. 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);
  41341. // Base texture
  41342. newTexture.hasAlpha = this.hasAlpha;
  41343. newTexture.level = this.level;
  41344. // RenderTarget Texture
  41345. newTexture.coordinatesMode = this.coordinatesMode;
  41346. newTexture.renderList = this.renderList.slice(0);
  41347. return newTexture;
  41348. };
  41349. RenderTargetTexture.prototype.serialize = function () {
  41350. if (!this.name) {
  41351. return null;
  41352. }
  41353. var serializationObject = _super.prototype.serialize.call(this);
  41354. serializationObject.renderTargetSize = this.getRenderSize();
  41355. serializationObject.renderList = [];
  41356. for (var index = 0; index < this.renderList.length; index++) {
  41357. serializationObject.renderList.push(this.renderList[index].id);
  41358. }
  41359. return serializationObject;
  41360. };
  41361. return RenderTargetTexture;
  41362. }(BABYLON.Texture));
  41363. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  41364. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  41365. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  41366. BABYLON.RenderTargetTexture = RenderTargetTexture;
  41367. })(BABYLON || (BABYLON = {}));
  41368. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  41369. /// <reference path="babylon.renderTargetTexture.ts" />
  41370. var BABYLON;
  41371. (function (BABYLON) {
  41372. var MirrorTexture = (function (_super) {
  41373. __extends(MirrorTexture, _super);
  41374. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  41375. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  41376. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  41377. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  41378. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  41379. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  41380. _this._transformMatrix = BABYLON.Matrix.Zero();
  41381. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  41382. _this.onBeforeRenderObservable.add(function () {
  41383. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  41384. _this._savedViewMatrix = scene.getViewMatrix();
  41385. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  41386. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  41387. scene.clipPlane = _this.mirrorPlane;
  41388. scene.getEngine().cullBackFaces = false;
  41389. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  41390. });
  41391. _this.onAfterRenderObservable.add(function () {
  41392. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  41393. scene.getEngine().cullBackFaces = true;
  41394. scene._mirroredCameraPosition = null;
  41395. delete scene.clipPlane;
  41396. });
  41397. return _this;
  41398. }
  41399. MirrorTexture.prototype.clone = function () {
  41400. var textureSize = this.getSize();
  41401. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  41402. // Base texture
  41403. newTexture.hasAlpha = this.hasAlpha;
  41404. newTexture.level = this.level;
  41405. // Mirror Texture
  41406. newTexture.mirrorPlane = this.mirrorPlane.clone();
  41407. newTexture.renderList = this.renderList.slice(0);
  41408. return newTexture;
  41409. };
  41410. MirrorTexture.prototype.serialize = function () {
  41411. if (!this.name) {
  41412. return null;
  41413. }
  41414. var serializationObject = _super.prototype.serialize.call(this);
  41415. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  41416. return serializationObject;
  41417. };
  41418. return MirrorTexture;
  41419. }(BABYLON.RenderTargetTexture));
  41420. BABYLON.MirrorTexture = MirrorTexture;
  41421. })(BABYLON || (BABYLON = {}));
  41422. //# sourceMappingURL=babylon.mirrorTexture.js.map
  41423. /// <reference path="babylon.renderTargetTexture.ts" />
  41424. var BABYLON;
  41425. (function (BABYLON) {
  41426. /**
  41427. * Creates a refraction texture used by refraction channel of the standard material.
  41428. * @param name the texture name
  41429. * @param size size of the underlying texture
  41430. * @param scene root scene
  41431. */
  41432. var RefractionTexture = (function (_super) {
  41433. __extends(RefractionTexture, _super);
  41434. function RefractionTexture(name, size, scene, generateMipMaps) {
  41435. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  41436. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  41437. _this.depth = 2.0;
  41438. _this.onBeforeRenderObservable.add(function () {
  41439. scene.clipPlane = _this.refractionPlane;
  41440. });
  41441. _this.onAfterRenderObservable.add(function () {
  41442. delete scene.clipPlane;
  41443. });
  41444. return _this;
  41445. }
  41446. RefractionTexture.prototype.clone = function () {
  41447. var textureSize = this.getSize();
  41448. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  41449. // Base texture
  41450. newTexture.hasAlpha = this.hasAlpha;
  41451. newTexture.level = this.level;
  41452. // Refraction Texture
  41453. newTexture.refractionPlane = this.refractionPlane.clone();
  41454. newTexture.renderList = this.renderList.slice(0);
  41455. newTexture.depth = this.depth;
  41456. return newTexture;
  41457. };
  41458. RefractionTexture.prototype.serialize = function () {
  41459. if (!this.name) {
  41460. return null;
  41461. }
  41462. var serializationObject = _super.prototype.serialize.call(this);
  41463. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  41464. serializationObject.depth = this.depth;
  41465. return serializationObject;
  41466. };
  41467. return RefractionTexture;
  41468. }(BABYLON.RenderTargetTexture));
  41469. BABYLON.RefractionTexture = RefractionTexture;
  41470. })(BABYLON || (BABYLON = {}));
  41471. //# sourceMappingURL=babylon.refractionTexture.js.map
  41472. /// <reference path="babylon.texture.ts" />
  41473. var BABYLON;
  41474. (function (BABYLON) {
  41475. var DynamicTexture = (function (_super) {
  41476. __extends(DynamicTexture, _super);
  41477. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  41478. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  41479. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  41480. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  41481. _this.name = name;
  41482. var engine = _this.getScene().getEngine();
  41483. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41484. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41485. _this._generateMipMaps = generateMipMaps;
  41486. if (options.getContext) {
  41487. _this._canvas = options;
  41488. _this._texture = engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  41489. }
  41490. else {
  41491. _this._canvas = document.createElement("canvas");
  41492. if (options.width) {
  41493. _this._texture = engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  41494. }
  41495. else {
  41496. _this._texture = engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  41497. }
  41498. }
  41499. var textureSize = _this.getSize();
  41500. _this._canvas.width = textureSize.width;
  41501. _this._canvas.height = textureSize.height;
  41502. _this._context = _this._canvas.getContext("2d");
  41503. return _this;
  41504. }
  41505. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  41506. get: function () {
  41507. return true;
  41508. },
  41509. enumerable: true,
  41510. configurable: true
  41511. });
  41512. DynamicTexture.prototype._recreate = function (textureSize) {
  41513. this._canvas.width = textureSize.width;
  41514. this._canvas.height = textureSize.height;
  41515. this.releaseInternalTexture();
  41516. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  41517. };
  41518. DynamicTexture.prototype.scale = function (ratio) {
  41519. var textureSize = this.getSize();
  41520. textureSize.width *= ratio;
  41521. textureSize.height *= ratio;
  41522. this._recreate(textureSize);
  41523. };
  41524. DynamicTexture.prototype.scaleTo = function (width, height) {
  41525. var textureSize = this.getSize();
  41526. textureSize.width = width;
  41527. textureSize.height = height;
  41528. this._recreate(textureSize);
  41529. };
  41530. DynamicTexture.prototype.getContext = function () {
  41531. return this._context;
  41532. };
  41533. DynamicTexture.prototype.clear = function () {
  41534. var size = this.getSize();
  41535. this._context.fillRect(0, 0, size.width, size.height);
  41536. };
  41537. DynamicTexture.prototype.update = function (invertY) {
  41538. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format);
  41539. };
  41540. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  41541. if (update === void 0) { update = true; }
  41542. var size = this.getSize();
  41543. if (clearColor) {
  41544. this._context.fillStyle = clearColor;
  41545. this._context.fillRect(0, 0, size.width, size.height);
  41546. }
  41547. this._context.font = font;
  41548. if (x === null || x === undefined) {
  41549. var textSize = this._context.measureText(text);
  41550. x = (size.width - textSize.width) / 2;
  41551. }
  41552. if (y === null || y === undefined) {
  41553. var fontSize = parseInt((font.replace(/\D/g, '')));
  41554. ;
  41555. y = (size.height / 2) + (fontSize / 3.65);
  41556. }
  41557. this._context.fillStyle = color;
  41558. this._context.fillText(text, x, y);
  41559. if (update) {
  41560. this.update(invertY);
  41561. }
  41562. };
  41563. DynamicTexture.prototype.clone = function () {
  41564. var textureSize = this.getSize();
  41565. var newTexture = new DynamicTexture(this.name, textureSize, this.getScene(), this._generateMipMaps);
  41566. // Base texture
  41567. newTexture.hasAlpha = this.hasAlpha;
  41568. newTexture.level = this.level;
  41569. // Dynamic Texture
  41570. newTexture.wrapU = this.wrapU;
  41571. newTexture.wrapV = this.wrapV;
  41572. return newTexture;
  41573. };
  41574. return DynamicTexture;
  41575. }(BABYLON.Texture));
  41576. BABYLON.DynamicTexture = DynamicTexture;
  41577. })(BABYLON || (BABYLON = {}));
  41578. //# sourceMappingURL=babylon.dynamicTexture.js.map
  41579. var BABYLON;
  41580. (function (BABYLON) {
  41581. var VideoTexture = (function (_super) {
  41582. __extends(VideoTexture, _super);
  41583. /**
  41584. * Creates a video texture.
  41585. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  41586. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  41587. * @param {BABYLON.Scene} scene is obviously the current scene.
  41588. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  41589. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  41590. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  41591. */
  41592. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  41593. if (generateMipMaps === void 0) { generateMipMaps = false; }
  41594. if (invertY === void 0) { invertY = false; }
  41595. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  41596. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  41597. _this._autoLaunch = true;
  41598. var urls;
  41599. _this.name = name;
  41600. if (urlsOrVideo instanceof HTMLVideoElement) {
  41601. _this.video = urlsOrVideo;
  41602. }
  41603. else {
  41604. urls = urlsOrVideo;
  41605. _this.video = document.createElement("video");
  41606. _this.video.autoplay = false;
  41607. _this.video.loop = true;
  41608. }
  41609. _this._generateMipMaps = generateMipMaps;
  41610. _this._samplingMode = samplingMode;
  41611. if (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight)) {
  41612. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  41613. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  41614. }
  41615. else {
  41616. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41617. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41618. _this._generateMipMaps = false;
  41619. }
  41620. if (urls) {
  41621. _this.video.addEventListener("canplay", function () {
  41622. _this._createTexture();
  41623. });
  41624. urls.forEach(function (url) {
  41625. var source = document.createElement("source");
  41626. source.src = url;
  41627. _this.video.appendChild(source);
  41628. });
  41629. }
  41630. else {
  41631. _this._createTexture();
  41632. }
  41633. _this._lastUpdate = BABYLON.Tools.Now;
  41634. return _this;
  41635. }
  41636. VideoTexture.prototype._createTexture = function () {
  41637. var _this = this;
  41638. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  41639. if (this._autoLaunch) {
  41640. this._autoLaunch = false;
  41641. this.video.play();
  41642. }
  41643. this.video.addEventListener("playing", function () {
  41644. _this._texture.isReady = true;
  41645. });
  41646. };
  41647. VideoTexture.prototype.update = function () {
  41648. var now = BABYLON.Tools.Now;
  41649. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  41650. return false;
  41651. }
  41652. this._lastUpdate = now;
  41653. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  41654. return true;
  41655. };
  41656. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  41657. var video = document.createElement("video");
  41658. var constraintsDeviceId;
  41659. if (constraints && constraints.deviceId) {
  41660. constraintsDeviceId = {
  41661. exact: constraints.deviceId
  41662. };
  41663. }
  41664. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  41665. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  41666. if (navigator.getUserMedia) {
  41667. navigator.getUserMedia({
  41668. video: {
  41669. deviceId: constraintsDeviceId,
  41670. width: {
  41671. min: (constraints && constraints.minWidth) || 256,
  41672. max: (constraints && constraints.maxWidth) || 640
  41673. },
  41674. height: {
  41675. min: (constraints && constraints.minHeight) || 256,
  41676. max: (constraints && constraints.maxHeight) || 480
  41677. }
  41678. }
  41679. }, function (stream) {
  41680. if (video.mozSrcObject !== undefined) {
  41681. video.mozSrcObject = stream;
  41682. }
  41683. else {
  41684. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  41685. }
  41686. video.play();
  41687. if (onReady) {
  41688. onReady(new BABYLON.VideoTexture("video", video, scene, true, true));
  41689. }
  41690. }, function (e) {
  41691. BABYLON.Tools.Error(e.name);
  41692. });
  41693. }
  41694. };
  41695. return VideoTexture;
  41696. }(BABYLON.Texture));
  41697. BABYLON.VideoTexture = VideoTexture;
  41698. })(BABYLON || (BABYLON = {}));
  41699. //# sourceMappingURL=babylon.videoTexture.js.map
  41700. var BABYLON;
  41701. (function (BABYLON) {
  41702. var RawTexture = (function (_super) {
  41703. __extends(RawTexture, _super);
  41704. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  41705. if (generateMipMaps === void 0) { generateMipMaps = true; }
  41706. if (invertY === void 0) { invertY = false; }
  41707. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  41708. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  41709. _this.format = format;
  41710. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  41711. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41712. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41713. return _this;
  41714. }
  41715. RawTexture.prototype.update = function (data) {
  41716. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  41717. };
  41718. // Statics
  41719. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  41720. if (generateMipMaps === void 0) { generateMipMaps = true; }
  41721. if (invertY === void 0) { invertY = false; }
  41722. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  41723. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  41724. };
  41725. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  41726. if (generateMipMaps === void 0) { generateMipMaps = true; }
  41727. if (invertY === void 0) { invertY = false; }
  41728. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  41729. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  41730. };
  41731. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  41732. if (generateMipMaps === void 0) { generateMipMaps = true; }
  41733. if (invertY === void 0) { invertY = false; }
  41734. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  41735. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  41736. };
  41737. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  41738. if (generateMipMaps === void 0) { generateMipMaps = true; }
  41739. if (invertY === void 0) { invertY = false; }
  41740. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  41741. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  41742. };
  41743. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  41744. if (generateMipMaps === void 0) { generateMipMaps = true; }
  41745. if (invertY === void 0) { invertY = false; }
  41746. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  41747. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  41748. };
  41749. return RawTexture;
  41750. }(BABYLON.Texture));
  41751. BABYLON.RawTexture = RawTexture;
  41752. })(BABYLON || (BABYLON = {}));
  41753. //# sourceMappingURL=babylon.rawTexture.js.map
  41754. var BABYLON;
  41755. (function (BABYLON) {
  41756. var PostProcess = (function () {
  41757. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl) {
  41758. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  41759. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  41760. if (vertexUrl === void 0) { vertexUrl = 'postprocess'; }
  41761. this.name = name;
  41762. this.width = -1;
  41763. this.height = -1;
  41764. /*
  41765. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  41766. Can only be used on a single postprocess or on the last one of a chain.
  41767. */
  41768. this.enablePixelPerfectMode = false;
  41769. this.samples = 1;
  41770. this._reusable = false;
  41771. this._textures = new BABYLON.SmartArray(2);
  41772. this._currentRenderTextureInd = 0;
  41773. this._scaleRatio = new BABYLON.Vector2(1, 1);
  41774. // Events
  41775. /**
  41776. * An event triggered when the postprocess is activated.
  41777. * @type {BABYLON.Observable}
  41778. */
  41779. this.onActivateObservable = new BABYLON.Observable();
  41780. /**
  41781. * An event triggered when the postprocess changes its size.
  41782. * @type {BABYLON.Observable}
  41783. */
  41784. this.onSizeChangedObservable = new BABYLON.Observable();
  41785. /**
  41786. * An event triggered when the postprocess applies its effect.
  41787. * @type {BABYLON.Observable}
  41788. */
  41789. this.onApplyObservable = new BABYLON.Observable();
  41790. /**
  41791. * An event triggered before rendering the postprocess
  41792. * @type {BABYLON.Observable}
  41793. */
  41794. this.onBeforeRenderObservable = new BABYLON.Observable();
  41795. /**
  41796. * An event triggered after rendering the postprocess
  41797. * @type {BABYLON.Observable}
  41798. */
  41799. this.onAfterRenderObservable = new BABYLON.Observable();
  41800. if (camera != null) {
  41801. this._camera = camera;
  41802. this._scene = camera.getScene();
  41803. camera.attachPostProcess(this);
  41804. this._engine = this._scene.getEngine();
  41805. }
  41806. else {
  41807. this._engine = engine;
  41808. }
  41809. this._options = options;
  41810. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  41811. this._reusable = reusable || false;
  41812. this._textureType = textureType;
  41813. this._samplers = samplers || [];
  41814. this._samplers.push("textureSampler");
  41815. this._fragmentUrl = fragmentUrl;
  41816. this._vertexUrl = vertexUrl;
  41817. this._parameters = parameters || [];
  41818. this._parameters.push("scale");
  41819. this.updateEffect(defines);
  41820. }
  41821. Object.defineProperty(PostProcess.prototype, "onActivate", {
  41822. set: function (callback) {
  41823. if (this._onActivateObserver) {
  41824. this.onActivateObservable.remove(this._onActivateObserver);
  41825. }
  41826. this._onActivateObserver = this.onActivateObservable.add(callback);
  41827. },
  41828. enumerable: true,
  41829. configurable: true
  41830. });
  41831. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  41832. set: function (callback) {
  41833. if (this._onSizeChangedObserver) {
  41834. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  41835. }
  41836. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  41837. },
  41838. enumerable: true,
  41839. configurable: true
  41840. });
  41841. Object.defineProperty(PostProcess.prototype, "onApply", {
  41842. set: function (callback) {
  41843. if (this._onApplyObserver) {
  41844. this.onApplyObservable.remove(this._onApplyObserver);
  41845. }
  41846. this._onApplyObserver = this.onApplyObservable.add(callback);
  41847. },
  41848. enumerable: true,
  41849. configurable: true
  41850. });
  41851. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  41852. set: function (callback) {
  41853. if (this._onBeforeRenderObserver) {
  41854. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  41855. }
  41856. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  41857. },
  41858. enumerable: true,
  41859. configurable: true
  41860. });
  41861. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  41862. set: function (callback) {
  41863. if (this._onAfterRenderObserver) {
  41864. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  41865. }
  41866. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  41867. },
  41868. enumerable: true,
  41869. configurable: true
  41870. });
  41871. PostProcess.prototype.updateEffect = function (defines) {
  41872. this._effect = this._engine.createEffect({ vertex: this._vertexUrl, fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  41873. };
  41874. PostProcess.prototype.isReusable = function () {
  41875. return this._reusable;
  41876. };
  41877. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  41878. PostProcess.prototype.markTextureDirty = function () {
  41879. this.width = -1;
  41880. };
  41881. PostProcess.prototype.activate = function (camera, sourceTexture) {
  41882. var _this = this;
  41883. camera = camera || this._camera;
  41884. var scene = camera.getScene();
  41885. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  41886. var requiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._options) | 0;
  41887. var requiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._options) | 0;
  41888. var desiredWidth = this._options.width || requiredWidth;
  41889. var desiredHeight = this._options.height || requiredHeight;
  41890. if (this.renderTargetSamplingMode !== BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  41891. if (!this._options.width) {
  41892. desiredWidth = BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  41893. }
  41894. if (!this._options.height) {
  41895. desiredHeight = BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  41896. }
  41897. }
  41898. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  41899. if (this._textures.length > 0) {
  41900. for (var i = 0; i < this._textures.length; i++) {
  41901. this._engine._releaseTexture(this._textures.data[i]);
  41902. }
  41903. this._textures.reset();
  41904. }
  41905. this.width = desiredWidth;
  41906. this.height = desiredHeight;
  41907. var textureSize = { width: this.width, height: this.height };
  41908. var textureOptions = {
  41909. generateMipMaps: false,
  41910. generateDepthBuffer: camera._postProcesses.indexOf(this) === 0,
  41911. generateStencilBuffer: camera._postProcesses.indexOf(this) === 0 && this._engine.isStencilEnable,
  41912. samplingMode: this.renderTargetSamplingMode,
  41913. type: this._textureType
  41914. };
  41915. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  41916. if (this._reusable) {
  41917. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  41918. }
  41919. this.onSizeChangedObservable.notifyObservers(this);
  41920. }
  41921. this._textures.forEach(function (texture) {
  41922. if (texture.samples !== _this.samples) {
  41923. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  41924. }
  41925. });
  41926. if (this.enablePixelPerfectMode) {
  41927. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  41928. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd], 0, requiredWidth, requiredHeight);
  41929. }
  41930. else {
  41931. this._scaleRatio.copyFromFloats(1, 1);
  41932. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  41933. }
  41934. this.onActivateObservable.notifyObservers(camera);
  41935. // Clear
  41936. if (this.clearColor) {
  41937. this._engine.clear(this.clearColor, true, true, true);
  41938. }
  41939. else {
  41940. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true, true);
  41941. }
  41942. if (this._reusable) {
  41943. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  41944. }
  41945. };
  41946. Object.defineProperty(PostProcess.prototype, "isSupported", {
  41947. get: function () {
  41948. return this._effect.isSupported;
  41949. },
  41950. enumerable: true,
  41951. configurable: true
  41952. });
  41953. PostProcess.prototype.apply = function () {
  41954. // Check
  41955. if (!this._effect.isReady())
  41956. return null;
  41957. // States
  41958. this._engine.enableEffect(this._effect);
  41959. this._engine.setState(false);
  41960. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  41961. this._engine.setDepthBuffer(false);
  41962. this._engine.setDepthWrite(false);
  41963. // Texture
  41964. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  41965. // Parameters
  41966. this._effect.setVector2("scale", this._scaleRatio);
  41967. this.onApplyObservable.notifyObservers(this._effect);
  41968. return this._effect;
  41969. };
  41970. PostProcess.prototype.dispose = function (camera) {
  41971. camera = camera || this._camera;
  41972. if (this._textures.length > 0) {
  41973. for (var i = 0; i < this._textures.length; i++) {
  41974. this._engine._releaseTexture(this._textures.data[i]);
  41975. }
  41976. }
  41977. this._textures.dispose();
  41978. if (!camera) {
  41979. return;
  41980. }
  41981. camera.detachPostProcess(this);
  41982. var index = camera._postProcesses.indexOf(this);
  41983. if (index === 0 && camera._postProcesses.length > 0) {
  41984. this._camera._postProcesses[0].markTextureDirty();
  41985. }
  41986. this.onActivateObservable.clear();
  41987. this.onAfterRenderObservable.clear();
  41988. this.onApplyObservable.clear();
  41989. this.onBeforeRenderObservable.clear();
  41990. this.onSizeChangedObservable.clear();
  41991. };
  41992. return PostProcess;
  41993. }());
  41994. BABYLON.PostProcess = PostProcess;
  41995. })(BABYLON || (BABYLON = {}));
  41996. //# sourceMappingURL=babylon.postProcess.js.map
  41997. var BABYLON;
  41998. (function (BABYLON) {
  41999. var PassPostProcess = (function (_super) {
  42000. __extends(PassPostProcess, _super);
  42001. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  42002. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  42003. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  42004. }
  42005. return PassPostProcess;
  42006. }(BABYLON.PostProcess));
  42007. BABYLON.PassPostProcess = PassPostProcess;
  42008. })(BABYLON || (BABYLON = {}));
  42009. //# sourceMappingURL=babylon.passPostProcess.js.map
  42010. var BABYLON;
  42011. (function (BABYLON) {
  42012. var ShadowGenerator = (function () {
  42013. /**
  42014. * Creates a ShadowGenerator object.
  42015. * A ShadowGenerator is the required tool to use the shadows.
  42016. * Each light casting shadows needs to use its own ShadowGenerator.
  42017. * Required parameters :
  42018. * - `mapSize` (integer), the size of the texture what stores the shadows. Example : 1024.
  42019. * - `light` : the light object generating the shadows.
  42020. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  42021. */
  42022. function ShadowGenerator(mapSize, light) {
  42023. var _this = this;
  42024. // Members
  42025. this._filter = ShadowGenerator.FILTER_NONE;
  42026. this.blurScale = 2;
  42027. this._blurBoxOffset = 0;
  42028. this._bias = 0.00005;
  42029. this._lightDirection = BABYLON.Vector3.Zero();
  42030. this.forceBackFacesOnly = false;
  42031. this._darkness = 0;
  42032. this._transparencyShadow = false;
  42033. this._viewMatrix = BABYLON.Matrix.Zero();
  42034. this._projectionMatrix = BABYLON.Matrix.Zero();
  42035. this._transformMatrix = BABYLON.Matrix.Zero();
  42036. this._worldViewProjection = BABYLON.Matrix.Zero();
  42037. this._currentFaceIndex = 0;
  42038. this._currentFaceIndexCache = 0;
  42039. this._useFullFloat = true;
  42040. this._light = light;
  42041. this._scene = light.getScene();
  42042. this._mapSize = mapSize;
  42043. light._shadowGenerator = this;
  42044. light._markMeshesAsLightDirty();
  42045. // Texture type fallback from float to int if not supported.
  42046. var textureType;
  42047. var caps = this._scene.getEngine().getCaps();
  42048. if (caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender) {
  42049. this._useFullFloat = true;
  42050. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  42051. }
  42052. else {
  42053. this._useFullFloat = false;
  42054. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  42055. }
  42056. // Render target
  42057. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, textureType, light.needCube());
  42058. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  42059. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  42060. this._shadowMap.anisotropicFilteringLevel = 1;
  42061. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  42062. this._shadowMap.renderParticles = false;
  42063. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  42064. _this._currentFaceIndex = faceIndex;
  42065. });
  42066. this._shadowMap.onAfterUnbindObservable.add(function () {
  42067. if (!_this.useBlurExponentialShadowMap) {
  42068. return;
  42069. }
  42070. if (!_this._shadowMap2) {
  42071. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false, true, textureType);
  42072. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  42073. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  42074. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  42075. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine(), false, textureType);
  42076. _this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  42077. effect.setTexture("textureSampler", _this._shadowMap);
  42078. });
  42079. _this.blurBoxOffset = 1;
  42080. }
  42081. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  42082. });
  42083. // Custom render function
  42084. var renderSubMesh = function (subMesh) {
  42085. var mesh = subMesh.getRenderingMesh();
  42086. var scene = _this._scene;
  42087. var engine = scene.getEngine();
  42088. // Culling
  42089. engine.setState(subMesh.getMaterial().backFaceCulling);
  42090. // Managing instances
  42091. var batch = mesh._getInstancesRenderList(subMesh._id);
  42092. if (batch.mustReturn) {
  42093. return;
  42094. }
  42095. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  42096. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  42097. engine.enableEffect(_this._effect);
  42098. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  42099. var material = subMesh.getMaterial();
  42100. _this._effect.setFloat2("biasAndScale", _this.bias, _this.depthScale);
  42101. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  42102. _this._effect.setVector3("lightPosition", _this.getLight().position);
  42103. if (_this.getLight().needCube()) {
  42104. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  42105. }
  42106. // Alpha test
  42107. if (material && material.needAlphaTesting()) {
  42108. var alphaTexture = material.getAlphaTestTexture();
  42109. _this._effect.setTexture("diffuseSampler", alphaTexture);
  42110. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  42111. }
  42112. // Bones
  42113. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  42114. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  42115. }
  42116. if (_this.forceBackFacesOnly) {
  42117. engine.setState(true, 0, false, true);
  42118. }
  42119. // Draw
  42120. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  42121. if (_this.forceBackFacesOnly) {
  42122. engine.setState(true, 0, false, false);
  42123. }
  42124. }
  42125. else {
  42126. // Need to reset refresh rate of the shadowMap
  42127. _this._shadowMap.resetRefreshCounter();
  42128. }
  42129. };
  42130. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  42131. var index;
  42132. for (index = 0; index < opaqueSubMeshes.length; index++) {
  42133. renderSubMesh(opaqueSubMeshes.data[index]);
  42134. }
  42135. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  42136. renderSubMesh(alphaTestSubMeshes.data[index]);
  42137. }
  42138. if (_this._transparencyShadow) {
  42139. for (index = 0; index < transparentSubMeshes.length; index++) {
  42140. renderSubMesh(transparentSubMeshes.data[index]);
  42141. }
  42142. }
  42143. };
  42144. this._shadowMap.onClearObservable.add(function (engine) {
  42145. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  42146. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  42147. }
  42148. else {
  42149. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  42150. }
  42151. });
  42152. }
  42153. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  42154. // Static
  42155. get: function () {
  42156. return ShadowGenerator._FILTER_NONE;
  42157. },
  42158. enumerable: true,
  42159. configurable: true
  42160. });
  42161. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  42162. get: function () {
  42163. return ShadowGenerator._FILTER_POISSONSAMPLING;
  42164. },
  42165. enumerable: true,
  42166. configurable: true
  42167. });
  42168. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  42169. get: function () {
  42170. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  42171. },
  42172. enumerable: true,
  42173. configurable: true
  42174. });
  42175. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  42176. get: function () {
  42177. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  42178. },
  42179. enumerable: true,
  42180. configurable: true
  42181. });
  42182. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  42183. get: function () {
  42184. return this._bias;
  42185. },
  42186. set: function (bias) {
  42187. this._bias = bias;
  42188. },
  42189. enumerable: true,
  42190. configurable: true
  42191. });
  42192. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  42193. get: function () {
  42194. return this._blurBoxOffset;
  42195. },
  42196. set: function (value) {
  42197. var _this = this;
  42198. if (this._blurBoxOffset === value) {
  42199. return;
  42200. }
  42201. this._blurBoxOffset = value;
  42202. if (this._boxBlurPostprocess) {
  42203. this._boxBlurPostprocess.dispose();
  42204. }
  42205. var textureType;
  42206. var caps = this._scene.getEngine().getCaps();
  42207. if (this._useFullFloat) {
  42208. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  42209. }
  42210. else {
  42211. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  42212. }
  42213. 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);
  42214. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  42215. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  42216. });
  42217. },
  42218. enumerable: true,
  42219. configurable: true
  42220. });
  42221. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  42222. get: function () {
  42223. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  42224. },
  42225. set: function (value) {
  42226. this._depthScale = value;
  42227. },
  42228. enumerable: true,
  42229. configurable: true
  42230. });
  42231. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  42232. get: function () {
  42233. return this._filter;
  42234. },
  42235. set: function (value) {
  42236. if (this._filter === value) {
  42237. return;
  42238. }
  42239. this._filter = value;
  42240. if (this.usePoissonSampling || this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  42241. this._shadowMap.anisotropicFilteringLevel = 16;
  42242. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  42243. }
  42244. else {
  42245. this._shadowMap.anisotropicFilteringLevel = 1;
  42246. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  42247. }
  42248. this._light._markMeshesAsLightDirty();
  42249. },
  42250. enumerable: true,
  42251. configurable: true
  42252. });
  42253. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  42254. get: function () {
  42255. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  42256. return this.useExponentialShadowMap;
  42257. },
  42258. set: function (value) {
  42259. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  42260. this.useExponentialShadowMap = value;
  42261. },
  42262. enumerable: true,
  42263. configurable: true
  42264. });
  42265. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  42266. get: function () {
  42267. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  42268. },
  42269. set: function (value) {
  42270. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  42271. },
  42272. enumerable: true,
  42273. configurable: true
  42274. });
  42275. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  42276. get: function () {
  42277. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  42278. },
  42279. set: function (value) {
  42280. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  42281. },
  42282. enumerable: true,
  42283. configurable: true
  42284. });
  42285. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  42286. get: function () {
  42287. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  42288. return this.useBlurExponentialShadowMap;
  42289. },
  42290. set: function (value) {
  42291. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  42292. this.useBlurExponentialShadowMap = value;
  42293. },
  42294. enumerable: true,
  42295. configurable: true
  42296. });
  42297. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  42298. get: function () {
  42299. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  42300. },
  42301. set: function (value) {
  42302. if (this._light.needCube() && value) {
  42303. this.useExponentialShadowMap = true; // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  42304. }
  42305. else {
  42306. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  42307. }
  42308. },
  42309. enumerable: true,
  42310. configurable: true
  42311. });
  42312. /**
  42313. * Boolean : true when the ShadowGenerator is finally computed.
  42314. */
  42315. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  42316. var defines = [];
  42317. if (this._useFullFloat) {
  42318. defines.push("#define FULLFLOAT");
  42319. }
  42320. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  42321. defines.push("#define ESM");
  42322. }
  42323. if (this.getLight().needCube()) {
  42324. defines.push("#define CUBEMAP");
  42325. }
  42326. var attribs = [BABYLON.VertexBuffer.PositionKind];
  42327. var mesh = subMesh.getMesh();
  42328. var material = subMesh.getMaterial();
  42329. // Alpha test
  42330. if (material && material.needAlphaTesting()) {
  42331. defines.push("#define ALPHATEST");
  42332. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  42333. attribs.push(BABYLON.VertexBuffer.UVKind);
  42334. defines.push("#define UV1");
  42335. }
  42336. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  42337. var alphaTexture = material.getAlphaTestTexture();
  42338. if (alphaTexture.coordinatesIndex === 1) {
  42339. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  42340. defines.push("#define UV2");
  42341. }
  42342. }
  42343. }
  42344. // Bones
  42345. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  42346. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  42347. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  42348. if (mesh.numBoneInfluencers > 4) {
  42349. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  42350. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  42351. }
  42352. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  42353. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  42354. }
  42355. else {
  42356. defines.push("#define NUM_BONE_INFLUENCERS 0");
  42357. }
  42358. // Instances
  42359. if (useInstances) {
  42360. defines.push("#define INSTANCES");
  42361. attribs.push("world0");
  42362. attribs.push("world1");
  42363. attribs.push("world2");
  42364. attribs.push("world3");
  42365. }
  42366. // Get correct effect
  42367. var join = defines.join("\n");
  42368. if (this._cachedDefines !== join) {
  42369. this._cachedDefines = join;
  42370. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  42371. }
  42372. return this._effect.isReady();
  42373. };
  42374. /**
  42375. * Returns a RenderTargetTexture object : the shadow map texture.
  42376. */
  42377. ShadowGenerator.prototype.getShadowMap = function () {
  42378. return this._shadowMap;
  42379. };
  42380. /**
  42381. * Returns the most ready computed shadow map as a RenderTargetTexture object.
  42382. */
  42383. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  42384. if (this._shadowMap2) {
  42385. return this._shadowMap2;
  42386. }
  42387. return this._shadowMap;
  42388. };
  42389. /**
  42390. * Returns the associated light object.
  42391. */
  42392. ShadowGenerator.prototype.getLight = function () {
  42393. return this._light;
  42394. };
  42395. // Methods
  42396. /**
  42397. * Returns a Matrix object : the updated transformation matrix.
  42398. */
  42399. ShadowGenerator.prototype.getTransformMatrix = function () {
  42400. var scene = this._scene;
  42401. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  42402. return this._transformMatrix;
  42403. }
  42404. this._currentRenderID = scene.getRenderId();
  42405. this._currentFaceIndexCache = this._currentFaceIndex;
  42406. var lightPosition = this._light.position;
  42407. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  42408. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  42409. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  42410. }
  42411. if (this._light.computeTransformedPosition()) {
  42412. lightPosition = this._light.transformedPosition;
  42413. }
  42414. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  42415. this._cachedPosition = lightPosition.clone();
  42416. this._cachedDirection = this._lightDirection.clone();
  42417. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  42418. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  42419. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  42420. }
  42421. return this._transformMatrix;
  42422. };
  42423. /**
  42424. * Returns the darkness value (float).
  42425. */
  42426. ShadowGenerator.prototype.getDarkness = function () {
  42427. return this._darkness;
  42428. };
  42429. /**
  42430. * Sets the ShadowGenerator darkness value (float <= 1.0).
  42431. * Returns the ShadowGenerator.
  42432. */
  42433. ShadowGenerator.prototype.setDarkness = function (darkness) {
  42434. if (darkness >= 1.0)
  42435. this._darkness = 1.0;
  42436. else if (darkness <= 0.0)
  42437. this._darkness = 0.0;
  42438. else
  42439. this._darkness = darkness;
  42440. return this;
  42441. };
  42442. /**
  42443. * Sets the ability to have transparent shadow (boolean).
  42444. * Returns the ShadowGenerator.
  42445. */
  42446. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  42447. this._transparencyShadow = hasShadow;
  42448. return this;
  42449. };
  42450. ShadowGenerator.prototype._packHalf = function (depth) {
  42451. var scale = depth * 255.0;
  42452. var fract = scale - Math.floor(scale);
  42453. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  42454. };
  42455. /**
  42456. * Disposes the ShadowGenerator.
  42457. * Returns nothing.
  42458. */
  42459. ShadowGenerator.prototype.dispose = function () {
  42460. this._shadowMap.dispose();
  42461. if (this._shadowMap2) {
  42462. this._shadowMap2.dispose();
  42463. }
  42464. if (this._downSamplePostprocess) {
  42465. this._downSamplePostprocess.dispose();
  42466. }
  42467. if (this._boxBlurPostprocess) {
  42468. this._boxBlurPostprocess.dispose();
  42469. }
  42470. this._light._shadowGenerator = null;
  42471. this._light._markMeshesAsLightDirty();
  42472. };
  42473. /**
  42474. * Serializes the ShadowGenerator and returns a serializationObject.
  42475. */
  42476. ShadowGenerator.prototype.serialize = function () {
  42477. var serializationObject = {};
  42478. serializationObject.lightId = this._light.id;
  42479. serializationObject.mapSize = this.getShadowMap().getRenderSize();
  42480. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  42481. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  42482. serializationObject.usePoissonSampling = this.usePoissonSampling;
  42483. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  42484. serializationObject.depthScale = this.depthScale;
  42485. serializationObject.darkness = this.getDarkness();
  42486. serializationObject.renderList = [];
  42487. for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
  42488. var mesh = this.getShadowMap().renderList[meshIndex];
  42489. serializationObject.renderList.push(mesh.id);
  42490. }
  42491. return serializationObject;
  42492. };
  42493. /**
  42494. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  42495. */
  42496. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  42497. //casting to point light, as light is missing the position attr and typescript complains.
  42498. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  42499. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  42500. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  42501. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  42502. meshes.forEach(function (mesh) {
  42503. shadowGenerator.getShadowMap().renderList.push(mesh);
  42504. });
  42505. }
  42506. if (parsedShadowGenerator.usePoissonSampling) {
  42507. shadowGenerator.usePoissonSampling = true;
  42508. }
  42509. else if (parsedShadowGenerator.useExponentialShadowMap) {
  42510. shadowGenerator.useExponentialShadowMap = true;
  42511. }
  42512. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  42513. shadowGenerator.useBlurExponentialShadowMap = true;
  42514. }
  42515. else if (parsedShadowGenerator.useVarianceShadowMap) {
  42516. shadowGenerator.useExponentialShadowMap = true;
  42517. }
  42518. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  42519. shadowGenerator.useBlurExponentialShadowMap = true;
  42520. }
  42521. if (parsedShadowGenerator.depthScale) {
  42522. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  42523. }
  42524. if (parsedShadowGenerator.blurScale) {
  42525. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  42526. }
  42527. if (parsedShadowGenerator.blurBoxOffset) {
  42528. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  42529. }
  42530. if (parsedShadowGenerator.bias !== undefined) {
  42531. shadowGenerator.bias = parsedShadowGenerator.bias;
  42532. }
  42533. if (parsedShadowGenerator.darkness) {
  42534. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  42535. }
  42536. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  42537. return shadowGenerator;
  42538. };
  42539. return ShadowGenerator;
  42540. }());
  42541. ShadowGenerator._FILTER_NONE = 0;
  42542. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  42543. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  42544. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  42545. BABYLON.ShadowGenerator = ShadowGenerator;
  42546. })(BABYLON || (BABYLON = {}));
  42547. //# sourceMappingURL=babylon.shadowGenerator.js.map
  42548. var BABYLON;
  42549. (function (BABYLON) {
  42550. var DefaultLoadingScreen = (function () {
  42551. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  42552. if (_loadingText === void 0) { _loadingText = ""; }
  42553. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  42554. var _this = this;
  42555. this._renderingCanvas = _renderingCanvas;
  42556. this._loadingText = _loadingText;
  42557. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  42558. // Resize
  42559. this._resizeLoadingUI = function () {
  42560. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  42561. _this._loadingDiv.style.position = "absolute";
  42562. _this._loadingDiv.style.left = canvasRect.left + "px";
  42563. _this._loadingDiv.style.top = canvasRect.top + "px";
  42564. _this._loadingDiv.style.width = canvasRect.width + "px";
  42565. _this._loadingDiv.style.height = canvasRect.height + "px";
  42566. };
  42567. }
  42568. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  42569. var _this = this;
  42570. if (this._loadingDiv) {
  42571. // Do not add a loading screen if there is already one
  42572. return;
  42573. }
  42574. this._loadingDiv = document.createElement("div");
  42575. this._loadingDiv.id = "babylonjsLoadingDiv";
  42576. this._loadingDiv.style.opacity = "0";
  42577. this._loadingDiv.style.transition = "opacity 1.5s ease";
  42578. // Loading text
  42579. this._loadingTextDiv = document.createElement("div");
  42580. this._loadingTextDiv.style.position = "absolute";
  42581. this._loadingTextDiv.style.left = "0";
  42582. this._loadingTextDiv.style.top = "50%";
  42583. this._loadingTextDiv.style.marginTop = "80px";
  42584. this._loadingTextDiv.style.width = "100%";
  42585. this._loadingTextDiv.style.height = "20px";
  42586. this._loadingTextDiv.style.fontFamily = "Arial";
  42587. this._loadingTextDiv.style.fontSize = "14px";
  42588. this._loadingTextDiv.style.color = "white";
  42589. this._loadingTextDiv.style.textAlign = "center";
  42590. this._loadingTextDiv.innerHTML = "Loading";
  42591. this._loadingDiv.appendChild(this._loadingTextDiv);
  42592. //set the predefined text
  42593. this._loadingTextDiv.innerHTML = this._loadingText;
  42594. // Loading img
  42595. var imgBack = new Image();
  42596. 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==";
  42597. imgBack.style.position = "absolute";
  42598. imgBack.style.left = "50%";
  42599. imgBack.style.top = "50%";
  42600. imgBack.style.marginLeft = "-50px";
  42601. imgBack.style.marginTop = "-50px";
  42602. imgBack.style.transition = "transform 1.0s ease";
  42603. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  42604. var deg = 360;
  42605. var onTransitionEnd = function () {
  42606. deg += 360;
  42607. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  42608. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  42609. };
  42610. imgBack.addEventListener("transitionend", onTransitionEnd);
  42611. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  42612. this._loadingDiv.appendChild(imgBack);
  42613. // front image
  42614. var imgFront = new Image();
  42615. 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=";
  42616. imgFront.style.position = "absolute";
  42617. imgFront.style.left = "50%";
  42618. imgFront.style.top = "50%";
  42619. imgFront.style.marginLeft = "-50px";
  42620. imgFront.style.marginTop = "-50px";
  42621. this._loadingDiv.appendChild(imgFront);
  42622. this._resizeLoadingUI();
  42623. window.addEventListener("resize", this._resizeLoadingUI);
  42624. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  42625. document.body.appendChild(this._loadingDiv);
  42626. setTimeout(function () {
  42627. _this._loadingDiv.style.opacity = "1";
  42628. imgBack.style.transform = "rotateZ(360deg)";
  42629. imgBack.style.webkitTransform = "rotateZ(360deg)";
  42630. }, 0);
  42631. };
  42632. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  42633. var _this = this;
  42634. if (!this._loadingDiv) {
  42635. return;
  42636. }
  42637. var onTransitionEnd = function () {
  42638. if (!_this._loadingDiv) {
  42639. return;
  42640. }
  42641. document.body.removeChild(_this._loadingDiv);
  42642. window.removeEventListener("resize", _this._resizeLoadingUI);
  42643. _this._loadingDiv = null;
  42644. };
  42645. this._loadingDiv.style.opacity = "0";
  42646. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  42647. };
  42648. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  42649. set: function (text) {
  42650. this._loadingText = text;
  42651. if (this._loadingTextDiv) {
  42652. this._loadingTextDiv.innerHTML = this._loadingText;
  42653. }
  42654. },
  42655. enumerable: true,
  42656. configurable: true
  42657. });
  42658. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  42659. get: function () {
  42660. return this._loadingDivBackgroundColor;
  42661. },
  42662. set: function (color) {
  42663. this._loadingDivBackgroundColor = color;
  42664. if (!this._loadingDiv) {
  42665. return;
  42666. }
  42667. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  42668. },
  42669. enumerable: true,
  42670. configurable: true
  42671. });
  42672. return DefaultLoadingScreen;
  42673. }());
  42674. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  42675. })(BABYLON || (BABYLON = {}));
  42676. //# sourceMappingURL=babylon.loadingScreen.js.map
  42677. var BABYLON;
  42678. (function (BABYLON) {
  42679. var SceneLoader = (function () {
  42680. function SceneLoader() {
  42681. }
  42682. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  42683. get: function () {
  42684. return 0;
  42685. },
  42686. enumerable: true,
  42687. configurable: true
  42688. });
  42689. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  42690. get: function () {
  42691. return 1;
  42692. },
  42693. enumerable: true,
  42694. configurable: true
  42695. });
  42696. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  42697. get: function () {
  42698. return 2;
  42699. },
  42700. enumerable: true,
  42701. configurable: true
  42702. });
  42703. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  42704. get: function () {
  42705. return 3;
  42706. },
  42707. enumerable: true,
  42708. configurable: true
  42709. });
  42710. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  42711. get: function () {
  42712. return SceneLoader._ForceFullSceneLoadingForIncremental;
  42713. },
  42714. set: function (value) {
  42715. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  42716. },
  42717. enumerable: true,
  42718. configurable: true
  42719. });
  42720. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  42721. get: function () {
  42722. return SceneLoader._ShowLoadingScreen;
  42723. },
  42724. set: function (value) {
  42725. SceneLoader._ShowLoadingScreen = value;
  42726. },
  42727. enumerable: true,
  42728. configurable: true
  42729. });
  42730. Object.defineProperty(SceneLoader, "loggingLevel", {
  42731. get: function () {
  42732. return SceneLoader._loggingLevel;
  42733. },
  42734. set: function (value) {
  42735. SceneLoader._loggingLevel = value;
  42736. },
  42737. enumerable: true,
  42738. configurable: true
  42739. });
  42740. SceneLoader._getDefaultPlugin = function () {
  42741. return SceneLoader._registeredPlugins[".babylon"];
  42742. };
  42743. SceneLoader._getPluginForExtension = function (extension) {
  42744. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  42745. if (registeredPlugin) {
  42746. return registeredPlugin;
  42747. }
  42748. return SceneLoader._getDefaultPlugin();
  42749. };
  42750. SceneLoader._getPluginForFilename = function (sceneFilename) {
  42751. if (sceneFilename.name) {
  42752. sceneFilename = sceneFilename.name;
  42753. }
  42754. var dotPosition = sceneFilename.lastIndexOf(".");
  42755. var queryStringPosition = sceneFilename.indexOf("?");
  42756. if (queryStringPosition === -1) {
  42757. queryStringPosition = sceneFilename.length;
  42758. }
  42759. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  42760. return SceneLoader._getPluginForExtension(extension);
  42761. };
  42762. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  42763. SceneLoader._getDirectLoad = function (sceneFilename) {
  42764. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  42765. return sceneFilename.substr(5);
  42766. }
  42767. return null;
  42768. };
  42769. // Public functions
  42770. SceneLoader.GetPluginForExtension = function (extension) {
  42771. return SceneLoader._getPluginForExtension(extension).plugin;
  42772. };
  42773. SceneLoader.RegisterPlugin = function (plugin) {
  42774. if (typeof plugin.extensions === "string") {
  42775. var extension = plugin.extensions;
  42776. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  42777. plugin: plugin,
  42778. isBinary: false
  42779. };
  42780. }
  42781. else {
  42782. var extensions = plugin.extensions;
  42783. Object.keys(extensions).forEach(function (extension) {
  42784. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  42785. plugin: plugin,
  42786. isBinary: extensions[extension].isBinary
  42787. };
  42788. });
  42789. }
  42790. };
  42791. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  42792. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  42793. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  42794. return;
  42795. }
  42796. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  42797. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  42798. return;
  42799. }
  42800. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  42801. var loadingToken = {};
  42802. scene._addPendingData(loadingToken);
  42803. var manifestChecked = function (success) {
  42804. scene.database = database;
  42805. var registeredPlugin = directLoad ? SceneLoader._getDefaultPlugin() : SceneLoader._getPluginForFilename(sceneFilename);
  42806. var plugin = registeredPlugin.plugin;
  42807. var useArrayBuffer = registeredPlugin.isBinary;
  42808. var importMeshFromData = function (data) {
  42809. var meshes = [];
  42810. var particleSystems = [];
  42811. var skeletons = [];
  42812. if (scene.isDisposed) {
  42813. if (onerror) {
  42814. onerror(scene, 'Scene was disposed before being able to load ' + rootUrl + sceneFilename);
  42815. }
  42816. return;
  42817. }
  42818. try {
  42819. if (plugin.importMesh) {
  42820. var syncedPlugin = plugin;
  42821. if (!syncedPlugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  42822. if (onerror) {
  42823. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  42824. }
  42825. scene._removePendingData(loadingToken);
  42826. return;
  42827. }
  42828. if (onsuccess) {
  42829. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  42830. onsuccess(meshes, particleSystems, skeletons);
  42831. scene._removePendingData(loadingToken);
  42832. }
  42833. }
  42834. else {
  42835. var asyncedPlugin = plugin;
  42836. asyncedPlugin.importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  42837. if (onsuccess) {
  42838. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  42839. onsuccess(meshes, particleSystems, skeletons);
  42840. scene._removePendingData(loadingToken);
  42841. }
  42842. }, function () {
  42843. if (onerror) {
  42844. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  42845. }
  42846. scene._removePendingData(loadingToken);
  42847. });
  42848. }
  42849. }
  42850. catch (e) {
  42851. if (onerror) {
  42852. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename, e);
  42853. }
  42854. scene._removePendingData(loadingToken);
  42855. }
  42856. };
  42857. if (directLoad) {
  42858. importMeshFromData(directLoad);
  42859. return;
  42860. }
  42861. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  42862. importMeshFromData(data);
  42863. }, progressCallBack, database, useArrayBuffer, function () {
  42864. if (onerror) {
  42865. onerror(scene, 'Unable to load file ' + rootUrl + sceneFilename);
  42866. }
  42867. });
  42868. };
  42869. if (scene.getEngine().enableOfflineSupport && !directLoad) {
  42870. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  42871. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  42872. }
  42873. else {
  42874. // If the scene is a data stream or offline support is not enabled, it's a direct load
  42875. manifestChecked(true);
  42876. }
  42877. };
  42878. /**
  42879. * Load a scene
  42880. * @param rootUrl a string that defines the root url for scene and resources
  42881. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  42882. * @param engine is the instance of BABYLON.Engine to use to create the scene
  42883. */
  42884. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  42885. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  42886. };
  42887. /**
  42888. * Append a scene
  42889. * @param rootUrl a string that defines the root url for scene and resources
  42890. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  42891. * @param scene is the instance of BABYLON.Scene to append to
  42892. */
  42893. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  42894. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  42895. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  42896. return;
  42897. }
  42898. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  42899. var registeredPlugin = directLoad ? SceneLoader._getDefaultPlugin() : SceneLoader._getPluginForFilename(sceneFilename);
  42900. var plugin = registeredPlugin.plugin;
  42901. var useArrayBuffer = registeredPlugin.isBinary;
  42902. var database;
  42903. var loadingToken = {};
  42904. scene._addPendingData(loadingToken);
  42905. if (SceneLoader.ShowLoadingScreen) {
  42906. scene.getEngine().displayLoadingUI();
  42907. }
  42908. var loadSceneFromData = function (data) {
  42909. scene.database = database;
  42910. if (plugin.load) {
  42911. var syncedPlugin = plugin;
  42912. if (!syncedPlugin.load(scene, data, rootUrl)) {
  42913. if (onerror) {
  42914. onerror(scene);
  42915. }
  42916. scene._removePendingData(loadingToken);
  42917. scene.getEngine().hideLoadingUI();
  42918. return;
  42919. }
  42920. if (onsuccess) {
  42921. onsuccess(scene);
  42922. }
  42923. scene._removePendingData(loadingToken);
  42924. }
  42925. else {
  42926. var asyncedPlugin = plugin;
  42927. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  42928. if (onsuccess) {
  42929. onsuccess(scene);
  42930. }
  42931. scene._removePendingData(loadingToken);
  42932. }, function () {
  42933. if (onerror) {
  42934. onerror(scene);
  42935. }
  42936. scene._removePendingData(loadingToken);
  42937. scene.getEngine().hideLoadingUI();
  42938. });
  42939. }
  42940. if (SceneLoader.ShowLoadingScreen) {
  42941. scene.executeWhenReady(function () {
  42942. scene.getEngine().hideLoadingUI();
  42943. });
  42944. }
  42945. };
  42946. var manifestChecked = function (success) {
  42947. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database, useArrayBuffer);
  42948. };
  42949. if (directLoad) {
  42950. loadSceneFromData(directLoad);
  42951. return;
  42952. }
  42953. if (rootUrl.indexOf("file:") === -1) {
  42954. if (scene.getEngine().enableOfflineSupport) {
  42955. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  42956. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  42957. }
  42958. else {
  42959. manifestChecked(true);
  42960. }
  42961. }
  42962. else {
  42963. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack, useArrayBuffer);
  42964. }
  42965. };
  42966. return SceneLoader;
  42967. }());
  42968. // Flags
  42969. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  42970. SceneLoader._ShowLoadingScreen = true;
  42971. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  42972. // Members
  42973. SceneLoader._registeredPlugins = {};
  42974. BABYLON.SceneLoader = SceneLoader;
  42975. ;
  42976. })(BABYLON || (BABYLON = {}));
  42977. //# sourceMappingURL=babylon.sceneLoader.js.map
  42978. var BABYLON;
  42979. (function (BABYLON) {
  42980. var Internals;
  42981. (function (Internals) {
  42982. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  42983. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  42984. var parsedMaterial = parsedData.materials[index];
  42985. if (parsedMaterial.id === id) {
  42986. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  42987. }
  42988. }
  42989. return null;
  42990. };
  42991. var isDescendantOf = function (mesh, names, hierarchyIds) {
  42992. names = (names instanceof Array) ? names : [names];
  42993. for (var i in names) {
  42994. if (mesh.name === names[i]) {
  42995. hierarchyIds.push(mesh.id);
  42996. return true;
  42997. }
  42998. }
  42999. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  43000. hierarchyIds.push(mesh.id);
  43001. return true;
  43002. }
  43003. return false;
  43004. };
  43005. var logOperation = function (operation, producer) {
  43006. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  43007. };
  43008. BABYLON.SceneLoader.RegisterPlugin({
  43009. extensions: ".babylon",
  43010. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  43011. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  43012. // when SceneLoader.debugLogging = true (default), or exception encountered.
  43013. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  43014. // and avoid problems with multiple concurrent .babylon loads.
  43015. var log = "importMesh has failed JSON parse";
  43016. try {
  43017. var parsedData = JSON.parse(data);
  43018. log = "";
  43019. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  43020. var loadedSkeletonsIds = [];
  43021. var loadedMaterialsIds = [];
  43022. var hierarchyIds = [];
  43023. var index;
  43024. var cache;
  43025. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  43026. var parsedMesh = parsedData.meshes[index];
  43027. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  43028. if (meshesNames instanceof Array) {
  43029. // Remove found mesh name from list.
  43030. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  43031. }
  43032. //Geometry?
  43033. if (parsedMesh.geometryId) {
  43034. //does the file contain geometries?
  43035. if (parsedData.geometries) {
  43036. //find the correct geometry and add it to the scene
  43037. var found = false;
  43038. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  43039. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  43040. return;
  43041. }
  43042. else {
  43043. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  43044. if (parsedGeometryData.id === parsedMesh.geometryId) {
  43045. switch (geometryType) {
  43046. case "boxes":
  43047. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  43048. break;
  43049. case "spheres":
  43050. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  43051. break;
  43052. case "cylinders":
  43053. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  43054. break;
  43055. case "toruses":
  43056. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  43057. break;
  43058. case "grounds":
  43059. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  43060. break;
  43061. case "planes":
  43062. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  43063. break;
  43064. case "torusKnots":
  43065. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  43066. break;
  43067. case "vertexData":
  43068. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  43069. break;
  43070. }
  43071. found = true;
  43072. }
  43073. });
  43074. }
  43075. });
  43076. if (!found) {
  43077. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  43078. }
  43079. }
  43080. }
  43081. // Material ?
  43082. if (parsedMesh.materialId) {
  43083. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  43084. if (!materialFound && parsedData.multiMaterials) {
  43085. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  43086. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  43087. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  43088. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  43089. var subMatId = parsedMultiMaterial.materials[matIndex];
  43090. loadedMaterialsIds.push(subMatId);
  43091. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  43092. log += "\n\tMaterial " + mat.toString(fullDetails);
  43093. }
  43094. loadedMaterialsIds.push(parsedMultiMaterial.id);
  43095. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  43096. materialFound = true;
  43097. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  43098. break;
  43099. }
  43100. }
  43101. }
  43102. if (!materialFound) {
  43103. loadedMaterialsIds.push(parsedMesh.materialId);
  43104. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  43105. if (!mat) {
  43106. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  43107. }
  43108. else {
  43109. log += "\n\tMaterial " + mat.toString(fullDetails);
  43110. }
  43111. }
  43112. }
  43113. // Skeleton ?
  43114. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  43115. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  43116. if (!skeletonAlreadyLoaded) {
  43117. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  43118. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  43119. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  43120. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  43121. skeletons.push(skeleton);
  43122. loadedSkeletonsIds.push(parsedSkeleton.id);
  43123. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  43124. }
  43125. }
  43126. }
  43127. }
  43128. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  43129. meshes.push(mesh);
  43130. log += "\n\tMesh " + mesh.toString(fullDetails);
  43131. }
  43132. }
  43133. // Connecting parents
  43134. var currentMesh;
  43135. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  43136. currentMesh = scene.meshes[index];
  43137. if (currentMesh._waitingParentId) {
  43138. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  43139. currentMesh._waitingParentId = undefined;
  43140. }
  43141. }
  43142. // freeze and compute world matrix application
  43143. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  43144. currentMesh = scene.meshes[index];
  43145. if (currentMesh._waitingFreezeWorldMatrix) {
  43146. currentMesh.freezeWorldMatrix();
  43147. currentMesh._waitingFreezeWorldMatrix = undefined;
  43148. }
  43149. else {
  43150. currentMesh.computeWorldMatrix(true);
  43151. }
  43152. }
  43153. // Particles
  43154. if (parsedData.particleSystems) {
  43155. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  43156. var parsedParticleSystem = parsedData.particleSystems[index];
  43157. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  43158. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  43159. }
  43160. }
  43161. }
  43162. return true;
  43163. }
  43164. catch (err) {
  43165. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log);
  43166. log = null;
  43167. throw err;
  43168. }
  43169. finally {
  43170. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  43171. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  43172. }
  43173. }
  43174. },
  43175. load: function (scene, data, rootUrl) {
  43176. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  43177. // when SceneLoader.debugLogging = true (default), or exception encountered.
  43178. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  43179. // and avoid problems with multiple concurrent .babylon loads.
  43180. var log = "importScene has failed JSON parse";
  43181. try {
  43182. var parsedData = JSON.parse(data);
  43183. log = "";
  43184. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  43185. // Scene
  43186. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  43187. scene.autoClear = parsedData.autoClear;
  43188. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  43189. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  43190. if (parsedData.gravity) {
  43191. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  43192. }
  43193. // Fog
  43194. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  43195. scene.fogMode = parsedData.fogMode;
  43196. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  43197. scene.fogStart = parsedData.fogStart;
  43198. scene.fogEnd = parsedData.fogEnd;
  43199. scene.fogDensity = parsedData.fogDensity;
  43200. log += "\tFog mode for scene: ";
  43201. switch (scene.fogMode) {
  43202. // getters not compiling, so using hardcoded
  43203. case 1:
  43204. log += "exp\n";
  43205. break;
  43206. case 2:
  43207. log += "exp2\n";
  43208. break;
  43209. case 3:
  43210. log += "linear\n";
  43211. break;
  43212. }
  43213. }
  43214. //Physics
  43215. if (parsedData.physicsEnabled) {
  43216. var physicsPlugin;
  43217. if (parsedData.physicsEngine === "cannon") {
  43218. physicsPlugin = new BABYLON.CannonJSPlugin();
  43219. }
  43220. else if (parsedData.physicsEngine === "oimo") {
  43221. physicsPlugin = new BABYLON.OimoJSPlugin();
  43222. }
  43223. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  43224. //else - default engine, which is currently oimo
  43225. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  43226. scene.enablePhysics(physicsGravity, physicsPlugin);
  43227. }
  43228. // Metadata
  43229. if (parsedData.metadata !== undefined) {
  43230. scene.metadata = parsedData.metadata;
  43231. }
  43232. //collisions, if defined. otherwise, default is true
  43233. if (parsedData.collisionsEnabled != undefined) {
  43234. scene.collisionsEnabled = parsedData.collisionsEnabled;
  43235. }
  43236. scene.workerCollisions = !!parsedData.workerCollisions;
  43237. var index;
  43238. var cache;
  43239. // Lights
  43240. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  43241. var parsedLight = parsedData.lights[index];
  43242. var light = BABYLON.Light.Parse(parsedLight, scene);
  43243. log += (index === 0 ? "\n\tLights:" : "");
  43244. log += "\n\t\t" + light.toString(fullDetails);
  43245. }
  43246. // Animations
  43247. if (parsedData.animations) {
  43248. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  43249. var parsedAnimation = parsedData.animations[index];
  43250. var animation = BABYLON.Animation.Parse(parsedAnimation);
  43251. scene.animations.push(animation);
  43252. log += (index === 0 ? "\n\tAnimations:" : "");
  43253. log += "\n\t\t" + animation.toString(fullDetails);
  43254. }
  43255. }
  43256. if (parsedData.autoAnimate) {
  43257. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  43258. }
  43259. // Materials
  43260. if (parsedData.materials) {
  43261. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  43262. var parsedMaterial = parsedData.materials[index];
  43263. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  43264. log += (index === 0 ? "\n\tMaterials:" : "");
  43265. log += "\n\t\t" + mat.toString(fullDetails);
  43266. }
  43267. }
  43268. if (parsedData.multiMaterials) {
  43269. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  43270. var parsedMultiMaterial = parsedData.multiMaterials[index];
  43271. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  43272. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  43273. log += "\n\t\t" + mmat.toString(fullDetails);
  43274. }
  43275. }
  43276. // Morph targets
  43277. if (parsedData.morphTargetManagers) {
  43278. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  43279. var managerData = _a[_i];
  43280. var parsedManager = BABYLON.MorphTargetManager.Parse(managerData, scene);
  43281. }
  43282. }
  43283. // Skeletons
  43284. if (parsedData.skeletons) {
  43285. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  43286. var parsedSkeleton = parsedData.skeletons[index];
  43287. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  43288. log += (index === 0 ? "\n\tSkeletons:" : "");
  43289. log += "\n\t\t" + skeleton.toString(fullDetails);
  43290. }
  43291. }
  43292. // Geometries
  43293. var geometries = parsedData.geometries;
  43294. if (geometries) {
  43295. // Boxes
  43296. var boxes = geometries.boxes;
  43297. if (boxes) {
  43298. for (index = 0, cache = boxes.length; index < cache; index++) {
  43299. var parsedBox = boxes[index];
  43300. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  43301. }
  43302. }
  43303. // Spheres
  43304. var spheres = geometries.spheres;
  43305. if (spheres) {
  43306. for (index = 0, cache = spheres.length; index < cache; index++) {
  43307. var parsedSphere = spheres[index];
  43308. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  43309. }
  43310. }
  43311. // Cylinders
  43312. var cylinders = geometries.cylinders;
  43313. if (cylinders) {
  43314. for (index = 0, cache = cylinders.length; index < cache; index++) {
  43315. var parsedCylinder = cylinders[index];
  43316. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  43317. }
  43318. }
  43319. // Toruses
  43320. var toruses = geometries.toruses;
  43321. if (toruses) {
  43322. for (index = 0, cache = toruses.length; index < cache; index++) {
  43323. var parsedTorus = toruses[index];
  43324. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  43325. }
  43326. }
  43327. // Grounds
  43328. var grounds = geometries.grounds;
  43329. if (grounds) {
  43330. for (index = 0, cache = grounds.length; index < cache; index++) {
  43331. var parsedGround = grounds[index];
  43332. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  43333. }
  43334. }
  43335. // Planes
  43336. var planes = geometries.planes;
  43337. if (planes) {
  43338. for (index = 0, cache = planes.length; index < cache; index++) {
  43339. var parsedPlane = planes[index];
  43340. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  43341. }
  43342. }
  43343. // TorusKnots
  43344. var torusKnots = geometries.torusKnots;
  43345. if (torusKnots) {
  43346. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  43347. var parsedTorusKnot = torusKnots[index];
  43348. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  43349. }
  43350. }
  43351. // VertexData
  43352. var vertexData = geometries.vertexData;
  43353. if (vertexData) {
  43354. for (index = 0, cache = vertexData.length; index < cache; index++) {
  43355. var parsedVertexData = vertexData[index];
  43356. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  43357. }
  43358. }
  43359. }
  43360. // Meshes
  43361. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  43362. var parsedMesh = parsedData.meshes[index];
  43363. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  43364. log += (index === 0 ? "\n\tMeshes:" : "");
  43365. log += "\n\t\t" + mesh.toString(fullDetails);
  43366. }
  43367. // Cameras
  43368. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  43369. var parsedCamera = parsedData.cameras[index];
  43370. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  43371. log += (index === 0 ? "\n\tCameras:" : "");
  43372. log += "\n\t\t" + camera.toString(fullDetails);
  43373. }
  43374. if (parsedData.activeCameraID) {
  43375. scene.setActiveCameraByID(parsedData.activeCameraID);
  43376. }
  43377. // Browsing all the graph to connect the dots
  43378. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  43379. var camera = scene.cameras[index];
  43380. if (camera._waitingParentId) {
  43381. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  43382. camera._waitingParentId = undefined;
  43383. }
  43384. }
  43385. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  43386. var light = scene.lights[index];
  43387. if (light._waitingParentId) {
  43388. light.parent = scene.getLastEntryByID(light._waitingParentId);
  43389. light._waitingParentId = undefined;
  43390. }
  43391. }
  43392. // Sounds
  43393. var loadedSounds = [];
  43394. var loadedSound;
  43395. if (BABYLON.AudioEngine && parsedData.sounds) {
  43396. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  43397. var parsedSound = parsedData.sounds[index];
  43398. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  43399. if (!parsedSound.url)
  43400. parsedSound.url = parsedSound.name;
  43401. if (!loadedSounds[parsedSound.url]) {
  43402. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  43403. loadedSounds[parsedSound.url] = loadedSound;
  43404. }
  43405. else {
  43406. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  43407. }
  43408. }
  43409. else {
  43410. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  43411. }
  43412. }
  43413. }
  43414. loadedSounds = [];
  43415. // Connect parents & children and parse actions
  43416. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  43417. var mesh = scene.meshes[index];
  43418. if (mesh._waitingParentId) {
  43419. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  43420. mesh._waitingParentId = undefined;
  43421. }
  43422. if (mesh._waitingActions) {
  43423. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  43424. mesh._waitingActions = undefined;
  43425. }
  43426. }
  43427. // freeze world matrix application
  43428. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  43429. var currentMesh = scene.meshes[index];
  43430. if (currentMesh._waitingFreezeWorldMatrix) {
  43431. currentMesh.freezeWorldMatrix();
  43432. currentMesh._waitingFreezeWorldMatrix = undefined;
  43433. }
  43434. else {
  43435. currentMesh.computeWorldMatrix(true);
  43436. }
  43437. }
  43438. // Particles Systems
  43439. if (parsedData.particleSystems) {
  43440. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  43441. var parsedParticleSystem = parsedData.particleSystems[index];
  43442. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  43443. }
  43444. }
  43445. // Lens flares
  43446. if (parsedData.lensFlareSystems) {
  43447. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  43448. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  43449. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  43450. }
  43451. }
  43452. // Shadows
  43453. if (parsedData.shadowGenerators) {
  43454. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  43455. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  43456. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  43457. }
  43458. }
  43459. // Lights exclusions / inclusions
  43460. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  43461. var light = scene.lights[index];
  43462. // Excluded check
  43463. if (light._excludedMeshesIds.length > 0) {
  43464. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  43465. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  43466. if (excludedMesh) {
  43467. light.excludedMeshes.push(excludedMesh);
  43468. }
  43469. }
  43470. light._excludedMeshesIds = [];
  43471. }
  43472. // Included check
  43473. if (light._includedOnlyMeshesIds.length > 0) {
  43474. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  43475. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  43476. if (includedOnlyMesh) {
  43477. light.includedOnlyMeshes.push(includedOnlyMesh);
  43478. }
  43479. }
  43480. light._includedOnlyMeshesIds = [];
  43481. }
  43482. }
  43483. // Actions (scene)
  43484. if (parsedData.actions) {
  43485. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  43486. }
  43487. // Finish
  43488. return true;
  43489. }
  43490. catch (err) {
  43491. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log);
  43492. log = null;
  43493. throw err;
  43494. }
  43495. finally {
  43496. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  43497. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  43498. }
  43499. }
  43500. }
  43501. });
  43502. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  43503. })(BABYLON || (BABYLON = {}));
  43504. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  43505. var BABYLON;
  43506. (function (BABYLON) {
  43507. var FilesInput = (function () {
  43508. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  43509. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  43510. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  43511. this._engine = p_engine;
  43512. this._canvas = p_canvas;
  43513. this._currentScene = p_scene;
  43514. this._sceneLoadedCallback = p_sceneLoadedCallback;
  43515. this._progressCallback = p_progressCallback;
  43516. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  43517. this._textureLoadingCallback = p_textureLoadingCallback;
  43518. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  43519. }
  43520. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  43521. var _this = this;
  43522. if (p_elementToMonitor) {
  43523. this._elementToMonitor = p_elementToMonitor;
  43524. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  43525. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  43526. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  43527. }
  43528. };
  43529. FilesInput.prototype.renderFunction = function () {
  43530. if (this._additionnalRenderLoopLogicCallback) {
  43531. this._additionnalRenderLoopLogicCallback();
  43532. }
  43533. if (this._currentScene) {
  43534. if (this._textureLoadingCallback) {
  43535. var remaining = this._currentScene.getWaitingItemsCount();
  43536. if (remaining > 0) {
  43537. this._textureLoadingCallback(remaining);
  43538. }
  43539. }
  43540. this._currentScene.render();
  43541. }
  43542. };
  43543. FilesInput.prototype.drag = function (e) {
  43544. e.stopPropagation();
  43545. e.preventDefault();
  43546. };
  43547. FilesInput.prototype.drop = function (eventDrop) {
  43548. eventDrop.stopPropagation();
  43549. eventDrop.preventDefault();
  43550. this.loadFiles(eventDrop);
  43551. };
  43552. FilesInput.prototype.loadFiles = function (event) {
  43553. if (this._startingProcessingFilesCallback)
  43554. this._startingProcessingFilesCallback();
  43555. // Handling data transfer via drag'n'drop
  43556. if (event && event.dataTransfer && event.dataTransfer.files) {
  43557. this._filesToLoad = event.dataTransfer.files;
  43558. }
  43559. // Handling files from input files
  43560. if (event && event.target && event.target.files) {
  43561. this._filesToLoad = event.target.files;
  43562. }
  43563. if (this._filesToLoad && this._filesToLoad.length > 0) {
  43564. for (var i = 0; i < this._filesToLoad.length; i++) {
  43565. var name_1 = this._filesToLoad[i].name.toLowerCase();
  43566. var extension = name_1.split('.').pop();
  43567. var type = this._filesToLoad[i].type;
  43568. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  43569. && name_1.indexOf(".binary.babylon") === -1 && name_1.indexOf(".incremental.babylon") === -1) {
  43570. this._sceneFileToLoad = this._filesToLoad[i];
  43571. }
  43572. else {
  43573. FilesInput.FilesToLoad[name_1] = this._filesToLoad[i];
  43574. }
  43575. }
  43576. this.reload();
  43577. }
  43578. };
  43579. FilesInput.prototype.reload = function () {
  43580. var _this = this;
  43581. var that = this;
  43582. // If a ".babylon" file has been provided
  43583. if (this._sceneFileToLoad) {
  43584. if (this._currentScene) {
  43585. if (BABYLON.Tools.errorsCount > 0) {
  43586. BABYLON.Tools.ClearLogCache();
  43587. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  43588. }
  43589. this._engine.stopRenderLoop();
  43590. this._currentScene.dispose();
  43591. }
  43592. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  43593. that._currentScene = newScene;
  43594. // Wait for textures and shaders to be ready
  43595. that._currentScene.executeWhenReady(function () {
  43596. if (that._sceneLoadedCallback) {
  43597. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  43598. }
  43599. that._engine.runRenderLoop(function () { that.renderFunction(); });
  43600. });
  43601. }, function (progress) {
  43602. if (_this._progressCallback) {
  43603. _this._progressCallback(progress);
  43604. }
  43605. });
  43606. }
  43607. else {
  43608. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  43609. }
  43610. };
  43611. return FilesInput;
  43612. }());
  43613. FilesInput.FilesToLoad = new Array();
  43614. BABYLON.FilesInput = FilesInput;
  43615. })(BABYLON || (BABYLON = {}));
  43616. //# sourceMappingURL=babylon.filesInput.js.map
  43617. var BABYLON;
  43618. (function (BABYLON) {
  43619. /**
  43620. * This class implement a typical dictionary using a string as key and the generic type T as value.
  43621. * The underlying implementation relies on an associative array to ensure the best performances.
  43622. * The value can be anything including 'null' but except 'undefined'
  43623. */
  43624. var StringDictionary = (function () {
  43625. function StringDictionary() {
  43626. this._count = 0;
  43627. this._data = {};
  43628. }
  43629. /**
  43630. * This will clear this dictionary and copy the content from the 'source' one.
  43631. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  43632. * @param source the dictionary to take the content from and copy to this dictionary
  43633. */
  43634. StringDictionary.prototype.copyFrom = function (source) {
  43635. var _this = this;
  43636. this.clear();
  43637. source.forEach(function (t, v) { return _this.add(t, v); });
  43638. };
  43639. /**
  43640. * Get a value based from its key
  43641. * @param key the given key to get the matching value from
  43642. * @return the value if found, otherwise undefined is returned
  43643. */
  43644. StringDictionary.prototype.get = function (key) {
  43645. var val = this._data[key];
  43646. if (val !== undefined) {
  43647. return val;
  43648. }
  43649. return undefined;
  43650. };
  43651. /**
  43652. * Get a value from its key or add it if it doesn't exist.
  43653. * This method will ensure you that a given key/data will be present in the dictionary.
  43654. * @param key the given key to get the matching value from
  43655. * @param factory the factory that will create the value if the key is not present in the dictionary.
  43656. * The factory will only be invoked if there's no data for the given key.
  43657. * @return the value corresponding to the key.
  43658. */
  43659. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  43660. var val = this.get(key);
  43661. if (val !== undefined) {
  43662. return val;
  43663. }
  43664. val = factory(key);
  43665. if (val) {
  43666. this.add(key, val);
  43667. }
  43668. return val;
  43669. };
  43670. /**
  43671. * Get a value from its key if present in the dictionary otherwise add it
  43672. * @param key the key to get the value from
  43673. * @param val if there's no such key/value pair in the dictionary add it with this value
  43674. * @return the value corresponding to the key
  43675. */
  43676. StringDictionary.prototype.getOrAdd = function (key, val) {
  43677. var curVal = this.get(key);
  43678. if (curVal !== undefined) {
  43679. return curVal;
  43680. }
  43681. this.add(key, val);
  43682. return val;
  43683. };
  43684. /**
  43685. * Check if there's a given key in the dictionary
  43686. * @param key the key to check for
  43687. * @return true if the key is present, false otherwise
  43688. */
  43689. StringDictionary.prototype.contains = function (key) {
  43690. return this._data[key] !== undefined;
  43691. };
  43692. /**
  43693. * Add a new key and its corresponding value
  43694. * @param key the key to add
  43695. * @param value the value corresponding to the key
  43696. * @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
  43697. */
  43698. StringDictionary.prototype.add = function (key, value) {
  43699. if (this._data[key] !== undefined) {
  43700. return false;
  43701. }
  43702. this._data[key] = value;
  43703. ++this._count;
  43704. return true;
  43705. };
  43706. StringDictionary.prototype.set = function (key, value) {
  43707. if (this._data[key] === undefined) {
  43708. return false;
  43709. }
  43710. this._data[key] = value;
  43711. return true;
  43712. };
  43713. /**
  43714. * Get the element of the given key and remove it from the dictionary
  43715. * @param key
  43716. */
  43717. StringDictionary.prototype.getAndRemove = function (key) {
  43718. var val = this.get(key);
  43719. if (val !== undefined) {
  43720. delete this._data[key];
  43721. --this._count;
  43722. return val;
  43723. }
  43724. return null;
  43725. };
  43726. /**
  43727. * Remove a key/value from the dictionary.
  43728. * @param key the key to remove
  43729. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  43730. */
  43731. StringDictionary.prototype.remove = function (key) {
  43732. if (this.contains(key)) {
  43733. delete this._data[key];
  43734. --this._count;
  43735. return true;
  43736. }
  43737. return false;
  43738. };
  43739. /**
  43740. * Clear the whole content of the dictionary
  43741. */
  43742. StringDictionary.prototype.clear = function () {
  43743. this._data = {};
  43744. this._count = 0;
  43745. };
  43746. Object.defineProperty(StringDictionary.prototype, "count", {
  43747. get: function () {
  43748. return this._count;
  43749. },
  43750. enumerable: true,
  43751. configurable: true
  43752. });
  43753. /**
  43754. * Execute a callback on each key/val of the dictionary.
  43755. * Note that you can remove any element in this dictionary in the callback implementation
  43756. * @param callback the callback to execute on a given key/value pair
  43757. */
  43758. StringDictionary.prototype.forEach = function (callback) {
  43759. for (var cur in this._data) {
  43760. var val = this._data[cur];
  43761. callback(cur, val);
  43762. }
  43763. };
  43764. /**
  43765. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  43766. * If the callback returns null or undefined the method will iterate to the next key/value pair
  43767. * Note that you can remove any element in this dictionary in the callback implementation
  43768. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  43769. */
  43770. StringDictionary.prototype.first = function (callback) {
  43771. for (var cur in this._data) {
  43772. var val = this._data[cur];
  43773. var res = callback(cur, val);
  43774. if (res) {
  43775. return res;
  43776. }
  43777. }
  43778. return null;
  43779. };
  43780. return StringDictionary;
  43781. }());
  43782. BABYLON.StringDictionary = StringDictionary;
  43783. })(BABYLON || (BABYLON = {}));
  43784. //# sourceMappingURL=babylon.stringDictionary.js.map
  43785. var BABYLON;
  43786. (function (BABYLON) {
  43787. var Tags = (function () {
  43788. function Tags() {
  43789. }
  43790. Tags.EnableFor = function (obj) {
  43791. obj._tags = obj._tags || {};
  43792. obj.hasTags = function () {
  43793. return Tags.HasTags(obj);
  43794. };
  43795. obj.addTags = function (tagsString) {
  43796. return Tags.AddTagsTo(obj, tagsString);
  43797. };
  43798. obj.removeTags = function (tagsString) {
  43799. return Tags.RemoveTagsFrom(obj, tagsString);
  43800. };
  43801. obj.matchesTagsQuery = function (tagsQuery) {
  43802. return Tags.MatchesQuery(obj, tagsQuery);
  43803. };
  43804. };
  43805. Tags.DisableFor = function (obj) {
  43806. delete obj._tags;
  43807. delete obj.hasTags;
  43808. delete obj.addTags;
  43809. delete obj.removeTags;
  43810. delete obj.matchesTagsQuery;
  43811. };
  43812. Tags.HasTags = function (obj) {
  43813. if (!obj._tags) {
  43814. return false;
  43815. }
  43816. return !BABYLON.Tools.IsEmpty(obj._tags);
  43817. };
  43818. Tags.GetTags = function (obj, asString) {
  43819. if (asString === void 0) { asString = true; }
  43820. if (!obj._tags) {
  43821. return null;
  43822. }
  43823. if (asString) {
  43824. var tagsArray = [];
  43825. for (var tag in obj._tags) {
  43826. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  43827. tagsArray.push(tag);
  43828. }
  43829. }
  43830. return tagsArray.join(" ");
  43831. }
  43832. else {
  43833. return obj._tags;
  43834. }
  43835. };
  43836. // the tags 'true' and 'false' are reserved and cannot be used as tags
  43837. // a tag cannot start with '||', '&&', and '!'
  43838. // it cannot contain whitespaces
  43839. Tags.AddTagsTo = function (obj, tagsString) {
  43840. if (!tagsString) {
  43841. return;
  43842. }
  43843. if (typeof tagsString !== "string") {
  43844. return;
  43845. }
  43846. var tags = tagsString.split(" ");
  43847. tags.forEach(function (tag, index, array) {
  43848. Tags._AddTagTo(obj, tag);
  43849. });
  43850. };
  43851. Tags._AddTagTo = function (obj, tag) {
  43852. tag = tag.trim();
  43853. if (tag === "" || tag === "true" || tag === "false") {
  43854. return;
  43855. }
  43856. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  43857. return;
  43858. }
  43859. Tags.EnableFor(obj);
  43860. obj._tags[tag] = true;
  43861. };
  43862. Tags.RemoveTagsFrom = function (obj, tagsString) {
  43863. if (!Tags.HasTags(obj)) {
  43864. return;
  43865. }
  43866. var tags = tagsString.split(" ");
  43867. for (var t in tags) {
  43868. Tags._RemoveTagFrom(obj, tags[t]);
  43869. }
  43870. };
  43871. Tags._RemoveTagFrom = function (obj, tag) {
  43872. delete obj._tags[tag];
  43873. };
  43874. Tags.MatchesQuery = function (obj, tagsQuery) {
  43875. if (tagsQuery === undefined) {
  43876. return true;
  43877. }
  43878. if (tagsQuery === "") {
  43879. return Tags.HasTags(obj);
  43880. }
  43881. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  43882. };
  43883. return Tags;
  43884. }());
  43885. BABYLON.Tags = Tags;
  43886. })(BABYLON || (BABYLON = {}));
  43887. //# sourceMappingURL=babylon.tags.js.map
  43888. var BABYLON;
  43889. (function (BABYLON) {
  43890. var Internals;
  43891. (function (Internals) {
  43892. var AndOrNotEvaluator = (function () {
  43893. function AndOrNotEvaluator() {
  43894. }
  43895. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  43896. if (!query.match(/\([^\(\)]*\)/g)) {
  43897. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  43898. }
  43899. else {
  43900. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  43901. // remove parenthesis
  43902. r = r.slice(1, r.length - 1);
  43903. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  43904. });
  43905. }
  43906. if (query === "true") {
  43907. return true;
  43908. }
  43909. if (query === "false") {
  43910. return false;
  43911. }
  43912. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  43913. };
  43914. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  43915. evaluateCallback = evaluateCallback || (function (r) {
  43916. return r === "true" ? true : false;
  43917. });
  43918. var result;
  43919. var or = parenthesisContent.split("||");
  43920. for (var i in or) {
  43921. if (or.hasOwnProperty(i)) {
  43922. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  43923. var and = ori.split("&&");
  43924. if (and.length > 1) {
  43925. for (var j = 0; j < and.length; ++j) {
  43926. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  43927. if (andj !== "true" && andj !== "false") {
  43928. if (andj[0] === "!") {
  43929. result = !evaluateCallback(andj.substring(1));
  43930. }
  43931. else {
  43932. result = evaluateCallback(andj);
  43933. }
  43934. }
  43935. else {
  43936. result = andj === "true" ? true : false;
  43937. }
  43938. if (!result) {
  43939. ori = "false";
  43940. break;
  43941. }
  43942. }
  43943. }
  43944. if (result || ori === "true") {
  43945. result = true;
  43946. break;
  43947. }
  43948. // result equals false (or undefined)
  43949. if (ori !== "true" && ori !== "false") {
  43950. if (ori[0] === "!") {
  43951. result = !evaluateCallback(ori.substring(1));
  43952. }
  43953. else {
  43954. result = evaluateCallback(ori);
  43955. }
  43956. }
  43957. else {
  43958. result = ori === "true" ? true : false;
  43959. }
  43960. }
  43961. }
  43962. // the whole parenthesis scope is replaced by 'true' or 'false'
  43963. return result ? "true" : "false";
  43964. };
  43965. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  43966. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  43967. // remove whitespaces
  43968. r = r.replace(/[\s]/g, function () { return ""; });
  43969. return r.length % 2 ? "!" : "";
  43970. });
  43971. booleanString = booleanString.trim();
  43972. if (booleanString === "!true") {
  43973. booleanString = "false";
  43974. }
  43975. else if (booleanString === "!false") {
  43976. booleanString = "true";
  43977. }
  43978. return booleanString;
  43979. };
  43980. return AndOrNotEvaluator;
  43981. }());
  43982. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  43983. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  43984. })(BABYLON || (BABYLON = {}));
  43985. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  43986. var BABYLON;
  43987. (function (BABYLON) {
  43988. var Database = (function () {
  43989. function Database(urlToScene, callbackManifestChecked) {
  43990. // Handling various flavors of prefixed version of IndexedDB
  43991. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  43992. this.callbackManifestChecked = callbackManifestChecked;
  43993. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  43994. this.db = null;
  43995. this.enableSceneOffline = false;
  43996. this.enableTexturesOffline = false;
  43997. this.manifestVersionFound = 0;
  43998. this.mustUpdateRessources = false;
  43999. this.hasReachedQuota = false;
  44000. if (!Database.IDBStorageEnabled) {
  44001. this.callbackManifestChecked(true);
  44002. }
  44003. else {
  44004. this.checkManifestFile();
  44005. }
  44006. }
  44007. Database.prototype.checkManifestFile = function () {
  44008. var _this = this;
  44009. function noManifestFile() {
  44010. that.enableSceneOffline = false;
  44011. that.enableTexturesOffline = false;
  44012. that.callbackManifestChecked(false);
  44013. }
  44014. var that = this;
  44015. var timeStampUsed = false;
  44016. var manifestURL = this.currentSceneUrl + ".manifest";
  44017. var xhr = new XMLHttpRequest();
  44018. if (navigator.onLine) {
  44019. // Adding a timestamp to by-pass browsers' cache
  44020. timeStampUsed = true;
  44021. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  44022. }
  44023. xhr.open("GET", manifestURL, true);
  44024. xhr.addEventListener("load", function () {
  44025. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  44026. try {
  44027. var manifestFile = JSON.parse(xhr.response);
  44028. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  44029. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  44030. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  44031. _this.manifestVersionFound = manifestFile.version;
  44032. }
  44033. if (_this.callbackManifestChecked) {
  44034. _this.callbackManifestChecked(true);
  44035. }
  44036. }
  44037. catch (ex) {
  44038. noManifestFile();
  44039. }
  44040. }
  44041. else {
  44042. noManifestFile();
  44043. }
  44044. }, false);
  44045. xhr.addEventListener("error", function (event) {
  44046. if (timeStampUsed) {
  44047. timeStampUsed = false;
  44048. // Let's retry without the timeStamp
  44049. // It could fail when coupled with HTML5 Offline API
  44050. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  44051. xhr.open("GET", retryManifestURL, true);
  44052. xhr.send();
  44053. }
  44054. else {
  44055. noManifestFile();
  44056. }
  44057. }, false);
  44058. try {
  44059. xhr.send();
  44060. }
  44061. catch (ex) {
  44062. BABYLON.Tools.Error("Error on XHR send request.");
  44063. that.callbackManifestChecked(false);
  44064. }
  44065. };
  44066. Database.prototype.openAsync = function (successCallback, errorCallback) {
  44067. var _this = this;
  44068. function handleError() {
  44069. that.isSupported = false;
  44070. if (errorCallback)
  44071. errorCallback();
  44072. }
  44073. var that = this;
  44074. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  44075. // Your browser doesn't support IndexedDB
  44076. this.isSupported = false;
  44077. if (errorCallback)
  44078. errorCallback();
  44079. }
  44080. else {
  44081. // If the DB hasn't been opened or created yet
  44082. if (!this.db) {
  44083. this.hasReachedQuota = false;
  44084. this.isSupported = true;
  44085. var request = this.idbFactory.open("babylonjs", 1);
  44086. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  44087. request.onerror = function (event) {
  44088. handleError();
  44089. };
  44090. // executes when a version change transaction cannot complete due to other active transactions
  44091. request.onblocked = function (event) {
  44092. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  44093. handleError();
  44094. };
  44095. // DB has been opened successfully
  44096. request.onsuccess = function (event) {
  44097. _this.db = request.result;
  44098. successCallback();
  44099. };
  44100. // Initialization of the DB. Creating Scenes & Textures stores
  44101. request.onupgradeneeded = function (event) {
  44102. _this.db = (event.target).result;
  44103. try {
  44104. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  44105. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  44106. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  44107. }
  44108. catch (ex) {
  44109. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  44110. handleError();
  44111. }
  44112. };
  44113. }
  44114. else {
  44115. if (successCallback)
  44116. successCallback();
  44117. }
  44118. }
  44119. };
  44120. Database.prototype.loadImageFromDB = function (url, image) {
  44121. var _this = this;
  44122. var completeURL = Database.ReturnFullUrlLocation(url);
  44123. var saveAndLoadImage = function () {
  44124. if (!_this.hasReachedQuota && _this.db !== null) {
  44125. // the texture is not yet in the DB, let's try to save it
  44126. _this._saveImageIntoDBAsync(completeURL, image);
  44127. }
  44128. else {
  44129. image.src = url;
  44130. }
  44131. };
  44132. if (!this.mustUpdateRessources) {
  44133. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  44134. }
  44135. else {
  44136. saveAndLoadImage();
  44137. }
  44138. };
  44139. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  44140. if (this.isSupported && this.db !== null) {
  44141. var texture;
  44142. var transaction = this.db.transaction(["textures"]);
  44143. transaction.onabort = function (event) {
  44144. image.src = url;
  44145. };
  44146. transaction.oncomplete = function (event) {
  44147. var blobTextureURL;
  44148. if (texture) {
  44149. var URL = window.URL || window.webkitURL;
  44150. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  44151. image.onerror = function () {
  44152. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  44153. image.src = url;
  44154. };
  44155. image.src = blobTextureURL;
  44156. }
  44157. else {
  44158. notInDBCallback();
  44159. }
  44160. };
  44161. var getRequest = transaction.objectStore("textures").get(url);
  44162. getRequest.onsuccess = function (event) {
  44163. texture = (event.target).result;
  44164. };
  44165. getRequest.onerror = function (event) {
  44166. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  44167. image.src = url;
  44168. };
  44169. }
  44170. else {
  44171. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  44172. image.src = url;
  44173. }
  44174. };
  44175. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  44176. var _this = this;
  44177. if (this.isSupported) {
  44178. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  44179. var generateBlobUrl = function () {
  44180. var blobTextureURL;
  44181. if (blob) {
  44182. var URL = window.URL || window.webkitURL;
  44183. try {
  44184. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  44185. }
  44186. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  44187. catch (ex) {
  44188. blobTextureURL = URL.createObjectURL(blob);
  44189. }
  44190. }
  44191. image.src = blobTextureURL;
  44192. };
  44193. if (Database.IsUASupportingBlobStorage) {
  44194. var xhr = new XMLHttpRequest(), blob;
  44195. xhr.open("GET", url, true);
  44196. xhr.responseType = "blob";
  44197. xhr.addEventListener("load", function () {
  44198. if (xhr.status === 200) {
  44199. // Blob as response (XHR2)
  44200. blob = xhr.response;
  44201. var transaction = _this.db.transaction(["textures"], "readwrite");
  44202. // the transaction could abort because of a QuotaExceededError error
  44203. transaction.onabort = function (event) {
  44204. try {
  44205. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  44206. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  44207. _this.hasReachedQuota = true;
  44208. }
  44209. }
  44210. catch (ex) { }
  44211. generateBlobUrl();
  44212. };
  44213. transaction.oncomplete = function (event) {
  44214. generateBlobUrl();
  44215. };
  44216. var newTexture = { textureUrl: url, data: blob };
  44217. try {
  44218. // Put the blob into the dabase
  44219. var addRequest = transaction.objectStore("textures").put(newTexture);
  44220. addRequest.onsuccess = function (event) {
  44221. };
  44222. addRequest.onerror = function (event) {
  44223. generateBlobUrl();
  44224. };
  44225. }
  44226. catch (ex) {
  44227. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  44228. if (ex.code === 25) {
  44229. Database.IsUASupportingBlobStorage = false;
  44230. }
  44231. image.src = url;
  44232. }
  44233. }
  44234. else {
  44235. image.src = url;
  44236. }
  44237. }, false);
  44238. xhr.addEventListener("error", function (event) {
  44239. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  44240. image.src = url;
  44241. }, false);
  44242. xhr.send();
  44243. }
  44244. else {
  44245. image.src = url;
  44246. }
  44247. }
  44248. else {
  44249. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  44250. image.src = url;
  44251. }
  44252. };
  44253. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  44254. var _this = this;
  44255. var updateVersion = function (event) {
  44256. // the version is not yet in the DB or we need to update it
  44257. _this._saveVersionIntoDBAsync(url, versionLoaded);
  44258. };
  44259. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  44260. };
  44261. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  44262. var _this = this;
  44263. if (this.isSupported) {
  44264. var version;
  44265. try {
  44266. var transaction = this.db.transaction(["versions"]);
  44267. transaction.oncomplete = function (event) {
  44268. if (version) {
  44269. // If the version in the JSON file is > than the version in DB
  44270. if (_this.manifestVersionFound > version.data) {
  44271. _this.mustUpdateRessources = true;
  44272. updateInDBCallback();
  44273. }
  44274. else {
  44275. callback(version.data);
  44276. }
  44277. }
  44278. else {
  44279. _this.mustUpdateRessources = true;
  44280. updateInDBCallback();
  44281. }
  44282. };
  44283. transaction.onabort = function (event) {
  44284. callback(-1);
  44285. };
  44286. var getRequest = transaction.objectStore("versions").get(url);
  44287. getRequest.onsuccess = function (event) {
  44288. version = (event.target).result;
  44289. };
  44290. getRequest.onerror = function (event) {
  44291. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  44292. callback(-1);
  44293. };
  44294. }
  44295. catch (ex) {
  44296. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  44297. callback(-1);
  44298. }
  44299. }
  44300. else {
  44301. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  44302. callback(-1);
  44303. }
  44304. };
  44305. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  44306. var _this = this;
  44307. if (this.isSupported && !this.hasReachedQuota) {
  44308. try {
  44309. // Open a transaction to the database
  44310. var transaction = this.db.transaction(["versions"], "readwrite");
  44311. // the transaction could abort because of a QuotaExceededError error
  44312. transaction.onabort = function (event) {
  44313. try {
  44314. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  44315. _this.hasReachedQuota = true;
  44316. }
  44317. }
  44318. catch (ex) { }
  44319. callback(-1);
  44320. };
  44321. transaction.oncomplete = function (event) {
  44322. callback(_this.manifestVersionFound);
  44323. };
  44324. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  44325. // Put the scene into the database
  44326. var addRequest = transaction.objectStore("versions").put(newVersion);
  44327. addRequest.onsuccess = function (event) {
  44328. };
  44329. addRequest.onerror = function (event) {
  44330. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  44331. };
  44332. }
  44333. catch (ex) {
  44334. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  44335. callback(-1);
  44336. }
  44337. }
  44338. else {
  44339. callback(-1);
  44340. }
  44341. };
  44342. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  44343. var _this = this;
  44344. var completeUrl = Database.ReturnFullUrlLocation(url);
  44345. var saveAndLoadFile = function (event) {
  44346. // the scene is not yet in the DB, let's try to save it
  44347. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  44348. };
  44349. this._checkVersionFromDB(completeUrl, function (version) {
  44350. if (version !== -1) {
  44351. if (!_this.mustUpdateRessources) {
  44352. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  44353. }
  44354. else {
  44355. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  44356. }
  44357. }
  44358. else {
  44359. errorCallback();
  44360. }
  44361. });
  44362. };
  44363. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  44364. if (this.isSupported) {
  44365. var targetStore;
  44366. if (url.indexOf(".babylon") !== -1) {
  44367. targetStore = "scenes";
  44368. }
  44369. else {
  44370. targetStore = "textures";
  44371. }
  44372. var file;
  44373. var transaction = this.db.transaction([targetStore]);
  44374. transaction.oncomplete = function (event) {
  44375. if (file) {
  44376. callback(file.data);
  44377. }
  44378. else {
  44379. notInDBCallback();
  44380. }
  44381. };
  44382. transaction.onabort = function (event) {
  44383. notInDBCallback();
  44384. };
  44385. var getRequest = transaction.objectStore(targetStore).get(url);
  44386. getRequest.onsuccess = function (event) {
  44387. file = (event.target).result;
  44388. };
  44389. getRequest.onerror = function (event) {
  44390. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  44391. notInDBCallback();
  44392. };
  44393. }
  44394. else {
  44395. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  44396. callback();
  44397. }
  44398. };
  44399. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  44400. var _this = this;
  44401. if (this.isSupported) {
  44402. var targetStore;
  44403. if (url.indexOf(".babylon") !== -1) {
  44404. targetStore = "scenes";
  44405. }
  44406. else {
  44407. targetStore = "textures";
  44408. }
  44409. // Create XHR
  44410. var xhr = new XMLHttpRequest(), fileData;
  44411. xhr.open("GET", url, true);
  44412. if (useArrayBuffer) {
  44413. xhr.responseType = "arraybuffer";
  44414. }
  44415. xhr.onprogress = progressCallback;
  44416. xhr.addEventListener("load", function () {
  44417. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  44418. // Blob as response (XHR2)
  44419. //fileData = xhr.responseText;
  44420. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  44421. if (!_this.hasReachedQuota) {
  44422. // Open a transaction to the database
  44423. var transaction = _this.db.transaction([targetStore], "readwrite");
  44424. // the transaction could abort because of a QuotaExceededError error
  44425. transaction.onabort = function (event) {
  44426. try {
  44427. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  44428. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  44429. _this.hasReachedQuota = true;
  44430. }
  44431. }
  44432. catch (ex) { }
  44433. callback(fileData);
  44434. };
  44435. transaction.oncomplete = function (event) {
  44436. callback(fileData);
  44437. };
  44438. var newFile;
  44439. if (targetStore === "scenes") {
  44440. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  44441. }
  44442. else {
  44443. newFile = { textureUrl: url, data: fileData };
  44444. }
  44445. try {
  44446. // Put the scene into the database
  44447. var addRequest = transaction.objectStore(targetStore).put(newFile);
  44448. addRequest.onsuccess = function (event) {
  44449. };
  44450. addRequest.onerror = function (event) {
  44451. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  44452. };
  44453. }
  44454. catch (ex) {
  44455. callback(fileData);
  44456. }
  44457. }
  44458. else {
  44459. callback(fileData);
  44460. }
  44461. }
  44462. else {
  44463. callback();
  44464. }
  44465. }, false);
  44466. xhr.addEventListener("error", function (event) {
  44467. BABYLON.Tools.Error("error on XHR request.");
  44468. callback();
  44469. }, false);
  44470. xhr.send();
  44471. }
  44472. else {
  44473. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  44474. callback();
  44475. }
  44476. };
  44477. return Database;
  44478. }());
  44479. Database.IsUASupportingBlobStorage = true;
  44480. Database.IDBStorageEnabled = true;
  44481. Database.parseURL = function (url) {
  44482. var a = document.createElement('a');
  44483. a.href = url;
  44484. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  44485. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  44486. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  44487. return absLocation;
  44488. };
  44489. Database.ReturnFullUrlLocation = function (url) {
  44490. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  44491. return (Database.parseURL(window.location.href) + url);
  44492. }
  44493. else {
  44494. return url;
  44495. }
  44496. };
  44497. BABYLON.Database = Database;
  44498. })(BABYLON || (BABYLON = {}));
  44499. //# sourceMappingURL=babylon.database.js.map
  44500. var BABYLON;
  44501. (function (BABYLON) {
  44502. var FresnelParameters = (function () {
  44503. function FresnelParameters() {
  44504. this._isEnabled = true;
  44505. this.leftColor = BABYLON.Color3.White();
  44506. this.rightColor = BABYLON.Color3.Black();
  44507. this.bias = 0;
  44508. this.power = 1;
  44509. }
  44510. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  44511. get: function () {
  44512. return this._isEnabled;
  44513. },
  44514. set: function (value) {
  44515. if (this._isEnabled === value) {
  44516. return;
  44517. }
  44518. this._isEnabled = value;
  44519. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  44520. },
  44521. enumerable: true,
  44522. configurable: true
  44523. });
  44524. FresnelParameters.prototype.clone = function () {
  44525. var newFresnelParameters = new FresnelParameters();
  44526. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  44527. return newFresnelParameters;
  44528. };
  44529. FresnelParameters.prototype.serialize = function () {
  44530. var serializationObject = {};
  44531. serializationObject.isEnabled = this.isEnabled;
  44532. serializationObject.leftColor = this.leftColor;
  44533. serializationObject.rightColor = this.rightColor;
  44534. serializationObject.bias = this.bias;
  44535. serializationObject.power = this.power;
  44536. return serializationObject;
  44537. };
  44538. FresnelParameters.Parse = function (parsedFresnelParameters) {
  44539. var fresnelParameters = new FresnelParameters();
  44540. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  44541. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  44542. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  44543. fresnelParameters.bias = parsedFresnelParameters.bias;
  44544. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  44545. return fresnelParameters;
  44546. };
  44547. return FresnelParameters;
  44548. }());
  44549. BABYLON.FresnelParameters = FresnelParameters;
  44550. })(BABYLON || (BABYLON = {}));
  44551. //# sourceMappingURL=babylon.fresnelParameters.js.map
  44552. var BABYLON;
  44553. (function (BABYLON) {
  44554. var MultiMaterial = (function (_super) {
  44555. __extends(MultiMaterial, _super);
  44556. function MultiMaterial(name, scene) {
  44557. var _this = _super.call(this, name, scene, true) || this;
  44558. _this.subMaterials = new Array();
  44559. scene.multiMaterials.push(_this);
  44560. return _this;
  44561. }
  44562. // Properties
  44563. MultiMaterial.prototype.getSubMaterial = function (index) {
  44564. if (index < 0 || index >= this.subMaterials.length) {
  44565. return this.getScene().defaultMaterial;
  44566. }
  44567. return this.subMaterials[index];
  44568. };
  44569. // Methods
  44570. MultiMaterial.prototype.getClassName = function () {
  44571. return "MultiMaterial";
  44572. };
  44573. MultiMaterial.prototype.isReady = function (mesh) {
  44574. for (var index = 0; index < this.subMaterials.length; index++) {
  44575. var subMaterial = this.subMaterials[index];
  44576. if (subMaterial) {
  44577. if (!this.subMaterials[index].isReady(mesh)) {
  44578. return false;
  44579. }
  44580. }
  44581. }
  44582. return true;
  44583. };
  44584. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  44585. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  44586. for (var index = 0; index < this.subMaterials.length; index++) {
  44587. var subMaterial = null;
  44588. if (cloneChildren) {
  44589. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  44590. }
  44591. else {
  44592. subMaterial = this.subMaterials[index];
  44593. }
  44594. newMultiMaterial.subMaterials.push(subMaterial);
  44595. }
  44596. return newMultiMaterial;
  44597. };
  44598. MultiMaterial.prototype.serialize = function () {
  44599. var serializationObject = {};
  44600. serializationObject.name = this.name;
  44601. serializationObject.id = this.id;
  44602. serializationObject.tags = BABYLON.Tags.GetTags(this);
  44603. serializationObject.materials = [];
  44604. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  44605. var subMat = this.subMaterials[matIndex];
  44606. if (subMat) {
  44607. serializationObject.materials.push(subMat.id);
  44608. }
  44609. else {
  44610. serializationObject.materials.push(null);
  44611. }
  44612. }
  44613. return serializationObject;
  44614. };
  44615. return MultiMaterial;
  44616. }(BABYLON.Material));
  44617. BABYLON.MultiMaterial = MultiMaterial;
  44618. })(BABYLON || (BABYLON = {}));
  44619. //# sourceMappingURL=babylon.multiMaterial.js.map
  44620. var BABYLON;
  44621. (function (BABYLON) {
  44622. var FreeCameraTouchInput = (function () {
  44623. function FreeCameraTouchInput() {
  44624. this._offsetX = null;
  44625. this._offsetY = null;
  44626. this._pointerCount = 0;
  44627. this._pointerPressed = [];
  44628. this.touchAngularSensibility = 200000.0;
  44629. this.touchMoveSensibility = 250.0;
  44630. }
  44631. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  44632. var _this = this;
  44633. var previousPosition;
  44634. if (this._pointerInput === undefined) {
  44635. this._onLostFocus = function (evt) {
  44636. _this._offsetX = null;
  44637. _this._offsetY = null;
  44638. };
  44639. this._pointerInput = function (p, s) {
  44640. var evt = p.event;
  44641. if (evt.pointerType === "mouse") {
  44642. return;
  44643. }
  44644. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  44645. if (!noPreventDefault) {
  44646. evt.preventDefault();
  44647. }
  44648. _this._pointerPressed.push(evt.pointerId);
  44649. if (_this._pointerPressed.length !== 1) {
  44650. return;
  44651. }
  44652. previousPosition = {
  44653. x: evt.clientX,
  44654. y: evt.clientY
  44655. };
  44656. }
  44657. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  44658. if (!noPreventDefault) {
  44659. evt.preventDefault();
  44660. }
  44661. var index = _this._pointerPressed.indexOf(evt.pointerId);
  44662. if (index === -1) {
  44663. return;
  44664. }
  44665. _this._pointerPressed.splice(index, 1);
  44666. if (index != 0) {
  44667. return;
  44668. }
  44669. previousPosition = null;
  44670. _this._offsetX = null;
  44671. _this._offsetY = null;
  44672. }
  44673. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  44674. if (!noPreventDefault) {
  44675. evt.preventDefault();
  44676. }
  44677. if (!previousPosition) {
  44678. return;
  44679. }
  44680. var index = _this._pointerPressed.indexOf(evt.pointerId);
  44681. if (index != 0) {
  44682. return;
  44683. }
  44684. _this._offsetX = evt.clientX - previousPosition.x;
  44685. _this._offsetY = -(evt.clientY - previousPosition.y);
  44686. }
  44687. };
  44688. }
  44689. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  44690. element.addEventListener("blur", this._onLostFocus);
  44691. };
  44692. FreeCameraTouchInput.prototype.detachControl = function (element) {
  44693. if (this._pointerInput && element) {
  44694. this.camera.getScene().onPointerObservable.remove(this._observer);
  44695. this._observer = null;
  44696. element.removeEventListener("blur", this._onLostFocus);
  44697. this._onLostFocus = null;
  44698. this._pointerPressed = [];
  44699. this._offsetX = null;
  44700. this._offsetY = null;
  44701. this._pointerCount = 0;
  44702. }
  44703. };
  44704. FreeCameraTouchInput.prototype.checkInputs = function () {
  44705. if (this._offsetX) {
  44706. var camera = this.camera;
  44707. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  44708. if (this._pointerPressed.length > 1) {
  44709. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  44710. }
  44711. else {
  44712. var speed = camera._computeLocalCameraSpeed();
  44713. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  44714. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  44715. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  44716. }
  44717. }
  44718. };
  44719. FreeCameraTouchInput.prototype.getTypeName = function () {
  44720. return "FreeCameraTouchInput";
  44721. };
  44722. FreeCameraTouchInput.prototype.getSimpleName = function () {
  44723. return "touch";
  44724. };
  44725. return FreeCameraTouchInput;
  44726. }());
  44727. __decorate([
  44728. BABYLON.serialize()
  44729. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  44730. __decorate([
  44731. BABYLON.serialize()
  44732. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  44733. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  44734. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  44735. })(BABYLON || (BABYLON = {}));
  44736. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  44737. /// <reference path="babylon.freeCamera.ts" />
  44738. var BABYLON;
  44739. (function (BABYLON) {
  44740. // We're mainly based on the logic defined into the FreeCamera code
  44741. var TouchCamera = (function (_super) {
  44742. __extends(TouchCamera, _super);
  44743. //-- end properties for backward compatibility for inputs
  44744. function TouchCamera(name, position, scene) {
  44745. var _this = _super.call(this, name, position, scene) || this;
  44746. _this.inputs.addTouch();
  44747. _this._setupInputs();
  44748. return _this;
  44749. }
  44750. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  44751. //-- Begin properties for backward compatibility for inputs
  44752. get: function () {
  44753. var touch = this.inputs.attached["touch"];
  44754. if (touch)
  44755. return touch.touchAngularSensibility;
  44756. },
  44757. set: function (value) {
  44758. var touch = this.inputs.attached["touch"];
  44759. if (touch)
  44760. touch.touchAngularSensibility = value;
  44761. },
  44762. enumerable: true,
  44763. configurable: true
  44764. });
  44765. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  44766. get: function () {
  44767. var touch = this.inputs.attached["touch"];
  44768. if (touch)
  44769. return touch.touchMoveSensibility;
  44770. },
  44771. set: function (value) {
  44772. var touch = this.inputs.attached["touch"];
  44773. if (touch)
  44774. touch.touchMoveSensibility = value;
  44775. },
  44776. enumerable: true,
  44777. configurable: true
  44778. });
  44779. TouchCamera.prototype.getClassName = function () {
  44780. return "TouchCamera";
  44781. };
  44782. TouchCamera.prototype._setupInputs = function () {
  44783. var mouse = this.inputs.attached["mouse"];
  44784. if (mouse) {
  44785. mouse.touchEnabled = false;
  44786. }
  44787. };
  44788. return TouchCamera;
  44789. }(BABYLON.FreeCamera));
  44790. BABYLON.TouchCamera = TouchCamera;
  44791. })(BABYLON || (BABYLON = {}));
  44792. //# sourceMappingURL=babylon.touchCamera.js.map
  44793. var BABYLON;
  44794. (function (BABYLON) {
  44795. var ProceduralTexture = (function (_super) {
  44796. __extends(ProceduralTexture, _super);
  44797. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  44798. if (generateMipMaps === void 0) { generateMipMaps = true; }
  44799. if (isCube === void 0) { isCube = false; }
  44800. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  44801. _this.isCube = isCube;
  44802. _this.isEnabled = true;
  44803. _this._currentRefreshId = -1;
  44804. _this._refreshRate = 1;
  44805. _this._vertexBuffers = {};
  44806. _this._uniforms = new Array();
  44807. _this._samplers = new Array();
  44808. _this._textures = new Array();
  44809. _this._floats = new Array();
  44810. _this._floatsArrays = {};
  44811. _this._colors3 = new Array();
  44812. _this._colors4 = new Array();
  44813. _this._vectors2 = new Array();
  44814. _this._vectors3 = new Array();
  44815. _this._matrices = new Array();
  44816. _this._fallbackTextureUsed = false;
  44817. scene._proceduralTextures.push(_this);
  44818. _this.name = name;
  44819. _this.isRenderTarget = true;
  44820. _this._size = size;
  44821. _this._generateMipMaps = generateMipMaps;
  44822. _this.setFragment(fragment);
  44823. _this._fallbackTexture = fallbackTexture;
  44824. var engine = scene.getEngine();
  44825. if (isCube) {
  44826. _this._texture = engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  44827. _this.setFloat("face", 0);
  44828. }
  44829. else {
  44830. _this._texture = engine.createRenderTargetTexture(size, generateMipMaps);
  44831. }
  44832. // VBO
  44833. var vertices = [];
  44834. vertices.push(1, 1);
  44835. vertices.push(-1, 1);
  44836. vertices.push(-1, -1);
  44837. vertices.push(1, -1);
  44838. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  44839. // Indices
  44840. var indices = [];
  44841. indices.push(0);
  44842. indices.push(1);
  44843. indices.push(2);
  44844. indices.push(0);
  44845. indices.push(2);
  44846. indices.push(3);
  44847. _this._indexBuffer = engine.createIndexBuffer(indices);
  44848. return _this;
  44849. }
  44850. ProceduralTexture.prototype.reset = function () {
  44851. if (this._effect === undefined) {
  44852. return;
  44853. }
  44854. var engine = this.getScene().getEngine();
  44855. engine._releaseEffect(this._effect);
  44856. };
  44857. ProceduralTexture.prototype.isReady = function () {
  44858. var _this = this;
  44859. var engine = this.getScene().getEngine();
  44860. var shaders;
  44861. if (!this._fragment) {
  44862. return false;
  44863. }
  44864. if (this._fallbackTextureUsed) {
  44865. return true;
  44866. }
  44867. if (this._fragment.fragmentElement !== undefined) {
  44868. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  44869. }
  44870. else {
  44871. shaders = { vertex: "procedural", fragment: this._fragment };
  44872. }
  44873. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", null, null, function () {
  44874. _this.releaseInternalTexture();
  44875. if (_this._fallbackTexture) {
  44876. _this._texture = _this._fallbackTexture._texture;
  44877. _this._texture.references++;
  44878. }
  44879. _this._fallbackTextureUsed = true;
  44880. });
  44881. return this._effect.isReady();
  44882. };
  44883. ProceduralTexture.prototype.resetRefreshCounter = function () {
  44884. this._currentRefreshId = -1;
  44885. };
  44886. ProceduralTexture.prototype.setFragment = function (fragment) {
  44887. this._fragment = fragment;
  44888. };
  44889. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  44890. get: function () {
  44891. return this._refreshRate;
  44892. },
  44893. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  44894. set: function (value) {
  44895. this._refreshRate = value;
  44896. this.resetRefreshCounter();
  44897. },
  44898. enumerable: true,
  44899. configurable: true
  44900. });
  44901. ProceduralTexture.prototype._shouldRender = function () {
  44902. if (!this.isEnabled || !this.isReady() || !this._texture) {
  44903. return false;
  44904. }
  44905. if (this._fallbackTextureUsed) {
  44906. return false;
  44907. }
  44908. if (this._currentRefreshId === -1) {
  44909. this._currentRefreshId = 1;
  44910. return true;
  44911. }
  44912. if (this.refreshRate === this._currentRefreshId) {
  44913. this._currentRefreshId = 1;
  44914. return true;
  44915. }
  44916. this._currentRefreshId++;
  44917. return false;
  44918. };
  44919. ProceduralTexture.prototype.getRenderSize = function () {
  44920. return this._size;
  44921. };
  44922. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  44923. if (this._fallbackTextureUsed) {
  44924. return;
  44925. }
  44926. this.releaseInternalTexture();
  44927. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  44928. };
  44929. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  44930. if (this._uniforms.indexOf(uniformName) === -1) {
  44931. this._uniforms.push(uniformName);
  44932. }
  44933. };
  44934. ProceduralTexture.prototype.setTexture = function (name, texture) {
  44935. if (this._samplers.indexOf(name) === -1) {
  44936. this._samplers.push(name);
  44937. }
  44938. this._textures[name] = texture;
  44939. return this;
  44940. };
  44941. ProceduralTexture.prototype.setFloat = function (name, value) {
  44942. this._checkUniform(name);
  44943. this._floats[name] = value;
  44944. return this;
  44945. };
  44946. ProceduralTexture.prototype.setFloats = function (name, value) {
  44947. this._checkUniform(name);
  44948. this._floatsArrays[name] = value;
  44949. return this;
  44950. };
  44951. ProceduralTexture.prototype.setColor3 = function (name, value) {
  44952. this._checkUniform(name);
  44953. this._colors3[name] = value;
  44954. return this;
  44955. };
  44956. ProceduralTexture.prototype.setColor4 = function (name, value) {
  44957. this._checkUniform(name);
  44958. this._colors4[name] = value;
  44959. return this;
  44960. };
  44961. ProceduralTexture.prototype.setVector2 = function (name, value) {
  44962. this._checkUniform(name);
  44963. this._vectors2[name] = value;
  44964. return this;
  44965. };
  44966. ProceduralTexture.prototype.setVector3 = function (name, value) {
  44967. this._checkUniform(name);
  44968. this._vectors3[name] = value;
  44969. return this;
  44970. };
  44971. ProceduralTexture.prototype.setMatrix = function (name, value) {
  44972. this._checkUniform(name);
  44973. this._matrices[name] = value;
  44974. return this;
  44975. };
  44976. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  44977. var scene = this.getScene();
  44978. var engine = scene.getEngine();
  44979. // Render
  44980. engine.enableEffect(this._effect);
  44981. engine.setState(false);
  44982. // Texture
  44983. for (var name in this._textures) {
  44984. this._effect.setTexture(name, this._textures[name]);
  44985. }
  44986. // Float
  44987. for (name in this._floats) {
  44988. this._effect.setFloat(name, this._floats[name]);
  44989. }
  44990. // Floats
  44991. for (name in this._floatsArrays) {
  44992. this._effect.setArray(name, this._floatsArrays[name]);
  44993. }
  44994. // Color3
  44995. for (name in this._colors3) {
  44996. this._effect.setColor3(name, this._colors3[name]);
  44997. }
  44998. // Color4
  44999. for (name in this._colors4) {
  45000. var color = this._colors4[name];
  45001. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  45002. }
  45003. // Vector2
  45004. for (name in this._vectors2) {
  45005. this._effect.setVector2(name, this._vectors2[name]);
  45006. }
  45007. // Vector3
  45008. for (name in this._vectors3) {
  45009. this._effect.setVector3(name, this._vectors3[name]);
  45010. }
  45011. // Matrix
  45012. for (name in this._matrices) {
  45013. this._effect.setMatrix(name, this._matrices[name]);
  45014. }
  45015. if (this.isCube) {
  45016. for (var face = 0; face < 6; face++) {
  45017. engine.bindFramebuffer(this._texture, face);
  45018. // VBOs
  45019. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  45020. this._effect.setFloat("face", face);
  45021. // Clear
  45022. engine.clear(scene.clearColor, true, true, true);
  45023. // Draw order
  45024. engine.draw(true, 0, 6);
  45025. // Mipmaps
  45026. if (face === 5) {
  45027. engine.generateMipMapsForCubemap(this._texture);
  45028. }
  45029. }
  45030. }
  45031. else {
  45032. engine.bindFramebuffer(this._texture);
  45033. // VBOs
  45034. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  45035. // Clear
  45036. engine.clear(scene.clearColor, true, true, true);
  45037. // Draw order
  45038. engine.draw(true, 0, 6);
  45039. }
  45040. // Unbind
  45041. engine.unBindFramebuffer(this._texture, this.isCube);
  45042. if (this.onGenerated) {
  45043. this.onGenerated();
  45044. }
  45045. };
  45046. ProceduralTexture.prototype.clone = function () {
  45047. var textureSize = this.getSize();
  45048. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  45049. // Base texture
  45050. newTexture.hasAlpha = this.hasAlpha;
  45051. newTexture.level = this.level;
  45052. // RenderTarget Texture
  45053. newTexture.coordinatesMode = this.coordinatesMode;
  45054. return newTexture;
  45055. };
  45056. ProceduralTexture.prototype.dispose = function () {
  45057. var index = this.getScene()._proceduralTextures.indexOf(this);
  45058. if (index >= 0) {
  45059. this.getScene()._proceduralTextures.splice(index, 1);
  45060. }
  45061. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  45062. if (vertexBuffer) {
  45063. vertexBuffer.dispose();
  45064. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  45065. }
  45066. if (this._indexBuffer && this.getScene().getEngine()._releaseBuffer(this._indexBuffer)) {
  45067. this._indexBuffer = null;
  45068. }
  45069. _super.prototype.dispose.call(this);
  45070. };
  45071. return ProceduralTexture;
  45072. }(BABYLON.Texture));
  45073. BABYLON.ProceduralTexture = ProceduralTexture;
  45074. })(BABYLON || (BABYLON = {}));
  45075. //# sourceMappingURL=babylon.proceduralTexture.js.map
  45076. /// <reference path="babylon.proceduralTexture.ts" />
  45077. var BABYLON;
  45078. (function (BABYLON) {
  45079. var CustomProceduralTexture = (function (_super) {
  45080. __extends(CustomProceduralTexture, _super);
  45081. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  45082. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  45083. _this._animate = true;
  45084. _this._time = 0;
  45085. _this._texturePath = texturePath;
  45086. //Try to load json
  45087. _this.loadJson(texturePath);
  45088. _this.refreshRate = 1;
  45089. return _this;
  45090. }
  45091. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  45092. var _this = this;
  45093. var that = this;
  45094. function noConfigFile() {
  45095. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  45096. try {
  45097. that.setFragment(that._texturePath);
  45098. }
  45099. catch (ex) {
  45100. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  45101. }
  45102. }
  45103. var configFileUrl = jsonUrl + "/config.json";
  45104. var xhr = new XMLHttpRequest();
  45105. xhr.open("GET", configFileUrl, true);
  45106. xhr.addEventListener("load", function () {
  45107. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  45108. try {
  45109. _this._config = JSON.parse(xhr.response);
  45110. _this.updateShaderUniforms();
  45111. _this.updateTextures();
  45112. _this.setFragment(_this._texturePath + "/custom");
  45113. _this._animate = _this._config.animate;
  45114. _this.refreshRate = _this._config.refreshrate;
  45115. }
  45116. catch (ex) {
  45117. noConfigFile();
  45118. }
  45119. }
  45120. else {
  45121. noConfigFile();
  45122. }
  45123. }, false);
  45124. xhr.addEventListener("error", function () {
  45125. noConfigFile();
  45126. }, false);
  45127. try {
  45128. xhr.send();
  45129. }
  45130. catch (ex) {
  45131. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  45132. }
  45133. };
  45134. CustomProceduralTexture.prototype.isReady = function () {
  45135. if (!_super.prototype.isReady.call(this)) {
  45136. return false;
  45137. }
  45138. for (var name in this._textures) {
  45139. var texture = this._textures[name];
  45140. if (!texture.isReady()) {
  45141. return false;
  45142. }
  45143. }
  45144. return true;
  45145. };
  45146. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  45147. if (this._animate) {
  45148. this._time += this.getScene().getAnimationRatio() * 0.03;
  45149. this.updateShaderUniforms();
  45150. }
  45151. _super.prototype.render.call(this, useCameraPostProcess);
  45152. };
  45153. CustomProceduralTexture.prototype.updateTextures = function () {
  45154. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  45155. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  45156. }
  45157. };
  45158. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  45159. if (this._config) {
  45160. for (var j = 0; j < this._config.uniforms.length; j++) {
  45161. var uniform = this._config.uniforms[j];
  45162. switch (uniform.type) {
  45163. case "float":
  45164. this.setFloat(uniform.name, uniform.value);
  45165. break;
  45166. case "color3":
  45167. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  45168. break;
  45169. case "color4":
  45170. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  45171. break;
  45172. case "vector2":
  45173. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  45174. break;
  45175. case "vector3":
  45176. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  45177. break;
  45178. }
  45179. }
  45180. }
  45181. this.setFloat("time", this._time);
  45182. };
  45183. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  45184. get: function () {
  45185. return this._animate;
  45186. },
  45187. set: function (value) {
  45188. this._animate = value;
  45189. },
  45190. enumerable: true,
  45191. configurable: true
  45192. });
  45193. return CustomProceduralTexture;
  45194. }(BABYLON.ProceduralTexture));
  45195. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  45196. })(BABYLON || (BABYLON = {}));
  45197. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  45198. var BABYLON;
  45199. (function (BABYLON) {
  45200. var FreeCameraGamepadInput = (function () {
  45201. function FreeCameraGamepadInput() {
  45202. this.gamepadAngularSensibility = 200;
  45203. this.gamepadMoveSensibility = 40;
  45204. // private members
  45205. this._cameraTransform = BABYLON.Matrix.Identity();
  45206. this._deltaTransform = BABYLON.Vector3.Zero();
  45207. this._vector3 = BABYLON.Vector3.Zero();
  45208. this._vector2 = BABYLON.Vector2.Zero();
  45209. }
  45210. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  45211. var _this = this;
  45212. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  45213. };
  45214. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  45215. if (this._gamepads) {
  45216. this._gamepads.dispose();
  45217. }
  45218. this.gamepad = null;
  45219. };
  45220. FreeCameraGamepadInput.prototype.checkInputs = function () {
  45221. if (this.gamepad && this.gamepad.leftStick) {
  45222. var camera = this.camera;
  45223. var LSValues = this.gamepad.leftStick;
  45224. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  45225. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  45226. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  45227. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  45228. var RSValues = this.gamepad.rightStick;
  45229. if (RSValues) {
  45230. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  45231. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  45232. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  45233. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  45234. }
  45235. else {
  45236. RSValues = { x: 0, y: 0 };
  45237. }
  45238. if (!camera.rotationQuaternion) {
  45239. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  45240. }
  45241. else {
  45242. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  45243. }
  45244. var speed = camera._computeLocalCameraSpeed() * 50.0;
  45245. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  45246. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  45247. camera.cameraDirection.addInPlace(this._deltaTransform);
  45248. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  45249. camera.cameraRotation.addInPlace(this._vector2);
  45250. }
  45251. };
  45252. FreeCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  45253. // Only the first gamepad found can control the camera
  45254. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  45255. // prioritize XBOX gamepads.
  45256. if (!this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  45257. this.gamepad = gamepad;
  45258. }
  45259. }
  45260. };
  45261. FreeCameraGamepadInput.prototype.getTypeName = function () {
  45262. return "FreeCameraGamepadInput";
  45263. };
  45264. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  45265. return "gamepad";
  45266. };
  45267. return FreeCameraGamepadInput;
  45268. }());
  45269. __decorate([
  45270. BABYLON.serialize()
  45271. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  45272. __decorate([
  45273. BABYLON.serialize()
  45274. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  45275. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  45276. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  45277. })(BABYLON || (BABYLON = {}));
  45278. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  45279. var BABYLON;
  45280. (function (BABYLON) {
  45281. var ArcRotateCameraGamepadInput = (function () {
  45282. function ArcRotateCameraGamepadInput() {
  45283. this.gamepadRotationSensibility = 80;
  45284. this.gamepadMoveSensibility = 40;
  45285. }
  45286. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  45287. var _this = this;
  45288. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  45289. };
  45290. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  45291. if (this._gamepads) {
  45292. this._gamepads.dispose();
  45293. }
  45294. this.gamepad = null;
  45295. };
  45296. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  45297. if (this.gamepad) {
  45298. var camera = this.camera;
  45299. var RSValues = this.gamepad.rightStick;
  45300. if (RSValues) {
  45301. if (RSValues.x != 0) {
  45302. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  45303. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  45304. camera.inertialAlphaOffset += normalizedRX;
  45305. }
  45306. }
  45307. if (RSValues.y != 0) {
  45308. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  45309. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  45310. camera.inertialBetaOffset += normalizedRY;
  45311. }
  45312. }
  45313. }
  45314. var LSValues = this.gamepad.leftStick;
  45315. if (LSValues && LSValues.y != 0) {
  45316. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  45317. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  45318. this.camera.inertialRadiusOffset -= normalizedLY;
  45319. }
  45320. }
  45321. }
  45322. };
  45323. ArcRotateCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  45324. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  45325. // prioritize XBOX gamepads.
  45326. if (!this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  45327. this.gamepad = gamepad;
  45328. }
  45329. }
  45330. };
  45331. ArcRotateCameraGamepadInput.prototype.getTypeName = function () {
  45332. return "ArcRotateCameraGamepadInput";
  45333. };
  45334. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  45335. return "gamepad";
  45336. };
  45337. return ArcRotateCameraGamepadInput;
  45338. }());
  45339. __decorate([
  45340. BABYLON.serialize()
  45341. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  45342. __decorate([
  45343. BABYLON.serialize()
  45344. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  45345. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  45346. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  45347. })(BABYLON || (BABYLON = {}));
  45348. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  45349. var BABYLON;
  45350. (function (BABYLON) {
  45351. var Gamepads = (function () {
  45352. function Gamepads(ongamedpadconnected) {
  45353. var _this = this;
  45354. this.babylonGamepads = [];
  45355. this.oneGamepadConnected = false;
  45356. this.isMonitoring = false;
  45357. this.gamepadEventSupported = 'GamepadEvent' in window;
  45358. this.gamepadSupport = (navigator.getGamepads ||
  45359. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  45360. this._callbackGamepadConnected = ongamedpadconnected;
  45361. if (this.gamepadSupport) {
  45362. //first add already-connected gamepads
  45363. this._updateGamepadObjects();
  45364. if (this.babylonGamepads.length) {
  45365. this._startMonitoringGamepads();
  45366. }
  45367. // Checking if the gamepad connected event is supported (like in Firefox)
  45368. if (this.gamepadEventSupported) {
  45369. this._onGamepadConnectedEvent = function (evt) {
  45370. _this._onGamepadConnected(evt.gamepad);
  45371. };
  45372. this._onGamepadDisonnectedEvent = function (evt) {
  45373. _this._onGamepadDisconnected(evt);
  45374. };
  45375. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  45376. window.addEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  45377. }
  45378. else {
  45379. this._startMonitoringGamepads();
  45380. }
  45381. }
  45382. }
  45383. Gamepads.prototype.dispose = function () {
  45384. if (Gamepads.gamepadDOMInfo) {
  45385. document.body.removeChild(Gamepads.gamepadDOMInfo);
  45386. }
  45387. if (this._onGamepadConnectedEvent) {
  45388. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  45389. window.removeEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  45390. this._onGamepadConnectedEvent = null;
  45391. this._onGamepadDisonnectedEvent = null;
  45392. }
  45393. };
  45394. Gamepads.prototype._onGamepadConnected = function (gamepad) {
  45395. var newGamepad = this._addNewGamepad(gamepad);
  45396. if (this._callbackGamepadConnected)
  45397. this._callbackGamepadConnected(newGamepad);
  45398. this._startMonitoringGamepads();
  45399. };
  45400. Gamepads.prototype._addNewGamepad = function (gamepad) {
  45401. if (!this.oneGamepadConnected) {
  45402. this.oneGamepadConnected = true;
  45403. if (Gamepads.gamepadDOMInfo) {
  45404. document.body.removeChild(Gamepads.gamepadDOMInfo);
  45405. Gamepads.gamepadDOMInfo = null;
  45406. }
  45407. }
  45408. var newGamepad;
  45409. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  45410. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  45411. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  45412. }
  45413. else if (gamepad.pose) {
  45414. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  45415. }
  45416. else {
  45417. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  45418. }
  45419. this.babylonGamepads.push(newGamepad);
  45420. return newGamepad;
  45421. };
  45422. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  45423. // Remove the gamepad from the list of gamepads to monitor.
  45424. for (var i in this.babylonGamepads) {
  45425. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  45426. this.babylonGamepads.splice(+i, 1);
  45427. break;
  45428. }
  45429. }
  45430. // If no gamepads are left, stop the polling loop.
  45431. if (this.babylonGamepads.length == 0) {
  45432. this._stopMonitoringGamepads();
  45433. }
  45434. };
  45435. Gamepads.prototype._startMonitoringGamepads = function () {
  45436. if (!this.isMonitoring) {
  45437. this.isMonitoring = true;
  45438. this._checkGamepadsStatus();
  45439. }
  45440. };
  45441. Gamepads.prototype._stopMonitoringGamepads = function () {
  45442. this.isMonitoring = false;
  45443. };
  45444. Gamepads.prototype._checkGamepadsStatus = function () {
  45445. var _this = this;
  45446. // updating gamepad objects
  45447. this._updateGamepadObjects();
  45448. for (var i in this.babylonGamepads) {
  45449. this.babylonGamepads[i].update();
  45450. }
  45451. if (this.isMonitoring) {
  45452. if (window.requestAnimationFrame) {
  45453. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  45454. }
  45455. else if (window.mozRequestAnimationFrame) {
  45456. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  45457. }
  45458. else if (window.webkitRequestAnimationFrame) {
  45459. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  45460. }
  45461. }
  45462. };
  45463. // This function is called only on Chrome, which does not yet support
  45464. // connection/disconnection events, but requires you to monitor
  45465. // an array for changes.
  45466. Gamepads.prototype._updateGamepadObjects = function () {
  45467. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  45468. for (var i = 0; i < gamepads.length; i++) {
  45469. if (gamepads[i]) {
  45470. if (!(gamepads[i].index in this.babylonGamepads)) {
  45471. var newGamepad = this._addNewGamepad(gamepads[i]);
  45472. if (this._callbackGamepadConnected) {
  45473. this._callbackGamepadConnected(newGamepad);
  45474. }
  45475. }
  45476. else {
  45477. this.babylonGamepads[i].browserGamepad = gamepads[i];
  45478. }
  45479. }
  45480. }
  45481. };
  45482. return Gamepads;
  45483. }());
  45484. BABYLON.Gamepads = Gamepads;
  45485. var StickValues = (function () {
  45486. function StickValues(x, y) {
  45487. this.x = x;
  45488. this.y = y;
  45489. }
  45490. return StickValues;
  45491. }());
  45492. BABYLON.StickValues = StickValues;
  45493. var Gamepad = (function () {
  45494. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  45495. if (leftStickX === void 0) { leftStickX = 0; }
  45496. if (leftStickY === void 0) { leftStickY = 1; }
  45497. if (rightStickX === void 0) { rightStickX = 2; }
  45498. if (rightStickY === void 0) { rightStickY = 3; }
  45499. this.id = id;
  45500. this.index = index;
  45501. this.browserGamepad = browserGamepad;
  45502. this.type = Gamepad.GAMEPAD;
  45503. this._leftStickAxisX = leftStickX;
  45504. this._leftStickAxisY = leftStickY;
  45505. this._rightStickAxisX = rightStickX;
  45506. this._rightStickAxisY = rightStickY;
  45507. if (this.browserGamepad.axes.length >= 2) {
  45508. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  45509. }
  45510. if (this.browserGamepad.axes.length >= 4) {
  45511. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  45512. }
  45513. }
  45514. Gamepad.prototype.onleftstickchanged = function (callback) {
  45515. this._onleftstickchanged = callback;
  45516. };
  45517. Gamepad.prototype.onrightstickchanged = function (callback) {
  45518. this._onrightstickchanged = callback;
  45519. };
  45520. Object.defineProperty(Gamepad.prototype, "leftStick", {
  45521. get: function () {
  45522. return this._leftStick;
  45523. },
  45524. set: function (newValues) {
  45525. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  45526. this._onleftstickchanged(newValues);
  45527. }
  45528. this._leftStick = newValues;
  45529. },
  45530. enumerable: true,
  45531. configurable: true
  45532. });
  45533. Object.defineProperty(Gamepad.prototype, "rightStick", {
  45534. get: function () {
  45535. return this._rightStick;
  45536. },
  45537. set: function (newValues) {
  45538. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  45539. this._onrightstickchanged(newValues);
  45540. }
  45541. this._rightStick = newValues;
  45542. },
  45543. enumerable: true,
  45544. configurable: true
  45545. });
  45546. Gamepad.prototype.update = function () {
  45547. if (this._leftStick) {
  45548. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  45549. }
  45550. if (this._rightStick) {
  45551. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  45552. }
  45553. };
  45554. return Gamepad;
  45555. }());
  45556. Gamepad.GAMEPAD = 0;
  45557. Gamepad.GENERIC = 1;
  45558. Gamepad.XBOX = 2;
  45559. Gamepad.POSE_ENABLED = 3;
  45560. BABYLON.Gamepad = Gamepad;
  45561. var GenericPad = (function (_super) {
  45562. __extends(GenericPad, _super);
  45563. function GenericPad(id, index, gamepad) {
  45564. var _this = _super.call(this, id, index, gamepad) || this;
  45565. _this.id = id;
  45566. _this.index = index;
  45567. _this.gamepad = gamepad;
  45568. _this.type = Gamepad.GENERIC;
  45569. _this._buttons = new Array(gamepad.buttons.length);
  45570. return _this;
  45571. }
  45572. GenericPad.prototype.onbuttondown = function (callback) {
  45573. this._onbuttondown = callback;
  45574. };
  45575. GenericPad.prototype.onbuttonup = function (callback) {
  45576. this._onbuttonup = callback;
  45577. };
  45578. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  45579. if (newValue !== currentValue) {
  45580. if (this._onbuttondown && newValue === 1) {
  45581. this._onbuttondown(buttonIndex);
  45582. }
  45583. if (this._onbuttonup && newValue === 0) {
  45584. this._onbuttonup(buttonIndex);
  45585. }
  45586. }
  45587. return newValue;
  45588. };
  45589. GenericPad.prototype.update = function () {
  45590. _super.prototype.update.call(this);
  45591. for (var index = 0; index < this._buttons.length; index++) {
  45592. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  45593. }
  45594. };
  45595. return GenericPad;
  45596. }(Gamepad));
  45597. BABYLON.GenericPad = GenericPad;
  45598. var Xbox360Button;
  45599. (function (Xbox360Button) {
  45600. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  45601. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  45602. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  45603. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  45604. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  45605. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  45606. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  45607. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  45608. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  45609. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  45610. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  45611. var Xbox360Dpad;
  45612. (function (Xbox360Dpad) {
  45613. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  45614. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  45615. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  45616. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  45617. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  45618. var Xbox360Pad = (function (_super) {
  45619. __extends(Xbox360Pad, _super);
  45620. function Xbox360Pad(id, index, gamepad, xboxOne) {
  45621. if (xboxOne === void 0) { xboxOne = false; }
  45622. var _this = _super.call(this, id, index, gamepad, 0, 1, (xboxOne ? 3 : 2), (xboxOne ? 4 : 3)) || this;
  45623. _this._leftTrigger = 0;
  45624. _this._rightTrigger = 0;
  45625. _this._buttonA = 0;
  45626. _this._buttonB = 0;
  45627. _this._buttonX = 0;
  45628. _this._buttonY = 0;
  45629. _this._buttonBack = 0;
  45630. _this._buttonStart = 0;
  45631. _this._buttonLB = 0;
  45632. _this._buttonRB = 0;
  45633. _this._buttonLeftStick = 0;
  45634. _this._buttonRightStick = 0;
  45635. _this._dPadUp = 0;
  45636. _this._dPadDown = 0;
  45637. _this._dPadLeft = 0;
  45638. _this._dPadRight = 0;
  45639. _this._isXboxOnePad = false;
  45640. _this.type = Gamepad.XBOX;
  45641. _this._isXboxOnePad = xboxOne;
  45642. return _this;
  45643. }
  45644. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  45645. this._onlefttriggerchanged = callback;
  45646. };
  45647. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  45648. this._onrighttriggerchanged = callback;
  45649. };
  45650. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  45651. get: function () {
  45652. return this._leftTrigger;
  45653. },
  45654. set: function (newValue) {
  45655. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  45656. this._onlefttriggerchanged(newValue);
  45657. }
  45658. this._leftTrigger = newValue;
  45659. },
  45660. enumerable: true,
  45661. configurable: true
  45662. });
  45663. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  45664. get: function () {
  45665. return this._rightTrigger;
  45666. },
  45667. set: function (newValue) {
  45668. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  45669. this._onrighttriggerchanged(newValue);
  45670. }
  45671. this._rightTrigger = newValue;
  45672. },
  45673. enumerable: true,
  45674. configurable: true
  45675. });
  45676. Xbox360Pad.prototype.onbuttondown = function (callback) {
  45677. this._onbuttondown = callback;
  45678. };
  45679. Xbox360Pad.prototype.onbuttonup = function (callback) {
  45680. this._onbuttonup = callback;
  45681. };
  45682. Xbox360Pad.prototype.ondpaddown = function (callback) {
  45683. this._ondpaddown = callback;
  45684. };
  45685. Xbox360Pad.prototype.ondpadup = function (callback) {
  45686. this._ondpadup = callback;
  45687. };
  45688. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  45689. if (newValue !== currentValue) {
  45690. if (this._onbuttondown && newValue === 1) {
  45691. this._onbuttondown(buttonType);
  45692. }
  45693. if (this._onbuttonup && newValue === 0) {
  45694. this._onbuttonup(buttonType);
  45695. }
  45696. }
  45697. return newValue;
  45698. };
  45699. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  45700. if (newValue !== currentValue) {
  45701. if (this._ondpaddown && newValue === 1) {
  45702. this._ondpaddown(buttonType);
  45703. }
  45704. if (this._ondpadup && newValue === 0) {
  45705. this._ondpadup(buttonType);
  45706. }
  45707. }
  45708. return newValue;
  45709. };
  45710. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  45711. get: function () {
  45712. return this._buttonA;
  45713. },
  45714. set: function (value) {
  45715. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  45716. },
  45717. enumerable: true,
  45718. configurable: true
  45719. });
  45720. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  45721. get: function () {
  45722. return this._buttonB;
  45723. },
  45724. set: function (value) {
  45725. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  45726. },
  45727. enumerable: true,
  45728. configurable: true
  45729. });
  45730. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  45731. get: function () {
  45732. return this._buttonX;
  45733. },
  45734. set: function (value) {
  45735. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  45736. },
  45737. enumerable: true,
  45738. configurable: true
  45739. });
  45740. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  45741. get: function () {
  45742. return this._buttonY;
  45743. },
  45744. set: function (value) {
  45745. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  45746. },
  45747. enumerable: true,
  45748. configurable: true
  45749. });
  45750. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  45751. get: function () {
  45752. return this._buttonStart;
  45753. },
  45754. set: function (value) {
  45755. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  45756. },
  45757. enumerable: true,
  45758. configurable: true
  45759. });
  45760. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  45761. get: function () {
  45762. return this._buttonBack;
  45763. },
  45764. set: function (value) {
  45765. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  45766. },
  45767. enumerable: true,
  45768. configurable: true
  45769. });
  45770. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  45771. get: function () {
  45772. return this._buttonLB;
  45773. },
  45774. set: function (value) {
  45775. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  45776. },
  45777. enumerable: true,
  45778. configurable: true
  45779. });
  45780. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  45781. get: function () {
  45782. return this._buttonRB;
  45783. },
  45784. set: function (value) {
  45785. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  45786. },
  45787. enumerable: true,
  45788. configurable: true
  45789. });
  45790. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  45791. get: function () {
  45792. return this._buttonLeftStick;
  45793. },
  45794. set: function (value) {
  45795. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  45796. },
  45797. enumerable: true,
  45798. configurable: true
  45799. });
  45800. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  45801. get: function () {
  45802. return this._buttonRightStick;
  45803. },
  45804. set: function (value) {
  45805. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  45806. },
  45807. enumerable: true,
  45808. configurable: true
  45809. });
  45810. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  45811. get: function () {
  45812. return this._dPadUp;
  45813. },
  45814. set: function (value) {
  45815. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  45816. },
  45817. enumerable: true,
  45818. configurable: true
  45819. });
  45820. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  45821. get: function () {
  45822. return this._dPadDown;
  45823. },
  45824. set: function (value) {
  45825. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  45826. },
  45827. enumerable: true,
  45828. configurable: true
  45829. });
  45830. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  45831. get: function () {
  45832. return this._dPadLeft;
  45833. },
  45834. set: function (value) {
  45835. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  45836. },
  45837. enumerable: true,
  45838. configurable: true
  45839. });
  45840. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  45841. get: function () {
  45842. return this._dPadRight;
  45843. },
  45844. set: function (value) {
  45845. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  45846. },
  45847. enumerable: true,
  45848. configurable: true
  45849. });
  45850. Xbox360Pad.prototype.update = function () {
  45851. _super.prototype.update.call(this);
  45852. if (this._isXboxOnePad) {
  45853. this.buttonA = this.browserGamepad.buttons[0].value;
  45854. this.buttonB = this.browserGamepad.buttons[1].value;
  45855. this.buttonX = this.browserGamepad.buttons[2].value;
  45856. this.buttonY = this.browserGamepad.buttons[3].value;
  45857. this.buttonLB = this.browserGamepad.buttons[4].value;
  45858. this.buttonRB = this.browserGamepad.buttons[5].value;
  45859. this.leftTrigger = this.browserGamepad.axes[2];
  45860. this.rightTrigger = this.browserGamepad.axes[5];
  45861. this.buttonBack = this.browserGamepad.buttons[9].value;
  45862. this.buttonStart = this.browserGamepad.buttons[8].value;
  45863. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  45864. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  45865. this.dPadUp = this.browserGamepad.buttons[11].value;
  45866. this.dPadDown = this.browserGamepad.buttons[12].value;
  45867. this.dPadLeft = this.browserGamepad.buttons[13].value;
  45868. this.dPadRight = this.browserGamepad.buttons[14].value;
  45869. }
  45870. else {
  45871. this.buttonA = this.browserGamepad.buttons[0].value;
  45872. this.buttonB = this.browserGamepad.buttons[1].value;
  45873. this.buttonX = this.browserGamepad.buttons[2].value;
  45874. this.buttonY = this.browserGamepad.buttons[3].value;
  45875. this.buttonLB = this.browserGamepad.buttons[4].value;
  45876. this.buttonRB = this.browserGamepad.buttons[5].value;
  45877. this.leftTrigger = this.browserGamepad.buttons[6].value;
  45878. this.rightTrigger = this.browserGamepad.buttons[7].value;
  45879. this.buttonBack = this.browserGamepad.buttons[8].value;
  45880. this.buttonStart = this.browserGamepad.buttons[9].value;
  45881. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  45882. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  45883. this.dPadUp = this.browserGamepad.buttons[12].value;
  45884. this.dPadDown = this.browserGamepad.buttons[13].value;
  45885. this.dPadLeft = this.browserGamepad.buttons[14].value;
  45886. this.dPadRight = this.browserGamepad.buttons[15].value;
  45887. }
  45888. };
  45889. return Xbox360Pad;
  45890. }(Gamepad));
  45891. BABYLON.Xbox360Pad = Xbox360Pad;
  45892. })(BABYLON || (BABYLON = {}));
  45893. //# sourceMappingURL=babylon.gamepads.js.map
  45894. var BABYLON;
  45895. (function (BABYLON) {
  45896. var PoseEnabledControllerType;
  45897. (function (PoseEnabledControllerType) {
  45898. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  45899. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  45900. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 2] = "GENERIC";
  45901. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  45902. var PoseEnabledControllerHelper = (function () {
  45903. function PoseEnabledControllerHelper() {
  45904. }
  45905. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  45906. // for now, only Oculus and Vive are supported
  45907. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  45908. return new OculusTouchController(vrGamepad);
  45909. }
  45910. else {
  45911. return new ViveController(vrGamepad);
  45912. }
  45913. };
  45914. return PoseEnabledControllerHelper;
  45915. }());
  45916. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  45917. var PoseEnabledController = (function (_super) {
  45918. __extends(PoseEnabledController, _super);
  45919. function PoseEnabledController(vrGamepad) {
  45920. var _this = _super.call(this, vrGamepad.id, vrGamepad.index, vrGamepad) || this;
  45921. _this.vrGamepad = vrGamepad;
  45922. _this.deviceScaleFactor = 1;
  45923. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  45924. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  45925. _this.controllerType = PoseEnabledControllerType.GENERIC;
  45926. _this.position = BABYLON.Vector3.Zero();
  45927. _this.rotationQuaternion = new BABYLON.Quaternion();
  45928. _this.devicePosition = BABYLON.Vector3.Zero();
  45929. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  45930. _this._calculatedPosition = BABYLON.Vector3.Zero();
  45931. _this._calculatedRotation = new BABYLON.Quaternion();
  45932. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  45933. return _this;
  45934. }
  45935. PoseEnabledController.prototype.update = function () {
  45936. _super.prototype.update.call(this);
  45937. var pose = this.vrGamepad.pose;
  45938. this.updateFromDevice(pose);
  45939. if (this._mesh) {
  45940. this._mesh.position.copyFrom(this._calculatedPosition);
  45941. this._mesh.rotationQuaternion.copyFrom(this._calculatedRotation);
  45942. }
  45943. };
  45944. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  45945. if (poseData) {
  45946. this.rawPose = poseData;
  45947. if (poseData.position) {
  45948. this.devicePosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  45949. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  45950. this.devicePosition.z *= -1;
  45951. }
  45952. this.devicePosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  45953. this._calculatedPosition.addInPlace(this.position);
  45954. }
  45955. if (poseData.orientation) {
  45956. this.deviceRotationQuaternion.copyFromFloats(this.rawPose.orientation[0], this.rawPose.orientation[1], -this.rawPose.orientation[2], -this.rawPose.orientation[3]);
  45957. if (this._mesh) {
  45958. if (this._mesh.getScene().useRightHandedSystem) {
  45959. this.deviceRotationQuaternion.z *= -1;
  45960. this.deviceRotationQuaternion.w *= -1;
  45961. }
  45962. else {
  45963. this.deviceRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this.deviceRotationQuaternion);
  45964. }
  45965. }
  45966. // if the camera is set, rotate to the camera's rotation
  45967. this.deviceRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  45968. }
  45969. }
  45970. };
  45971. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  45972. if (this._mesh) {
  45973. this._mesh.parent = undefined;
  45974. }
  45975. this._mesh = mesh;
  45976. if (this._poseControlledCamera) {
  45977. this._mesh.parent = this._poseControlledCamera;
  45978. }
  45979. if (!this._mesh.rotationQuaternion) {
  45980. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  45981. }
  45982. };
  45983. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  45984. this._poseControlledCamera = camera;
  45985. if (this._mesh) {
  45986. this._mesh.parent = this._poseControlledCamera;
  45987. }
  45988. };
  45989. PoseEnabledController.prototype.detachMesh = function () {
  45990. this._mesh = undefined;
  45991. };
  45992. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  45993. get: function () {
  45994. return this._mesh;
  45995. },
  45996. enumerable: true,
  45997. configurable: true
  45998. });
  45999. PoseEnabledController.prototype.getForwardRay = function (length) {
  46000. if (length === void 0) { length = 100; }
  46001. if (!this.mesh) {
  46002. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  46003. }
  46004. var m = this.mesh.getWorldMatrix();
  46005. var origin = m.getTranslation();
  46006. var forward = new BABYLON.Vector3(0, 0, -1);
  46007. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  46008. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  46009. return new BABYLON.Ray(origin, direction, length);
  46010. };
  46011. return PoseEnabledController;
  46012. }(BABYLON.Gamepad));
  46013. BABYLON.PoseEnabledController = PoseEnabledController;
  46014. var WebVRController = (function (_super) {
  46015. __extends(WebVRController, _super);
  46016. function WebVRController(vrGamepad) {
  46017. var _this = _super.call(this, vrGamepad) || this;
  46018. //public onTriggerStateChangedObservable = new Observable<{ state: ExtendedGamepadButton, changes: GamepadButtonChanges }>();
  46019. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  46020. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  46021. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  46022. _this.onPadStateChangedObservable = new BABYLON.Observable();
  46023. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  46024. _this.pad = { x: 0, y: 0 };
  46025. // avoid GC, store state in a tmp object
  46026. _this._changes = {
  46027. pressChanged: false,
  46028. touchChanged: false,
  46029. valueChanged: false,
  46030. changed: false
  46031. };
  46032. _this._buttons = new Array(vrGamepad.buttons.length);
  46033. _this.hand = vrGamepad.hand;
  46034. return _this;
  46035. }
  46036. WebVRController.prototype.onButtonStateChange = function (callback) {
  46037. this._onButtonStateChange = callback;
  46038. };
  46039. WebVRController.prototype.update = function () {
  46040. _super.prototype.update.call(this);
  46041. for (var index = 0; index < this._buttons.length; index++) {
  46042. this._setButtonValue(this.vrGamepad.buttons[index], this._buttons[index], index);
  46043. }
  46044. ;
  46045. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  46046. this.pad.x = this.leftStick.x;
  46047. this.pad.y = this.leftStick.y;
  46048. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  46049. }
  46050. };
  46051. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  46052. if (!currentState) {
  46053. this._buttons[buttonIndex] = {
  46054. pressed: newState.pressed,
  46055. touched: newState.touched,
  46056. value: newState.value
  46057. };
  46058. return;
  46059. }
  46060. this._checkChanges(newState, currentState);
  46061. if (this._changes.changed) {
  46062. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  46063. this.handleButtonChange(buttonIndex, newState, this._changes);
  46064. }
  46065. this._buttons[buttonIndex].pressed = newState.pressed;
  46066. this._buttons[buttonIndex].touched = newState.touched;
  46067. // oculus triggers are never 0, thou not touched.
  46068. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  46069. };
  46070. WebVRController.prototype._checkChanges = function (newState, currentState) {
  46071. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  46072. this._changes.touchChanged = newState.touched !== currentState.touched;
  46073. this._changes.valueChanged = newState.value !== currentState.value;
  46074. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  46075. return this._changes;
  46076. };
  46077. return WebVRController;
  46078. }(PoseEnabledController));
  46079. BABYLON.WebVRController = WebVRController;
  46080. var OculusTouchController = (function (_super) {
  46081. __extends(OculusTouchController, _super);
  46082. function OculusTouchController(vrGamepad) {
  46083. var _this = _super.call(this, vrGamepad) || this;
  46084. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  46085. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  46086. _this.controllerType = PoseEnabledControllerType.OCULUS;
  46087. return _this;
  46088. }
  46089. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  46090. var _this = this;
  46091. var meshName = this.hand === 'right' ? 'RightTouch.babylon' : 'LeftTouch.babylon';
  46092. BABYLON.SceneLoader.ImportMesh("", "http://yoda.blob.core.windows.net/models/", meshName, scene, function (newMeshes) {
  46093. /*
  46094. Parent Mesh name: oculus_touch_left
  46095. - body
  46096. - trigger
  46097. - thumbstick
  46098. - grip
  46099. - button_y
  46100. - button_x
  46101. - button_enter
  46102. */
  46103. _this._defaultModel = newMeshes[1];
  46104. if (meshLoaded) {
  46105. meshLoaded(_this._defaultModel);
  46106. }
  46107. _this.attachToMesh(_this._defaultModel);
  46108. });
  46109. };
  46110. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  46111. // helper getters for left and right hand.
  46112. get: function () {
  46113. if (this.hand === 'right') {
  46114. return this.onMainButtonStateChangedObservable;
  46115. }
  46116. else {
  46117. throw new Error('No A button on left hand');
  46118. }
  46119. },
  46120. enumerable: true,
  46121. configurable: true
  46122. });
  46123. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  46124. get: function () {
  46125. if (this.hand === 'right') {
  46126. return this.onSecondaryButtonStateChangedObservable;
  46127. }
  46128. else {
  46129. throw new Error('No B button on left hand');
  46130. }
  46131. },
  46132. enumerable: true,
  46133. configurable: true
  46134. });
  46135. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  46136. get: function () {
  46137. if (this.hand === 'left') {
  46138. return this.onMainButtonStateChangedObservable;
  46139. }
  46140. else {
  46141. throw new Error('No X button on right hand');
  46142. }
  46143. },
  46144. enumerable: true,
  46145. configurable: true
  46146. });
  46147. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  46148. get: function () {
  46149. if (this.hand === 'left') {
  46150. return this.onSecondaryButtonStateChangedObservable;
  46151. }
  46152. else {
  46153. throw new Error('No Y button on right hand');
  46154. }
  46155. },
  46156. enumerable: true,
  46157. configurable: true
  46158. });
  46159. /*
  46160. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  46161. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  46162. 2) secondary trigger (same)
  46163. 3) A (right) X (left), touch, pressed = value
  46164. 4) B / Y
  46165. 5) thumb rest
  46166. */
  46167. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  46168. var notifyObject = state; //{ state: state, changes: changes };
  46169. var triggerDirection = this.hand === 'right' ? -1 : 1;
  46170. switch (buttonIdx) {
  46171. case 0:
  46172. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  46173. return;
  46174. case 1:
  46175. if (this._defaultModel) {
  46176. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  46177. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  46178. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  46179. }
  46180. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  46181. return;
  46182. case 2:
  46183. if (this._defaultModel) {
  46184. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  46185. }
  46186. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  46187. return;
  46188. case 3:
  46189. if (this._defaultModel) {
  46190. if (notifyObject.pressed) {
  46191. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  46192. }
  46193. else {
  46194. (this._defaultModel.getChildren()[1]).position.y = 0;
  46195. }
  46196. }
  46197. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  46198. return;
  46199. case 4:
  46200. if (this._defaultModel) {
  46201. if (notifyObject.pressed) {
  46202. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  46203. }
  46204. else {
  46205. (this._defaultModel.getChildren()[2]).position.y = 0;
  46206. }
  46207. }
  46208. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  46209. return;
  46210. case 5:
  46211. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  46212. return;
  46213. }
  46214. };
  46215. return OculusTouchController;
  46216. }(WebVRController));
  46217. BABYLON.OculusTouchController = OculusTouchController;
  46218. var ViveController = (function (_super) {
  46219. __extends(ViveController, _super);
  46220. function ViveController(vrGamepad) {
  46221. var _this = _super.call(this, vrGamepad) || this;
  46222. _this.controllerType = PoseEnabledControllerType.VIVE;
  46223. return _this;
  46224. }
  46225. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  46226. var _this = this;
  46227. BABYLON.SceneLoader.ImportMesh("", "http://yoda.blob.core.windows.net/models/", "ViveWand.babylon", scene, function (newMeshes) {
  46228. /*
  46229. Parent Mesh name: ViveWand
  46230. - body
  46231. - r_gripper
  46232. - l_gripper
  46233. - menu_button
  46234. - system_button
  46235. - trackpad
  46236. - trigger
  46237. - LED
  46238. */
  46239. _this._defaultModel = newMeshes[1];
  46240. if (meshLoaded) {
  46241. meshLoaded(_this._defaultModel);
  46242. }
  46243. _this.attachToMesh(_this._defaultModel);
  46244. });
  46245. };
  46246. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  46247. get: function () {
  46248. return this.onMainButtonStateChangedObservable;
  46249. },
  46250. enumerable: true,
  46251. configurable: true
  46252. });
  46253. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  46254. get: function () {
  46255. return this.onMainButtonStateChangedObservable;
  46256. },
  46257. enumerable: true,
  46258. configurable: true
  46259. });
  46260. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  46261. get: function () {
  46262. return this.onSecondaryButtonStateChangedObservable;
  46263. },
  46264. enumerable: true,
  46265. configurable: true
  46266. });
  46267. /**
  46268. * Vive mapping:
  46269. * 0: touchpad
  46270. * 1: trigger
  46271. * 2: left AND right buttons
  46272. * 3: menu button
  46273. */
  46274. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  46275. var notifyObject = state; //{ state: state, changes: changes };
  46276. switch (buttonIdx) {
  46277. case 0:
  46278. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  46279. return;
  46280. case 1:
  46281. if (this._defaultModel) {
  46282. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  46283. }
  46284. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  46285. return;
  46286. case 2:
  46287. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  46288. return;
  46289. case 3:
  46290. if (this._defaultModel) {
  46291. if (notifyObject.pressed) {
  46292. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  46293. }
  46294. else {
  46295. (this._defaultModel.getChildren()[2]).position.y = 0;
  46296. }
  46297. }
  46298. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  46299. return;
  46300. }
  46301. };
  46302. return ViveController;
  46303. }(WebVRController));
  46304. BABYLON.ViveController = ViveController;
  46305. })(BABYLON || (BABYLON = {}));
  46306. //# sourceMappingURL=babylon.extendedGamepad.js.map
  46307. /// <reference path="babylon.targetCamera.ts" />
  46308. var BABYLON;
  46309. (function (BABYLON) {
  46310. var FollowCamera = (function (_super) {
  46311. __extends(FollowCamera, _super);
  46312. function FollowCamera(name, position, scene, lockedTarget) {
  46313. var _this = _super.call(this, name, position, scene) || this;
  46314. _this.radius = 12;
  46315. _this.rotationOffset = 0;
  46316. _this.heightOffset = 4;
  46317. _this.cameraAcceleration = 0.05;
  46318. _this.maxCameraSpeed = 20;
  46319. _this.lockedTarget = lockedTarget;
  46320. return _this;
  46321. }
  46322. FollowCamera.prototype.getRadians = function (degrees) {
  46323. return degrees * Math.PI / 180;
  46324. };
  46325. FollowCamera.prototype.follow = function (cameraTarget) {
  46326. if (!cameraTarget)
  46327. return;
  46328. var yRotation;
  46329. if (cameraTarget.rotationQuaternion) {
  46330. var rotMatrix = new BABYLON.Matrix();
  46331. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  46332. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  46333. }
  46334. else {
  46335. yRotation = cameraTarget.rotation.y;
  46336. }
  46337. var radians = this.getRadians(this.rotationOffset) + yRotation;
  46338. var targetPosition = cameraTarget.getAbsolutePosition();
  46339. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  46340. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  46341. var dx = targetX - this.position.x;
  46342. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  46343. var dz = (targetZ) - this.position.z;
  46344. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  46345. var vy = dy * this.cameraAcceleration;
  46346. var vz = dz * this.cameraAcceleration * 2;
  46347. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  46348. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  46349. }
  46350. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  46351. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  46352. }
  46353. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  46354. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  46355. }
  46356. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  46357. this.setTarget(targetPosition);
  46358. };
  46359. FollowCamera.prototype._checkInputs = function () {
  46360. _super.prototype._checkInputs.call(this);
  46361. this.follow(this.lockedTarget);
  46362. };
  46363. FollowCamera.prototype.getClassName = function () {
  46364. return "FollowCamera";
  46365. };
  46366. return FollowCamera;
  46367. }(BABYLON.TargetCamera));
  46368. __decorate([
  46369. BABYLON.serialize()
  46370. ], FollowCamera.prototype, "radius", void 0);
  46371. __decorate([
  46372. BABYLON.serialize()
  46373. ], FollowCamera.prototype, "rotationOffset", void 0);
  46374. __decorate([
  46375. BABYLON.serialize()
  46376. ], FollowCamera.prototype, "heightOffset", void 0);
  46377. __decorate([
  46378. BABYLON.serialize()
  46379. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  46380. __decorate([
  46381. BABYLON.serialize()
  46382. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  46383. __decorate([
  46384. BABYLON.serializeAsMeshReference("lockedTargetId")
  46385. ], FollowCamera.prototype, "lockedTarget", void 0);
  46386. BABYLON.FollowCamera = FollowCamera;
  46387. var ArcFollowCamera = (function (_super) {
  46388. __extends(ArcFollowCamera, _super);
  46389. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  46390. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  46391. _this.alpha = alpha;
  46392. _this.beta = beta;
  46393. _this.radius = radius;
  46394. _this.target = target;
  46395. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  46396. _this.follow();
  46397. return _this;
  46398. }
  46399. ArcFollowCamera.prototype.follow = function () {
  46400. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  46401. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  46402. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  46403. var targetPosition = this.target.getAbsolutePosition();
  46404. this.position = targetPosition.add(this._cartesianCoordinates);
  46405. this.setTarget(targetPosition);
  46406. };
  46407. ArcFollowCamera.prototype._checkInputs = function () {
  46408. _super.prototype._checkInputs.call(this);
  46409. this.follow();
  46410. };
  46411. ArcFollowCamera.prototype.getClassName = function () {
  46412. return "ArcFollowCamera";
  46413. };
  46414. return ArcFollowCamera;
  46415. }(BABYLON.TargetCamera));
  46416. BABYLON.ArcFollowCamera = ArcFollowCamera;
  46417. })(BABYLON || (BABYLON = {}));
  46418. //# sourceMappingURL=babylon.followCamera.js.map
  46419. /// <reference path="babylon.touchCamera.ts" />
  46420. var BABYLON;
  46421. (function (BABYLON) {
  46422. // We're mainly based on the logic defined into the FreeCamera code
  46423. var UniversalCamera = (function (_super) {
  46424. __extends(UniversalCamera, _super);
  46425. //-- end properties for backward compatibility for inputs
  46426. function UniversalCamera(name, position, scene) {
  46427. var _this = _super.call(this, name, position, scene) || this;
  46428. _this.inputs.addGamepad();
  46429. return _this;
  46430. }
  46431. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  46432. //-- Begin properties for backward compatibility for inputs
  46433. get: function () {
  46434. var gamepad = this.inputs.attached["gamepad"];
  46435. if (gamepad)
  46436. return gamepad.gamepadAngularSensibility;
  46437. },
  46438. set: function (value) {
  46439. var gamepad = this.inputs.attached["gamepad"];
  46440. if (gamepad)
  46441. gamepad.gamepadAngularSensibility = value;
  46442. },
  46443. enumerable: true,
  46444. configurable: true
  46445. });
  46446. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  46447. get: function () {
  46448. var gamepad = this.inputs.attached["gamepad"];
  46449. if (gamepad)
  46450. return gamepad.gamepadMoveSensibility;
  46451. },
  46452. set: function (value) {
  46453. var gamepad = this.inputs.attached["gamepad"];
  46454. if (gamepad)
  46455. gamepad.gamepadMoveSensibility = value;
  46456. },
  46457. enumerable: true,
  46458. configurable: true
  46459. });
  46460. UniversalCamera.prototype.getClassName = function () {
  46461. return "UniversalCamera";
  46462. };
  46463. return UniversalCamera;
  46464. }(BABYLON.TouchCamera));
  46465. BABYLON.UniversalCamera = UniversalCamera;
  46466. })(BABYLON || (BABYLON = {}));
  46467. //# sourceMappingURL=babylon.universalCamera.js.map
  46468. /// <reference path="babylon.universalCamera.ts" />
  46469. var BABYLON;
  46470. (function (BABYLON) {
  46471. // We're mainly based on the logic defined into the FreeCamera code
  46472. var GamepadCamera = (function (_super) {
  46473. __extends(GamepadCamera, _super);
  46474. //-- end properties for backward compatibility for inputs
  46475. function GamepadCamera(name, position, scene) {
  46476. return _super.call(this, name, position, scene) || this;
  46477. }
  46478. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  46479. //-- Begin properties for backward compatibility for inputs
  46480. get: function () {
  46481. var gamepad = this.inputs.attached["gamepad"];
  46482. if (gamepad)
  46483. return gamepad.gamepadAngularSensibility;
  46484. },
  46485. set: function (value) {
  46486. var gamepad = this.inputs.attached["gamepad"];
  46487. if (gamepad)
  46488. gamepad.gamepadAngularSensibility = value;
  46489. },
  46490. enumerable: true,
  46491. configurable: true
  46492. });
  46493. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  46494. get: function () {
  46495. var gamepad = this.inputs.attached["gamepad"];
  46496. if (gamepad)
  46497. return gamepad.gamepadMoveSensibility;
  46498. },
  46499. set: function (value) {
  46500. var gamepad = this.inputs.attached["gamepad"];
  46501. if (gamepad)
  46502. gamepad.gamepadMoveSensibility = value;
  46503. },
  46504. enumerable: true,
  46505. configurable: true
  46506. });
  46507. GamepadCamera.prototype.getClassName = function () {
  46508. return "GamepadCamera";
  46509. };
  46510. return GamepadCamera;
  46511. }(BABYLON.UniversalCamera));
  46512. BABYLON.GamepadCamera = GamepadCamera;
  46513. })(BABYLON || (BABYLON = {}));
  46514. //# sourceMappingURL=babylon.gamepadCamera.js.map
  46515. var BABYLON;
  46516. (function (BABYLON) {
  46517. var PostProcessRenderPipelineManager = (function () {
  46518. function PostProcessRenderPipelineManager() {
  46519. this._renderPipelines = {};
  46520. }
  46521. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  46522. this._renderPipelines[renderPipeline._name] = renderPipeline;
  46523. };
  46524. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  46525. var renderPipeline = this._renderPipelines[renderPipelineName];
  46526. if (!renderPipeline) {
  46527. return;
  46528. }
  46529. renderPipeline._attachCameras(cameras, unique);
  46530. };
  46531. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  46532. var renderPipeline = this._renderPipelines[renderPipelineName];
  46533. if (!renderPipeline) {
  46534. return;
  46535. }
  46536. renderPipeline._detachCameras(cameras);
  46537. };
  46538. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  46539. var renderPipeline = this._renderPipelines[renderPipelineName];
  46540. if (!renderPipeline) {
  46541. return;
  46542. }
  46543. renderPipeline._enableEffect(renderEffectName, cameras);
  46544. };
  46545. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  46546. var renderPipeline = this._renderPipelines[renderPipelineName];
  46547. if (!renderPipeline) {
  46548. return;
  46549. }
  46550. renderPipeline._disableEffect(renderEffectName, cameras);
  46551. };
  46552. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  46553. var renderPipeline = this._renderPipelines[renderPipelineName];
  46554. if (!renderPipeline) {
  46555. return;
  46556. }
  46557. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  46558. };
  46559. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  46560. var renderPipeline = this._renderPipelines[renderPipelineName];
  46561. if (!renderPipeline) {
  46562. return;
  46563. }
  46564. renderPipeline._disableDisplayOnlyPass(cameras);
  46565. };
  46566. PostProcessRenderPipelineManager.prototype.update = function () {
  46567. for (var renderPipelineName in this._renderPipelines) {
  46568. var pipeline = this._renderPipelines[renderPipelineName];
  46569. if (!pipeline.isSupported) {
  46570. pipeline.dispose();
  46571. delete this._renderPipelines[renderPipelineName];
  46572. }
  46573. else {
  46574. pipeline._update();
  46575. }
  46576. }
  46577. };
  46578. return PostProcessRenderPipelineManager;
  46579. }());
  46580. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  46581. })(BABYLON || (BABYLON = {}));
  46582. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  46583. var BABYLON;
  46584. (function (BABYLON) {
  46585. var PostProcessRenderPass = (function () {
  46586. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  46587. this._enabled = true;
  46588. this._refCount = 0;
  46589. this._name = name;
  46590. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  46591. this.setRenderList(renderList);
  46592. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  46593. this._renderTexture.onAfterRenderObservable.add(afterRender);
  46594. this._scene = scene;
  46595. this._renderList = renderList;
  46596. }
  46597. // private
  46598. PostProcessRenderPass.prototype._incRefCount = function () {
  46599. if (this._refCount === 0) {
  46600. this._scene.customRenderTargets.push(this._renderTexture);
  46601. }
  46602. return ++this._refCount;
  46603. };
  46604. PostProcessRenderPass.prototype._decRefCount = function () {
  46605. this._refCount--;
  46606. if (this._refCount <= 0) {
  46607. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  46608. }
  46609. return this._refCount;
  46610. };
  46611. PostProcessRenderPass.prototype._update = function () {
  46612. this.setRenderList(this._renderList);
  46613. };
  46614. // public
  46615. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  46616. this._renderTexture.renderList = renderList;
  46617. };
  46618. PostProcessRenderPass.prototype.getRenderTexture = function () {
  46619. return this._renderTexture;
  46620. };
  46621. return PostProcessRenderPass;
  46622. }());
  46623. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  46624. })(BABYLON || (BABYLON = {}));
  46625. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  46626. var BABYLON;
  46627. (function (BABYLON) {
  46628. var PostProcessRenderEffect = (function () {
  46629. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  46630. this._engine = engine;
  46631. this._name = name;
  46632. this._singleInstance = singleInstance || true;
  46633. this._getPostProcess = getPostProcess;
  46634. this._cameras = [];
  46635. this._indicesForCamera = [];
  46636. this._postProcesses = {};
  46637. this._renderPasses = {};
  46638. this._renderEffectAsPasses = {};
  46639. }
  46640. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  46641. get: function () {
  46642. for (var index in this._postProcesses) {
  46643. if (!this._postProcesses[index].isSupported) {
  46644. return false;
  46645. }
  46646. }
  46647. return true;
  46648. },
  46649. enumerable: true,
  46650. configurable: true
  46651. });
  46652. PostProcessRenderEffect.prototype._update = function () {
  46653. for (var renderPassName in this._renderPasses) {
  46654. this._renderPasses[renderPassName]._update();
  46655. }
  46656. };
  46657. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  46658. this._renderPasses[renderPass._name] = renderPass;
  46659. this._linkParameters();
  46660. };
  46661. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  46662. delete this._renderPasses[renderPass._name];
  46663. this._linkParameters();
  46664. };
  46665. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  46666. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  46667. this._linkParameters();
  46668. };
  46669. PostProcessRenderEffect.prototype.getPass = function (passName) {
  46670. for (var renderPassName in this._renderPasses) {
  46671. if (renderPassName === passName) {
  46672. return this._renderPasses[passName];
  46673. }
  46674. }
  46675. };
  46676. PostProcessRenderEffect.prototype.emptyPasses = function () {
  46677. this._renderPasses = {};
  46678. this._linkParameters();
  46679. };
  46680. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  46681. var cameraKey;
  46682. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  46683. for (var i = 0; i < _cam.length; i++) {
  46684. var camera = _cam[i];
  46685. var cameraName = camera.name;
  46686. if (this._singleInstance) {
  46687. cameraKey = 0;
  46688. }
  46689. else {
  46690. cameraKey = cameraName;
  46691. }
  46692. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  46693. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  46694. if (!this._indicesForCamera[cameraName]) {
  46695. this._indicesForCamera[cameraName] = [];
  46696. }
  46697. this._indicesForCamera[cameraName].push(index);
  46698. if (this._cameras.indexOf(camera) === -1) {
  46699. this._cameras[cameraName] = camera;
  46700. }
  46701. for (var passName in this._renderPasses) {
  46702. this._renderPasses[passName]._incRefCount();
  46703. }
  46704. }
  46705. this._linkParameters();
  46706. };
  46707. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  46708. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  46709. for (var i = 0; i < _cam.length; i++) {
  46710. var camera = _cam[i];
  46711. var cameraName = camera.name;
  46712. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  46713. var index = this._cameras.indexOf(cameraName);
  46714. this._indicesForCamera.splice(index, 1);
  46715. this._cameras.splice(index, 1);
  46716. for (var passName in this._renderPasses) {
  46717. this._renderPasses[passName]._decRefCount();
  46718. }
  46719. }
  46720. };
  46721. PostProcessRenderEffect.prototype._enable = function (cameras) {
  46722. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  46723. for (var i = 0; i < _cam.length; i++) {
  46724. var camera = _cam[i];
  46725. var cameraName = camera.name;
  46726. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  46727. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  46728. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  46729. }
  46730. }
  46731. for (var passName in this._renderPasses) {
  46732. this._renderPasses[passName]._incRefCount();
  46733. }
  46734. }
  46735. };
  46736. PostProcessRenderEffect.prototype._disable = function (cameras) {
  46737. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  46738. for (var i = 0; i < _cam.length; i++) {
  46739. var camera = _cam[i];
  46740. var cameraName = camera.Name;
  46741. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  46742. for (var passName in this._renderPasses) {
  46743. this._renderPasses[passName]._decRefCount();
  46744. }
  46745. }
  46746. };
  46747. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  46748. if (this._singleInstance) {
  46749. return this._postProcesses[0];
  46750. }
  46751. else {
  46752. return this._postProcesses[camera.name];
  46753. }
  46754. };
  46755. PostProcessRenderEffect.prototype._linkParameters = function () {
  46756. var _this = this;
  46757. for (var index in this._postProcesses) {
  46758. if (this.applyParameters) {
  46759. this.applyParameters(this._postProcesses[index]);
  46760. }
  46761. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  46762. _this._linkTextures(effect);
  46763. });
  46764. }
  46765. };
  46766. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  46767. for (var renderPassName in this._renderPasses) {
  46768. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  46769. }
  46770. for (var renderEffectName in this._renderEffectAsPasses) {
  46771. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  46772. }
  46773. };
  46774. return PostProcessRenderEffect;
  46775. }());
  46776. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  46777. })(BABYLON || (BABYLON = {}));
  46778. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  46779. var BABYLON;
  46780. (function (BABYLON) {
  46781. var PostProcessRenderPipeline = (function () {
  46782. function PostProcessRenderPipeline(engine, name) {
  46783. this._engine = engine;
  46784. this._name = name;
  46785. this._renderEffects = {};
  46786. this._renderEffectsForIsolatedPass = {};
  46787. this._cameras = [];
  46788. }
  46789. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  46790. get: function () {
  46791. for (var renderEffectName in this._renderEffects) {
  46792. if (!this._renderEffects[renderEffectName].isSupported) {
  46793. return false;
  46794. }
  46795. }
  46796. return true;
  46797. },
  46798. enumerable: true,
  46799. configurable: true
  46800. });
  46801. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  46802. this._renderEffects[renderEffect._name] = renderEffect;
  46803. };
  46804. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  46805. var renderEffects = this._renderEffects[renderEffectName];
  46806. if (!renderEffects) {
  46807. return;
  46808. }
  46809. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  46810. };
  46811. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  46812. var renderEffects = this._renderEffects[renderEffectName];
  46813. if (!renderEffects) {
  46814. return;
  46815. }
  46816. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  46817. };
  46818. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  46819. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  46820. var indicesToDelete = [];
  46821. var i;
  46822. for (i = 0; i < _cam.length; i++) {
  46823. var camera = _cam[i];
  46824. var cameraName = camera.name;
  46825. if (this._cameras.indexOf(camera) === -1) {
  46826. this._cameras[cameraName] = camera;
  46827. }
  46828. else if (unique) {
  46829. indicesToDelete.push(i);
  46830. }
  46831. }
  46832. for (i = 0; i < indicesToDelete.length; i++) {
  46833. cameras.splice(indicesToDelete[i], 1);
  46834. }
  46835. for (var renderEffectName in this._renderEffects) {
  46836. this._renderEffects[renderEffectName]._attachCameras(_cam);
  46837. }
  46838. };
  46839. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  46840. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  46841. for (var renderEffectName in this._renderEffects) {
  46842. this._renderEffects[renderEffectName]._detachCameras(_cam);
  46843. }
  46844. for (var i = 0; i < _cam.length; i++) {
  46845. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  46846. }
  46847. };
  46848. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  46849. var _this = this;
  46850. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  46851. var pass = null;
  46852. var renderEffectName;
  46853. for (renderEffectName in this._renderEffects) {
  46854. pass = this._renderEffects[renderEffectName].getPass(passName);
  46855. if (pass != null) {
  46856. break;
  46857. }
  46858. }
  46859. if (pass === null) {
  46860. return;
  46861. }
  46862. for (renderEffectName in this._renderEffects) {
  46863. this._renderEffects[renderEffectName]._disable(_cam);
  46864. }
  46865. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  46866. for (var i = 0; i < _cam.length; i++) {
  46867. var camera = _cam[i];
  46868. var cameraName = camera.name;
  46869. 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); });
  46870. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  46871. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  46872. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  46873. }
  46874. };
  46875. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  46876. var _this = this;
  46877. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  46878. for (var i = 0; i < _cam.length; i++) {
  46879. var camera = _cam[i];
  46880. var cameraName = camera.name;
  46881. 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); });
  46882. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  46883. }
  46884. for (var renderEffectName in this._renderEffects) {
  46885. this._renderEffects[renderEffectName]._enable(_cam);
  46886. }
  46887. };
  46888. PostProcessRenderPipeline.prototype._update = function () {
  46889. for (var renderEffectName in this._renderEffects) {
  46890. this._renderEffects[renderEffectName]._update();
  46891. }
  46892. for (var i = 0; i < this._cameras.length; i++) {
  46893. var cameraName = this._cameras[i].name;
  46894. if (this._renderEffectsForIsolatedPass[cameraName]) {
  46895. this._renderEffectsForIsolatedPass[cameraName]._update();
  46896. }
  46897. }
  46898. };
  46899. PostProcessRenderPipeline.prototype.dispose = function () {
  46900. // Must be implemented by children
  46901. };
  46902. return PostProcessRenderPipeline;
  46903. }());
  46904. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  46905. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  46906. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  46907. })(BABYLON || (BABYLON = {}));
  46908. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  46909. var BABYLON;
  46910. (function (BABYLON) {
  46911. var DepthRenderer = (function () {
  46912. function DepthRenderer(scene, type) {
  46913. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  46914. var _this = this;
  46915. this._viewMatrix = BABYLON.Matrix.Zero();
  46916. this._projectionMatrix = BABYLON.Matrix.Zero();
  46917. this._transformMatrix = BABYLON.Matrix.Zero();
  46918. this._worldViewProjection = BABYLON.Matrix.Zero();
  46919. this._scene = scene;
  46920. var engine = scene.getEngine();
  46921. // Render target
  46922. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  46923. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46924. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46925. this._depthMap.refreshRate = 1;
  46926. this._depthMap.renderParticles = false;
  46927. this._depthMap.renderList = null;
  46928. // set default depth value to 1.0 (far away)
  46929. this._depthMap.onClearObservable.add(function (engine) {
  46930. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  46931. });
  46932. // Custom render function
  46933. var renderSubMesh = function (subMesh) {
  46934. var mesh = subMesh.getRenderingMesh();
  46935. var scene = _this._scene;
  46936. var engine = scene.getEngine();
  46937. // Culling
  46938. engine.setState(subMesh.getMaterial().backFaceCulling);
  46939. // Managing instances
  46940. var batch = mesh._getInstancesRenderList(subMesh._id);
  46941. if (batch.mustReturn) {
  46942. return;
  46943. }
  46944. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  46945. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  46946. engine.enableEffect(_this._effect);
  46947. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  46948. var material = subMesh.getMaterial();
  46949. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  46950. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  46951. // Alpha test
  46952. if (material && material.needAlphaTesting()) {
  46953. var alphaTexture = material.getAlphaTestTexture();
  46954. _this._effect.setTexture("diffuseSampler", alphaTexture);
  46955. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  46956. }
  46957. // Bones
  46958. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  46959. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  46960. }
  46961. // Draw
  46962. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  46963. }
  46964. };
  46965. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  46966. var index;
  46967. for (index = 0; index < opaqueSubMeshes.length; index++) {
  46968. renderSubMesh(opaqueSubMeshes.data[index]);
  46969. }
  46970. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  46971. renderSubMesh(alphaTestSubMeshes.data[index]);
  46972. }
  46973. };
  46974. }
  46975. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  46976. var material = subMesh.getMaterial();
  46977. if (material.disableDepthWrite) {
  46978. return false;
  46979. }
  46980. var defines = [];
  46981. var attribs = [BABYLON.VertexBuffer.PositionKind];
  46982. var mesh = subMesh.getMesh();
  46983. var scene = mesh.getScene();
  46984. // Alpha test
  46985. if (material && material.needAlphaTesting()) {
  46986. defines.push("#define ALPHATEST");
  46987. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  46988. attribs.push(BABYLON.VertexBuffer.UVKind);
  46989. defines.push("#define UV1");
  46990. }
  46991. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  46992. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  46993. defines.push("#define UV2");
  46994. }
  46995. }
  46996. // Bones
  46997. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  46998. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  46999. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  47000. if (mesh.numBoneInfluencers > 4) {
  47001. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  47002. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  47003. }
  47004. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  47005. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  47006. }
  47007. else {
  47008. defines.push("#define NUM_BONE_INFLUENCERS 0");
  47009. }
  47010. // Instances
  47011. if (useInstances) {
  47012. defines.push("#define INSTANCES");
  47013. attribs.push("world0");
  47014. attribs.push("world1");
  47015. attribs.push("world2");
  47016. attribs.push("world3");
  47017. }
  47018. // Get correct effect
  47019. var join = defines.join("\n");
  47020. if (this._cachedDefines !== join) {
  47021. this._cachedDefines = join;
  47022. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  47023. }
  47024. return this._effect.isReady();
  47025. };
  47026. DepthRenderer.prototype.getDepthMap = function () {
  47027. return this._depthMap;
  47028. };
  47029. // Methods
  47030. DepthRenderer.prototype.dispose = function () {
  47031. this._depthMap.dispose();
  47032. };
  47033. return DepthRenderer;
  47034. }());
  47035. BABYLON.DepthRenderer = DepthRenderer;
  47036. })(BABYLON || (BABYLON = {}));
  47037. //# sourceMappingURL=babylon.depthRenderer.js.map
  47038. var BABYLON;
  47039. (function (BABYLON) {
  47040. var SSAORenderingPipeline = (function (_super) {
  47041. __extends(SSAORenderingPipeline, _super);
  47042. /**
  47043. * @constructor
  47044. * @param {string} name - The rendering pipeline name
  47045. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  47046. * @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 }
  47047. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  47048. */
  47049. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  47050. var _this = _super.call(this, scene.getEngine(), name) || this;
  47051. // Members
  47052. /**
  47053. * The PassPostProcess id in the pipeline that contains the original scene color
  47054. * @type {string}
  47055. */
  47056. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  47057. /**
  47058. * The SSAO PostProcess id in the pipeline
  47059. * @type {string}
  47060. */
  47061. _this.SSAORenderEffect = "SSAORenderEffect";
  47062. /**
  47063. * The horizontal blur PostProcess id in the pipeline
  47064. * @type {string}
  47065. */
  47066. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  47067. /**
  47068. * The vertical blur PostProcess id in the pipeline
  47069. * @type {string}
  47070. */
  47071. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  47072. /**
  47073. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  47074. * @type {string}
  47075. */
  47076. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  47077. /**
  47078. * The output strength of the SSAO post-process. Default value is 1.0.
  47079. * @type {number}
  47080. */
  47081. _this.totalStrength = 1.0;
  47082. /**
  47083. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  47084. * @type {number}
  47085. */
  47086. _this.radius = 0.0001;
  47087. /**
  47088. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  47089. * Must not be equal to fallOff and superior to fallOff.
  47090. * Default value is 0.975
  47091. * @type {number}
  47092. */
  47093. _this.area = 0.0075;
  47094. /**
  47095. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  47096. * Must not be equal to area and inferior to area.
  47097. * Default value is 0.0
  47098. * @type {number}
  47099. */
  47100. _this.fallOff = 0.000001;
  47101. /**
  47102. * The base color of the SSAO post-process
  47103. * The final result is "base + ssao" between [0, 1]
  47104. * @type {number}
  47105. */
  47106. _this.base = 0.5;
  47107. _this._firstUpdate = true;
  47108. _this._scene = scene;
  47109. // Set up assets
  47110. _this._createRandomTexture();
  47111. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  47112. var ssaoRatio = ratio.ssaoRatio || ratio;
  47113. var combineRatio = ratio.combineRatio || ratio;
  47114. _this._ratio = {
  47115. ssaoRatio: ssaoRatio,
  47116. combineRatio: combineRatio
  47117. };
  47118. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  47119. _this._createSSAOPostProcess(ssaoRatio);
  47120. _this._createBlurPostProcess(ssaoRatio);
  47121. _this._createSSAOCombinePostProcess(combineRatio);
  47122. // Set up pipeline
  47123. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  47124. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  47125. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  47126. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  47127. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  47128. // Finish
  47129. scene.postProcessRenderPipelineManager.addPipeline(_this);
  47130. if (cameras)
  47131. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  47132. return _this;
  47133. }
  47134. // Public Methods
  47135. /**
  47136. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  47137. */
  47138. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  47139. if (disableDepthRender === void 0) { disableDepthRender = false; }
  47140. for (var i = 0; i < this._scene.cameras.length; i++) {
  47141. var camera = this._scene.cameras[i];
  47142. this._originalColorPostProcess.dispose(camera);
  47143. this._ssaoPostProcess.dispose(camera);
  47144. this._blurHPostProcess.dispose(camera);
  47145. this._blurVPostProcess.dispose(camera);
  47146. this._ssaoCombinePostProcess.dispose(camera);
  47147. }
  47148. this._randomTexture.dispose();
  47149. if (disableDepthRender)
  47150. this._scene.disableDepthRenderer();
  47151. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  47152. _super.prototype.dispose.call(this);
  47153. };
  47154. // Private Methods
  47155. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  47156. var _this = this;
  47157. /*
  47158. var samplerOffsets = [
  47159. -8.0, -6.0, -4.0, -2.0,
  47160. 0.0,
  47161. 2.0, 4.0, 6.0, 8.0
  47162. ];
  47163. */
  47164. var samples = 16;
  47165. var samplerOffsets = [];
  47166. for (var i = -8; i < 8; i++) {
  47167. samplerOffsets.push(i * 2);
  47168. }
  47169. 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");
  47170. this._blurHPostProcess.onApply = function (effect) {
  47171. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  47172. effect.setTexture("depthSampler", _this._depthTexture);
  47173. if (_this._firstUpdate) {
  47174. effect.setArray("samplerOffsets", samplerOffsets);
  47175. }
  47176. };
  47177. 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");
  47178. this._blurVPostProcess.onApply = function (effect) {
  47179. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  47180. effect.setTexture("depthSampler", _this._depthTexture);
  47181. if (_this._firstUpdate) {
  47182. effect.setArray("samplerOffsets", samplerOffsets);
  47183. _this._firstUpdate = false;
  47184. }
  47185. };
  47186. };
  47187. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  47188. var _this = this;
  47189. var numSamples = 16;
  47190. var sampleSphere = [
  47191. 0.5381, 0.1856, -0.4319,
  47192. 0.1379, 0.2486, 0.4430,
  47193. 0.3371, 0.5679, -0.0057,
  47194. -0.6999, -0.0451, -0.0019,
  47195. 0.0689, -0.1598, -0.8547,
  47196. 0.0560, 0.0069, -0.1843,
  47197. -0.0146, 0.1402, 0.0762,
  47198. 0.0100, -0.1924, -0.0344,
  47199. -0.3577, -0.5301, -0.4358,
  47200. -0.3169, 0.1063, 0.0158,
  47201. 0.0103, -0.5869, 0.0046,
  47202. -0.0897, -0.4940, 0.3287,
  47203. 0.7119, -0.0154, -0.0918,
  47204. -0.0533, 0.0596, -0.5411,
  47205. 0.0352, -0.0631, 0.5460,
  47206. -0.4776, 0.2847, -0.0271
  47207. ];
  47208. var samplesFactor = 1.0 / numSamples;
  47209. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  47210. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  47211. "area", "fallOff", "base", "range", "viewport"
  47212. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  47213. var viewport = new BABYLON.Vector2(0, 0);
  47214. this._ssaoPostProcess.onApply = function (effect) {
  47215. if (_this._firstUpdate) {
  47216. effect.setArray3("sampleSphere", sampleSphere);
  47217. effect.setFloat("samplesFactor", samplesFactor);
  47218. effect.setFloat("randTextureTiles", 4.0);
  47219. }
  47220. effect.setFloat("totalStrength", _this.totalStrength);
  47221. effect.setFloat("radius", _this.radius);
  47222. effect.setFloat("area", _this.area);
  47223. effect.setFloat("fallOff", _this.fallOff);
  47224. effect.setFloat("base", _this.base);
  47225. effect.setTexture("textureSampler", _this._depthTexture);
  47226. effect.setTexture("randomSampler", _this._randomTexture);
  47227. };
  47228. };
  47229. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  47230. var _this = this;
  47231. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  47232. this._ssaoCombinePostProcess.onApply = function (effect) {
  47233. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  47234. };
  47235. };
  47236. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  47237. var size = 512;
  47238. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  47239. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  47240. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  47241. var context = this._randomTexture.getContext();
  47242. var rand = function (min, max) {
  47243. return Math.random() * (max - min) + min;
  47244. };
  47245. var randVector = BABYLON.Vector3.Zero();
  47246. for (var x = 0; x < size; x++) {
  47247. for (var y = 0; y < size; y++) {
  47248. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  47249. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  47250. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  47251. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  47252. context.fillRect(x, y, 1, 1);
  47253. }
  47254. }
  47255. this._randomTexture.update(false);
  47256. };
  47257. return SSAORenderingPipeline;
  47258. }(BABYLON.PostProcessRenderPipeline));
  47259. __decorate([
  47260. BABYLON.serialize()
  47261. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  47262. __decorate([
  47263. BABYLON.serialize()
  47264. ], SSAORenderingPipeline.prototype, "radius", void 0);
  47265. __decorate([
  47266. BABYLON.serialize()
  47267. ], SSAORenderingPipeline.prototype, "area", void 0);
  47268. __decorate([
  47269. BABYLON.serialize()
  47270. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  47271. __decorate([
  47272. BABYLON.serialize()
  47273. ], SSAORenderingPipeline.prototype, "base", void 0);
  47274. __decorate([
  47275. BABYLON.serialize()
  47276. ], SSAORenderingPipeline.prototype, "_ratio", void 0);
  47277. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  47278. })(BABYLON || (BABYLON = {}));
  47279. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  47280. // BABYLON.JS Chromatic Aberration GLSL Shader
  47281. // Author: Olivier Guyot
  47282. // Separates very slightly R, G and B colors on the edges of the screen
  47283. // Inspired by Francois Tarlier & Martins Upitis
  47284. var BABYLON;
  47285. (function (BABYLON) {
  47286. var LensRenderingPipeline = (function (_super) {
  47287. __extends(LensRenderingPipeline, _super);
  47288. /**
  47289. * @constructor
  47290. *
  47291. * Effect parameters are as follow:
  47292. * {
  47293. * chromatic_aberration: number; // from 0 to x (1 for realism)
  47294. * edge_blur: number; // from 0 to x (1 for realism)
  47295. * distortion: number; // from 0 to x (1 for realism)
  47296. * grain_amount: number; // from 0 to 1
  47297. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  47298. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  47299. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  47300. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  47301. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  47302. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  47303. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  47304. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  47305. * }
  47306. * Note: if an effect parameter is unset, effect is disabled
  47307. *
  47308. * @param {string} name - The rendering pipeline name
  47309. * @param {object} parameters - An object containing all parameters (see above)
  47310. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  47311. * @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)
  47312. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  47313. */
  47314. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  47315. if (ratio === void 0) { ratio = 1.0; }
  47316. var _this = _super.call(this, scene.getEngine(), name) || this;
  47317. // Lens effects can be of the following:
  47318. // - chromatic aberration (slight shift of RGB colors)
  47319. // - blur on the edge of the lens
  47320. // - lens distortion
  47321. // - depth-of-field blur & highlights enhancing
  47322. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  47323. // - grain effect (noise or custom texture)
  47324. // Two additional texture samplers are needed:
  47325. // - depth map (for depth-of-field)
  47326. // - grain texture
  47327. /**
  47328. * The chromatic aberration PostProcess id in the pipeline
  47329. * @type {string}
  47330. */
  47331. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  47332. /**
  47333. * The highlights enhancing PostProcess id in the pipeline
  47334. * @type {string}
  47335. */
  47336. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  47337. /**
  47338. * The depth-of-field PostProcess id in the pipeline
  47339. * @type {string}
  47340. */
  47341. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  47342. _this._scene = scene;
  47343. // Fetch texture samplers
  47344. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  47345. if (parameters.grain_texture) {
  47346. _this._grainTexture = parameters.grain_texture;
  47347. }
  47348. else {
  47349. _this._createGrainTexture();
  47350. }
  47351. // save parameters
  47352. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  47353. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  47354. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  47355. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  47356. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  47357. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  47358. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  47359. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  47360. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  47361. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  47362. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  47363. // Create effects
  47364. _this._createChromaticAberrationPostProcess(ratio);
  47365. _this._createHighlightsPostProcess(ratio);
  47366. _this._createDepthOfFieldPostProcess(ratio / 4);
  47367. // Set up pipeline
  47368. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  47369. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  47370. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  47371. if (_this._highlightsGain === -1) {
  47372. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  47373. }
  47374. // Finish
  47375. scene.postProcessRenderPipelineManager.addPipeline(_this);
  47376. if (cameras) {
  47377. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  47378. }
  47379. return _this;
  47380. }
  47381. // public methods (self explanatory)
  47382. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  47383. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  47384. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  47385. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  47386. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  47387. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  47388. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  47389. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  47390. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  47391. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  47392. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  47393. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  47394. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  47395. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  47396. };
  47397. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  47398. this._highlightsPostProcess.updateEffect();
  47399. };
  47400. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  47401. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  47402. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  47403. this._highlightsGain = amount;
  47404. };
  47405. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  47406. if (this._highlightsGain === -1) {
  47407. this._highlightsGain = 1.0;
  47408. }
  47409. this._highlightsThreshold = amount;
  47410. };
  47411. LensRenderingPipeline.prototype.disableHighlights = function () {
  47412. this._highlightsGain = -1;
  47413. };
  47414. /**
  47415. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  47416. */
  47417. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  47418. if (disableDepthRender === void 0) { disableDepthRender = false; }
  47419. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  47420. this._chromaticAberrationPostProcess = undefined;
  47421. this._highlightsPostProcess = undefined;
  47422. this._depthOfFieldPostProcess = undefined;
  47423. this._grainTexture.dispose();
  47424. if (disableDepthRender)
  47425. this._scene.disableDepthRenderer();
  47426. };
  47427. // colors shifting and distortion
  47428. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  47429. var _this = this;
  47430. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  47431. [], // samplers
  47432. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  47433. this._chromaticAberrationPostProcess.onApply = function (effect) {
  47434. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  47435. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  47436. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  47437. };
  47438. };
  47439. // highlights enhancing
  47440. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  47441. var _this = this;
  47442. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  47443. [], // samplers
  47444. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  47445. this._highlightsPostProcess.onApply = function (effect) {
  47446. effect.setFloat('gain', _this._highlightsGain);
  47447. effect.setFloat('threshold', _this._highlightsThreshold);
  47448. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  47449. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  47450. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  47451. };
  47452. };
  47453. // colors shifting and distortion
  47454. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  47455. var _this = this;
  47456. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  47457. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  47458. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  47459. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  47460. this._depthOfFieldPostProcess.onApply = function (effect) {
  47461. effect.setTexture("depthSampler", _this._depthTexture);
  47462. effect.setTexture("grainSampler", _this._grainTexture);
  47463. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  47464. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  47465. effect.setFloat('grain_amount', _this._grainAmount);
  47466. effect.setBool('blur_noise', _this._blurNoise);
  47467. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  47468. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  47469. effect.setFloat('distortion', _this._distortion);
  47470. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  47471. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  47472. effect.setFloat('aperture', _this._dofAperture);
  47473. effect.setFloat('darken', _this._dofDarken);
  47474. effect.setFloat('edge_blur', _this._edgeBlur);
  47475. effect.setBool('highlights', (_this._highlightsGain !== -1));
  47476. effect.setFloat('near', _this._scene.activeCamera.minZ);
  47477. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  47478. };
  47479. };
  47480. // creates a black and white random noise texture, 512x512
  47481. LensRenderingPipeline.prototype._createGrainTexture = function () {
  47482. var size = 512;
  47483. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  47484. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  47485. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  47486. var context = this._grainTexture.getContext();
  47487. var rand = function (min, max) {
  47488. return Math.random() * (max - min) + min;
  47489. };
  47490. var value;
  47491. for (var x = 0; x < size; x++) {
  47492. for (var y = 0; y < size; y++) {
  47493. value = Math.floor(rand(0.42, 0.58) * 255);
  47494. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  47495. context.fillRect(x, y, 1, 1);
  47496. }
  47497. }
  47498. this._grainTexture.update(false);
  47499. };
  47500. return LensRenderingPipeline;
  47501. }(BABYLON.PostProcessRenderPipeline));
  47502. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  47503. })(BABYLON || (BABYLON = {}));
  47504. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  47505. /// <reference path="RenderPipeline\babylon.postProcessRenderPipeline.ts" />
  47506. var BABYLON;
  47507. (function (BABYLON) {
  47508. var HDRRenderingPipeline = (function (_super) {
  47509. __extends(HDRRenderingPipeline, _super);
  47510. /**
  47511. * @constructor
  47512. * @param {string} name - The rendering pipeline name
  47513. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  47514. * @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)
  47515. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  47516. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  47517. */
  47518. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  47519. if (originalPostProcess === void 0) { originalPostProcess = null; }
  47520. var _this = _super.call(this, scene.getEngine(), name) || this;
  47521. /**
  47522. * Public members
  47523. */
  47524. // Gaussian Blur
  47525. /**
  47526. * Gaussian blur coefficient
  47527. * @type {number}
  47528. */
  47529. _this.gaussCoeff = 0.3;
  47530. /**
  47531. * Gaussian blur mean
  47532. * @type {number}
  47533. */
  47534. _this.gaussMean = 1.0;
  47535. /**
  47536. * Gaussian blur standard deviation
  47537. * @type {number}
  47538. */
  47539. _this.gaussStandDev = 0.8;
  47540. /**
  47541. * Gaussian blur multiplier. Multiplies the blur effect
  47542. * @type {number}
  47543. */
  47544. _this.gaussMultiplier = 4.0;
  47545. // HDR
  47546. /**
  47547. * Exposure, controls the overall intensity of the pipeline
  47548. * @type {number}
  47549. */
  47550. _this.exposure = 1.0;
  47551. /**
  47552. * Minimum luminance that the post-process can output. Luminance is >= 0
  47553. * @type {number}
  47554. */
  47555. _this.minimumLuminance = 1.0;
  47556. /**
  47557. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  47558. * @type {number}
  47559. */
  47560. _this.maximumLuminance = 1e20;
  47561. /**
  47562. * Increase rate for luminance: eye adaptation speed to dark
  47563. * @type {number}
  47564. */
  47565. _this.luminanceIncreaserate = 0.5;
  47566. /**
  47567. * Decrease rate for luminance: eye adaptation speed to bright
  47568. * @type {number}
  47569. */
  47570. _this.luminanceDecreaseRate = 0.5;
  47571. // Bright pass
  47572. /**
  47573. * Minimum luminance needed to compute HDR
  47574. * @type {number}
  47575. */
  47576. _this.brightThreshold = 0.8;
  47577. _this._needUpdate = true;
  47578. _this._scene = scene;
  47579. // Bright pass
  47580. _this._createBrightPassPostProcess(scene, ratio);
  47581. // Down sample X4
  47582. _this._createDownSampleX4PostProcess(scene, ratio);
  47583. // Create gaussian blur post-processes
  47584. _this._createGaussianBlurPostProcess(scene, ratio);
  47585. // Texture adder
  47586. _this._createTextureAdderPostProcess(scene, ratio);
  47587. // Luminance generator
  47588. _this._createLuminanceGeneratorPostProcess(scene);
  47589. // HDR
  47590. _this._createHDRPostProcess(scene, ratio);
  47591. // Pass postprocess
  47592. if (originalPostProcess === null) {
  47593. _this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  47594. }
  47595. else {
  47596. _this._originalPostProcess = originalPostProcess;
  47597. }
  47598. // Configure pipeline
  47599. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  47600. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  47601. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  47602. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  47603. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  47604. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  47605. var addDownSamplerPostProcess = function (id) {
  47606. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  47607. };
  47608. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  47609. addDownSamplerPostProcess(i);
  47610. }
  47611. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  47612. // Finish
  47613. scene.postProcessRenderPipelineManager.addPipeline(_this);
  47614. if (cameras !== null) {
  47615. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  47616. }
  47617. _this.update();
  47618. return _this;
  47619. }
  47620. /**
  47621. * Tells the pipeline to update its post-processes
  47622. */
  47623. HDRRenderingPipeline.prototype.update = function () {
  47624. this._needUpdate = true;
  47625. };
  47626. /**
  47627. * Returns the current calculated luminance
  47628. */
  47629. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  47630. return this._hdrCurrentLuminance;
  47631. };
  47632. /**
  47633. * Returns the currently drawn luminance
  47634. */
  47635. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  47636. return this._hdrOutputLuminance;
  47637. };
  47638. /**
  47639. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  47640. */
  47641. HDRRenderingPipeline.prototype.dispose = function () {
  47642. for (var i = 0; i < this._scene.cameras.length; i++) {
  47643. var camera = this._scene.cameras[i];
  47644. this._originalPostProcess.dispose(camera);
  47645. this._brightPassPostProcess.dispose(camera);
  47646. this._downSampleX4PostProcess.dispose(camera);
  47647. this._guassianBlurHPostProcess.dispose(camera);
  47648. this._guassianBlurVPostProcess.dispose(camera);
  47649. this._textureAdderPostProcess.dispose(camera);
  47650. for (var j = HDRRenderingPipeline.LUM_STEPS - 1; j >= 0; j--) {
  47651. this._downSamplePostProcesses[j].dispose(camera);
  47652. }
  47653. this._hdrPostProcess.dispose(camera);
  47654. }
  47655. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  47656. _super.prototype.dispose.call(this);
  47657. };
  47658. /**
  47659. * Creates the HDR post-process and computes the luminance adaptation
  47660. */
  47661. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  47662. var _this = this;
  47663. var hdrLastLuminance = 0.0;
  47664. this._hdrOutputLuminance = -1.0;
  47665. this._hdrCurrentLuminance = 1.0;
  47666. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  47667. this._hdrPostProcess.onApply = function (effect) {
  47668. if (_this._hdrOutputLuminance < 0.0) {
  47669. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  47670. }
  47671. else {
  47672. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  47673. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  47674. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  47675. }
  47676. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  47677. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  47678. }
  47679. else {
  47680. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  47681. }
  47682. }
  47683. _this._hdrOutputLuminance = BABYLON.MathTools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  47684. hdrLastLuminance += scene.getEngine().getDeltaTime();
  47685. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  47686. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  47687. effect.setFloat("exposure", _this.exposure);
  47688. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  47689. _this._needUpdate = false;
  47690. };
  47691. };
  47692. /**
  47693. * Texture Adder post-process
  47694. */
  47695. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  47696. var _this = this;
  47697. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  47698. this._textureAdderPostProcess.onApply = function (effect) {
  47699. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  47700. };
  47701. };
  47702. /**
  47703. * Down sample X4 post-process
  47704. */
  47705. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  47706. var _this = this;
  47707. var downSampleX4Offsets = new Array(32);
  47708. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  47709. this._downSampleX4PostProcess.onApply = function (effect) {
  47710. if (_this._needUpdate) {
  47711. var id = 0;
  47712. for (var i = -2; i < 2; i++) {
  47713. for (var j = -2; j < 2; j++) {
  47714. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  47715. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  47716. id += 2;
  47717. }
  47718. }
  47719. }
  47720. effect.setArray2("dsOffsets", downSampleX4Offsets);
  47721. };
  47722. };
  47723. /**
  47724. * Bright pass post-process
  47725. */
  47726. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  47727. var _this = this;
  47728. var brightOffsets = new Array(8);
  47729. var brightPassCallback = function (effect) {
  47730. if (_this._needUpdate) {
  47731. var sU = (1.0 / _this._brightPassPostProcess.width);
  47732. var sV = (1.0 / _this._brightPassPostProcess.height);
  47733. brightOffsets[0] = -0.5 * sU;
  47734. brightOffsets[1] = 0.5 * sV;
  47735. brightOffsets[2] = 0.5 * sU;
  47736. brightOffsets[3] = 0.5 * sV;
  47737. brightOffsets[4] = -0.5 * sU;
  47738. brightOffsets[5] = -0.5 * sV;
  47739. brightOffsets[6] = 0.5 * sU;
  47740. brightOffsets[7] = -0.5 * sV;
  47741. }
  47742. effect.setArray2("dsOffsets", brightOffsets);
  47743. effect.setFloat("brightThreshold", _this.brightThreshold);
  47744. };
  47745. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  47746. this._brightPassPostProcess.onApply = brightPassCallback;
  47747. };
  47748. /**
  47749. * Luminance generator. Creates the luminance post-process and down sample post-processes
  47750. */
  47751. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  47752. var _this = this;
  47753. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  47754. var luminanceOffsets = new Array(8);
  47755. var downSampleOffsets = new Array(18);
  47756. var halfDestPixelSize;
  47757. this._downSamplePostProcesses = new Array(lumSteps);
  47758. // Utils for luminance
  47759. var luminanceUpdateSourceOffsets = function (width, height) {
  47760. var sU = (1.0 / width);
  47761. var sV = (1.0 / height);
  47762. luminanceOffsets[0] = -0.5 * sU;
  47763. luminanceOffsets[1] = 0.5 * sV;
  47764. luminanceOffsets[2] = 0.5 * sU;
  47765. luminanceOffsets[3] = 0.5 * sV;
  47766. luminanceOffsets[4] = -0.5 * sU;
  47767. luminanceOffsets[5] = -0.5 * sV;
  47768. luminanceOffsets[6] = 0.5 * sU;
  47769. luminanceOffsets[7] = -0.5 * sV;
  47770. };
  47771. var luminanceUpdateDestOffsets = function (width, height) {
  47772. var id = 0;
  47773. for (var x = -1; x < 2; x++) {
  47774. for (var y = -1; y < 2; y++) {
  47775. downSampleOffsets[id] = (x) / width;
  47776. downSampleOffsets[id + 1] = (y) / height;
  47777. id += 2;
  47778. }
  47779. }
  47780. };
  47781. // Luminance callback
  47782. var luminanceCallback = function (effect) {
  47783. if (_this._needUpdate) {
  47784. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  47785. }
  47786. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  47787. effect.setArray2("lumOffsets", luminanceOffsets);
  47788. };
  47789. // Down sample callbacks
  47790. var downSampleCallback = function (indice) {
  47791. var i = indice;
  47792. return function (effect) {
  47793. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  47794. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  47795. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  47796. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  47797. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  47798. effect.setArray2("dsOffsets", downSampleOffsets);
  47799. };
  47800. };
  47801. var downSampleAfterRenderCallback = function (effect) {
  47802. // Unpack result
  47803. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  47804. 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);
  47805. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  47806. };
  47807. // Create luminance post-process
  47808. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  47809. 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);
  47810. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  47811. // Create down sample post-processes
  47812. for (var i = lumSteps - 2; i >= 0; i--) {
  47813. var length = Math.pow(3, i);
  47814. ratio = { width: length, height: length };
  47815. var defines = "#define DOWN_SAMPLE\n";
  47816. if (i === 0) {
  47817. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  47818. }
  47819. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  47820. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  47821. if (i === 0) {
  47822. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  47823. }
  47824. }
  47825. };
  47826. /**
  47827. * Gaussian blur post-processes. Horizontal and Vertical
  47828. */
  47829. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  47830. var _this = this;
  47831. var blurOffsetsW = new Array(9);
  47832. var blurOffsetsH = new Array(9);
  47833. var blurWeights = new Array(9);
  47834. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  47835. // Utils for gaussian blur
  47836. var calculateBlurOffsets = function (height) {
  47837. var lastOutputDimensions = {
  47838. width: scene.getEngine().getRenderWidth(),
  47839. height: scene.getEngine().getRenderHeight()
  47840. };
  47841. for (var i = 0; i < 9; i++) {
  47842. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  47843. if (height) {
  47844. blurOffsetsH[i] = value;
  47845. }
  47846. else {
  47847. blurOffsetsW[i] = value;
  47848. }
  47849. }
  47850. };
  47851. var calculateWeights = function () {
  47852. var x = 0.0;
  47853. for (var i = 0; i < 9; i++) {
  47854. x = (i - 4.0) / 4.0;
  47855. 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));
  47856. }
  47857. };
  47858. // Callback
  47859. var gaussianBlurCallback = function (height) {
  47860. return function (effect) {
  47861. if (_this._needUpdate) {
  47862. calculateWeights();
  47863. calculateBlurOffsets(height);
  47864. }
  47865. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  47866. effect.setArray("blurWeights", blurWeights);
  47867. effect.setFloat("multiplier", _this.gaussMultiplier);
  47868. };
  47869. };
  47870. // Create horizontal gaussian blur post-processes
  47871. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  47872. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  47873. // Create vertical gaussian blur post-process
  47874. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  47875. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  47876. };
  47877. return HDRRenderingPipeline;
  47878. }(BABYLON.PostProcessRenderPipeline));
  47879. // Luminance generator
  47880. HDRRenderingPipeline.LUM_STEPS = 6;
  47881. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  47882. })(BABYLON || (BABYLON = {}));
  47883. //# sourceMappingURL=babylon.hdrRenderingPipeline.js.map
  47884. /// <reference path="RenderPipeline\babylon.postProcessRenderPipeline.ts" />
  47885. var BABYLON;
  47886. (function (BABYLON) {
  47887. var StandardRenderingPipeline = (function (_super) {
  47888. __extends(StandardRenderingPipeline, _super);
  47889. /**
  47890. * @constructor
  47891. * @param {string} name - The rendering pipeline name
  47892. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  47893. * @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)
  47894. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  47895. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  47896. */
  47897. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  47898. if (originalPostProcess === void 0) { originalPostProcess = null; }
  47899. var _this = _super.call(this, scene.getEngine(), name) || this;
  47900. _this.downSampleX4PostProcess = null;
  47901. _this.brightPassPostProcess = null;
  47902. _this.gaussianBlurHPostProcesses = [];
  47903. _this.gaussianBlurVPostProcesses = [];
  47904. _this.textureAdderPostProcess = null;
  47905. _this.luminancePostProcess = null;
  47906. _this.luminanceDownSamplePostProcesses = [];
  47907. _this.hdrPostProcess = null;
  47908. _this.textureAdderFinalPostProcess = null;
  47909. _this.lensFlareFinalPostProcess = null;
  47910. _this.hdrFinalPostProcess = null;
  47911. _this.lensFlarePostProcess = null;
  47912. _this.lensFlareComposePostProcess = null;
  47913. _this.motionBlurPostProcess = null;
  47914. _this.depthOfFieldPostProcess = null;
  47915. // Values
  47916. _this.brightThreshold = 1.0;
  47917. _this.blurWidth = 2.0;
  47918. _this.horizontalBlur = false;
  47919. _this.gaussianCoefficient = 0.25;
  47920. _this.gaussianMean = 1.0;
  47921. _this.gaussianStandardDeviation = 1.0;
  47922. _this.exposure = 1.0;
  47923. _this.lensTexture = null;
  47924. _this.hdrMinimumLuminance = 1.0;
  47925. _this.hdrDecreaseRate = 0.5;
  47926. _this.hdrIncreaseRate = 0.5;
  47927. _this.lensColorTexture = null;
  47928. _this.lensFlareStrength = 20.0;
  47929. _this.lensFlareGhostDispersal = 1.4;
  47930. _this.lensFlareHaloWidth = 0.7;
  47931. _this.lensFlareDistortionStrength = 16.0;
  47932. _this.lensStarTexture = null;
  47933. _this.lensFlareDirtTexture = null;
  47934. _this.depthOfFieldDistance = 10.0;
  47935. _this.depthOfFieldBlurWidth = 2.0;
  47936. _this.motionStrength = 1.0;
  47937. // IAnimatable
  47938. _this.animations = [];
  47939. _this._depthRenderer = null;
  47940. _this._currentDepthOfFieldSource = null;
  47941. _this._currentHDRSource = null;
  47942. _this._hdrCurrentLuminance = 1.0;
  47943. _this._motionBlurSamples = 64;
  47944. // Getters and setters
  47945. _this._depthOfFieldEnabled = true;
  47946. _this._lensFlareEnabled = true;
  47947. _this._hdrEnabled = true;
  47948. _this._motionBlurEnabled = true;
  47949. _this._cameras = cameras || [];
  47950. // Initialize
  47951. _this._scene = scene;
  47952. // Misc
  47953. var floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  47954. // Create pass post-process
  47955. if (!originalPostProcess) {
  47956. _this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", floatTextureType);
  47957. }
  47958. else {
  47959. _this.originalPostProcess = originalPostProcess;
  47960. }
  47961. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  47962. // Create down sample X4 post-process
  47963. _this._createDownSampleX4PostProcess(scene, ratio / 2);
  47964. // Create bright pass post-process
  47965. _this._createBrightPassPostProcess(scene, ratio / 2);
  47966. // Create gaussian blur post-processes (down sampling blurs)
  47967. _this._createGaussianBlurPostProcesses(scene, ratio / 2, 0);
  47968. _this._createGaussianBlurPostProcesses(scene, ratio / 4, 1);
  47969. _this._createGaussianBlurPostProcesses(scene, ratio / 8, 2);
  47970. _this._createGaussianBlurPostProcesses(scene, ratio / 16, 3);
  47971. // Create texture adder post-process
  47972. _this._createTextureAdderPostProcess(scene, ratio);
  47973. // Create depth-of-field source post-process
  47974. _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);
  47975. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  47976. // Create lens flare post-process
  47977. _this._createLensFlarePostProcess(scene, ratio);
  47978. // Create depth-of-field source post-process post lens-flare and disable it now
  47979. _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);
  47980. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  47981. // Create luminance
  47982. _this._createLuminancePostProcesses(scene, floatTextureType);
  47983. // Create HDR
  47984. _this._createHdrPostProcess(scene, ratio);
  47985. // Create depth-of-field source post-process post hdr and disable it now
  47986. _this.hdrFinalPostProcess = new BABYLON.PostProcess("HDRPostHDReDepthOfFieldSource", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  47987. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  47988. // Create gaussian blur used by depth-of-field
  47989. _this._createGaussianBlurPostProcesses(scene, ratio / 2, 5, "depthOfFieldBlurWidth");
  47990. // Create depth-of-field post-process
  47991. _this._createDepthOfFieldPostProcess(scene, ratio);
  47992. // Create motion blur post-process
  47993. _this._createMotionBlurPostProcess(scene, ratio);
  47994. // Finish
  47995. scene.postProcessRenderPipelineManager.addPipeline(_this);
  47996. if (cameras !== null) {
  47997. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  47998. }
  47999. // Deactivate
  48000. _this.LensFlareEnabled = false;
  48001. _this.DepthOfFieldEnabled = false;
  48002. _this.HDREnabled = false;
  48003. _this.MotionBlurEnabled = false;
  48004. return _this;
  48005. }
  48006. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  48007. get: function () {
  48008. return this._depthOfFieldEnabled;
  48009. },
  48010. set: function (enabled) {
  48011. var blurIndex = this.gaussianBlurHPostProcesses.length - 1;
  48012. if (enabled && !this._depthOfFieldEnabled) {
  48013. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  48014. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  48015. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRDepthOfField", this._scene.cameras);
  48016. this._depthRenderer = this._scene.enableDepthRenderer();
  48017. }
  48018. else if (!enabled && this._depthOfFieldEnabled) {
  48019. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._cameras);
  48020. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._cameras);
  48021. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRDepthOfField", this._cameras);
  48022. }
  48023. this._depthOfFieldEnabled = enabled;
  48024. },
  48025. enumerable: true,
  48026. configurable: true
  48027. });
  48028. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  48029. get: function () {
  48030. return this._lensFlareEnabled;
  48031. },
  48032. set: function (enabled) {
  48033. var blurIndex = this.gaussianBlurHPostProcesses.length - 2;
  48034. if (enabled && !this._lensFlareEnabled) {
  48035. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlare", this._scene.cameras);
  48036. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlareShift", this._scene.cameras);
  48037. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  48038. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  48039. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlareCompose", this._scene.cameras);
  48040. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRPostLensFlareDepthOfFieldSource", this._scene.cameras);
  48041. }
  48042. else if (!enabled && this._lensFlareEnabled) {
  48043. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlare", this._scene.cameras);
  48044. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlareShift", this._scene.cameras);
  48045. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  48046. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  48047. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlareCompose", this._scene.cameras);
  48048. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRPostLensFlareDepthOfFieldSource", this._scene.cameras);
  48049. }
  48050. this._lensFlareEnabled = enabled;
  48051. },
  48052. enumerable: true,
  48053. configurable: true
  48054. });
  48055. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  48056. get: function () {
  48057. return this._hdrEnabled;
  48058. },
  48059. set: function (enabled) {
  48060. if (enabled && !this._hdrEnabled) {
  48061. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLuminance", this._scene.cameras);
  48062. for (var i = 0; i < this.luminanceDownSamplePostProcesses.length; i++) {
  48063. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLuminanceDownSample" + i, this._scene.cameras);
  48064. }
  48065. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDR", this._scene.cameras);
  48066. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRPostHDReDepthOfFieldSource", this._scene.cameras);
  48067. }
  48068. else if (!enabled && this._hdrEnabled) {
  48069. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLuminance", this._scene.cameras);
  48070. for (var i = 0; i < this.luminanceDownSamplePostProcesses.length; i++) {
  48071. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLuminanceDownSample" + i, this._scene.cameras);
  48072. }
  48073. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDR", this._scene.cameras);
  48074. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRPostHDReDepthOfFieldSource", this._scene.cameras);
  48075. }
  48076. this._hdrEnabled = enabled;
  48077. },
  48078. enumerable: true,
  48079. configurable: true
  48080. });
  48081. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  48082. get: function () {
  48083. return this._motionBlurEnabled;
  48084. },
  48085. set: function (enabled) {
  48086. if (enabled && !this._motionBlurEnabled) {
  48087. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRMotionBlur", this._scene.cameras);
  48088. this._depthRenderer = this._scene.enableDepthRenderer();
  48089. }
  48090. else if (!enabled && this._motionBlurEnabled) {
  48091. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRMotionBlur", this._scene.cameras);
  48092. }
  48093. this._motionBlurEnabled = enabled;
  48094. },
  48095. enumerable: true,
  48096. configurable: true
  48097. });
  48098. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  48099. get: function () {
  48100. return this._motionBlurSamples;
  48101. },
  48102. set: function (samples) {
  48103. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  48104. this._motionBlurSamples = samples;
  48105. },
  48106. enumerable: true,
  48107. configurable: true
  48108. });
  48109. // Down Sample X4 Post-Processs
  48110. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  48111. var _this = this;
  48112. var downSampleX4Offsets = new Array(32);
  48113. 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);
  48114. this.downSampleX4PostProcess.onApply = function (effect) {
  48115. var id = 0;
  48116. for (var i = -2; i < 2; i++) {
  48117. for (var j = -2; j < 2; j++) {
  48118. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this.downSampleX4PostProcess.width);
  48119. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this.downSampleX4PostProcess.height);
  48120. id += 2;
  48121. }
  48122. }
  48123. effect.setArray2("dsOffsets", downSampleX4Offsets);
  48124. };
  48125. // Add to pipeline
  48126. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  48127. };
  48128. // Brightpass Post-Process
  48129. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  48130. var _this = this;
  48131. var brightOffsets = new Array(8);
  48132. 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);
  48133. this.brightPassPostProcess.onApply = function (effect) {
  48134. var sU = (1.0 / _this.brightPassPostProcess.width);
  48135. var sV = (1.0 / _this.brightPassPostProcess.height);
  48136. brightOffsets[0] = -0.5 * sU;
  48137. brightOffsets[1] = 0.5 * sV;
  48138. brightOffsets[2] = 0.5 * sU;
  48139. brightOffsets[3] = 0.5 * sV;
  48140. brightOffsets[4] = -0.5 * sU;
  48141. brightOffsets[5] = -0.5 * sV;
  48142. brightOffsets[6] = 0.5 * sU;
  48143. brightOffsets[7] = -0.5 * sV;
  48144. effect.setArray2("dsOffsets", brightOffsets);
  48145. effect.setFloat("brightThreshold", _this.brightThreshold);
  48146. };
  48147. // Add to pipeline
  48148. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  48149. };
  48150. // Create gaussian blur H&V post-processes
  48151. StandardRenderingPipeline.prototype._createGaussianBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  48152. var _this = this;
  48153. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  48154. var blurOffsets = new Array(9);
  48155. var blurWeights = new Array(9);
  48156. var uniforms = ["blurOffsets", "blurWeights", "blurWidth"];
  48157. var callback = function (height) {
  48158. return function (effect) {
  48159. // Weights
  48160. var x = 0.0;
  48161. for (var i = 0; i < 9; i++) {
  48162. x = (i - 4.0) / 4.0;
  48163. blurWeights[i] =
  48164. _this.gaussianCoefficient
  48165. * (1.0 / Math.sqrt(2.0 * Math.PI * _this.gaussianStandardDeviation))
  48166. * Math.exp((-((x - _this.gaussianMean) * (x - _this.gaussianMean))) / (2.0 * _this.gaussianStandardDeviation * _this.gaussianStandardDeviation));
  48167. }
  48168. var lastOutputDimensions = {
  48169. width: scene.getEngine().getRenderWidth(),
  48170. height: scene.getEngine().getRenderHeight()
  48171. };
  48172. for (var i = 0; i < 9; i++) {
  48173. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  48174. blurOffsets[i] = value;
  48175. }
  48176. effect.setArray("blurOffsets", blurOffsets);
  48177. effect.setArray("blurWeights", blurWeights);
  48178. if (height) {
  48179. effect.setFloat("blurWidth", _this.horizontalBlur ? 1.0 : _this[blurWidthKey]);
  48180. }
  48181. else {
  48182. effect.setFloat("blurWidth", _this[blurWidthKey]);
  48183. }
  48184. };
  48185. };
  48186. // Create horizontal gaussian blur post-processes
  48187. 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);
  48188. gaussianBlurHPostProcess.onApply = callback(false);
  48189. // Create vertical gaussian blur post-process
  48190. 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);
  48191. gaussianBlurVPostProcess.onApply = callback(true);
  48192. // Add to pipeline
  48193. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH" + indice, function () { return gaussianBlurHPostProcess; }, true));
  48194. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV" + indice, function () { return gaussianBlurVPostProcess; }, true));
  48195. // Finish
  48196. this.gaussianBlurHPostProcesses.push(gaussianBlurHPostProcess);
  48197. this.gaussianBlurVPostProcesses.push(gaussianBlurVPostProcess);
  48198. };
  48199. // Create texture adder post-process
  48200. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  48201. var _this = this;
  48202. 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);
  48203. this.textureAdderPostProcess.onApply = function (effect) {
  48204. effect.setTextureFromPostProcess("otherSampler", _this.originalPostProcess);
  48205. effect.setTexture("lensSampler", _this.lensTexture);
  48206. effect.setFloat("exposure", _this.exposure);
  48207. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  48208. _this._currentHDRSource = _this.textureAdderFinalPostProcess;
  48209. };
  48210. // Add to pipeline
  48211. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  48212. };
  48213. // Create luminance
  48214. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  48215. var _this = this;
  48216. // Create luminance
  48217. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  48218. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  48219. var offsets = [];
  48220. this.luminancePostProcess.onApply = function (effect) {
  48221. var sU = (1.0 / _this.luminancePostProcess.width);
  48222. var sV = (1.0 / _this.luminancePostProcess.height);
  48223. offsets[0] = -0.5 * sU;
  48224. offsets[1] = 0.5 * sV;
  48225. offsets[2] = 0.5 * sU;
  48226. offsets[3] = 0.5 * sV;
  48227. offsets[4] = -0.5 * sU;
  48228. offsets[5] = -0.5 * sV;
  48229. offsets[6] = 0.5 * sU;
  48230. offsets[7] = -0.5 * sV;
  48231. effect.setArray2("lumOffsets", offsets);
  48232. };
  48233. // Add to pipeline
  48234. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  48235. // Create down sample luminance
  48236. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  48237. var size = Math.pow(3, i);
  48238. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  48239. if (i === 0) {
  48240. defines += "#define FINAL_DOWN_SAMPLER";
  48241. }
  48242. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  48243. this.luminanceDownSamplePostProcesses.push(postProcess);
  48244. }
  48245. // Create callbacks and add effects
  48246. var lastLuminance = this.luminancePostProcess;
  48247. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  48248. var downSampleOffsets = new Array(18);
  48249. pp.onApply = function (effect) {
  48250. var id = 0;
  48251. for (var x = -1; x < 2; x++) {
  48252. for (var y = -1; y < 2; y++) {
  48253. downSampleOffsets[id] = x / lastLuminance.width;
  48254. downSampleOffsets[id + 1] = y / lastLuminance.height;
  48255. id += 2;
  48256. }
  48257. }
  48258. effect.setArray2("dsOffsets", downSampleOffsets);
  48259. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  48260. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  48261. lastLuminance = _this.luminancePostProcess;
  48262. }
  48263. else {
  48264. lastLuminance = pp;
  48265. }
  48266. };
  48267. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  48268. pp.onAfterRender = function (effect) {
  48269. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  48270. 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);
  48271. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  48272. };
  48273. }
  48274. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  48275. });
  48276. };
  48277. // Create HDR post-process
  48278. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  48279. var _this = this;
  48280. this.hdrPostProcess = new BABYLON.PostProcess("HDR", "standard", ["averageLuminance"], ["textureAdderSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  48281. var outputLiminance = 1;
  48282. var time = 0;
  48283. var lastTime = 0;
  48284. this.hdrPostProcess.onApply = function (effect) {
  48285. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentHDRSource);
  48286. time += scene.getEngine().getDeltaTime();
  48287. if (outputLiminance < 0) {
  48288. outputLiminance = _this._hdrCurrentLuminance;
  48289. }
  48290. else {
  48291. var dt = (lastTime - time) / 1000.0;
  48292. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  48293. outputLiminance += _this.hdrDecreaseRate * dt;
  48294. }
  48295. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  48296. outputLiminance -= _this.hdrIncreaseRate * dt;
  48297. }
  48298. else {
  48299. outputLiminance = _this._hdrCurrentLuminance;
  48300. }
  48301. }
  48302. outputLiminance = BABYLON.MathTools.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  48303. effect.setFloat("averageLuminance", outputLiminance);
  48304. lastTime = time;
  48305. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  48306. };
  48307. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  48308. };
  48309. // Create lens flare post-process
  48310. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  48311. var _this = this;
  48312. 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);
  48313. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  48314. this._createGaussianBlurPostProcesses(scene, ratio / 4, 4);
  48315. 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);
  48316. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  48317. var resolution = new BABYLON.Vector2(0, 0);
  48318. // Lens flare
  48319. this.lensFlarePostProcess.onApply = function (effect) {
  48320. effect.setTextureFromPostProcess("textureSampler", _this.gaussianBlurHPostProcesses[0]);
  48321. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  48322. effect.setFloat("strength", _this.lensFlareStrength);
  48323. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  48324. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  48325. // Shift
  48326. resolution.x = _this.lensFlarePostProcess.width;
  48327. resolution.y = _this.lensFlarePostProcess.height;
  48328. effect.setVector2("resolution", resolution);
  48329. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  48330. };
  48331. // Compose
  48332. 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);
  48333. 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);
  48334. this.lensFlareComposePostProcess.onApply = function (effect) {
  48335. effect.setTextureFromPostProcess("otherSampler", _this.textureAdderFinalPostProcess);
  48336. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  48337. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  48338. // Lens start rotation matrix
  48339. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  48340. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  48341. 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));
  48342. camRot *= 4.0;
  48343. 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);
  48344. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  48345. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  48346. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  48347. _this._currentHDRSource = _this.lensFlareFinalPostProcess;
  48348. };
  48349. };
  48350. // Create depth-of-field post-process
  48351. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  48352. var _this = this;
  48353. 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);
  48354. this.depthOfFieldPostProcess.onApply = function (effect) {
  48355. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  48356. effect.setTexture("depthSampler", _this._depthRenderer.getDepthMap());
  48357. effect.setFloat("distance", _this.depthOfFieldDistance);
  48358. };
  48359. // Add to pipeline
  48360. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  48361. };
  48362. // Create motion blur post-process
  48363. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  48364. var _this = this;
  48365. this.motionBlurPostProcess = new BABYLON.PostProcess("HDRMotionBlur", "standard", ["inverseViewProjection", "prevViewProjection", "screenSize", "motionScale", "motionStrength"], ["depthSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + this.motionBlurSamples.toFixed(1), BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  48366. var motionScale = 0;
  48367. var prevViewProjection = BABYLON.Matrix.Identity();
  48368. var invViewProjection = BABYLON.Matrix.Identity();
  48369. var viewProjection = BABYLON.Matrix.Identity();
  48370. var screenSize = BABYLON.Vector2.Zero();
  48371. this.motionBlurPostProcess.onApply = function (effect) {
  48372. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  48373. viewProjection.invertToRef(invViewProjection);
  48374. effect.setMatrix("inverseViewProjection", invViewProjection);
  48375. effect.setMatrix("prevViewProjection", prevViewProjection);
  48376. prevViewProjection = viewProjection;
  48377. screenSize.x = _this.motionBlurPostProcess.width;
  48378. screenSize.y = _this.motionBlurPostProcess.height;
  48379. effect.setVector2("screenSize", screenSize);
  48380. motionScale = scene.getEngine().getFps() / 60.0;
  48381. effect.setFloat("motionScale", motionScale);
  48382. effect.setFloat("motionStrength", _this.motionStrength);
  48383. effect.setTexture("depthSampler", _this._depthRenderer.getDepthMap());
  48384. };
  48385. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  48386. };
  48387. // Dispose
  48388. StandardRenderingPipeline.prototype.dispose = function () {
  48389. for (var i = 0; i < this._cameras.length; i++) {
  48390. var camera = this._cameras[i];
  48391. this.originalPostProcess.dispose(camera);
  48392. this.downSampleX4PostProcess.dispose(camera);
  48393. this.brightPassPostProcess.dispose(camera);
  48394. this.textureAdderPostProcess.dispose(camera);
  48395. for (var j = 0; j < this.gaussianBlurHPostProcesses.length; j++) {
  48396. this.gaussianBlurHPostProcesses[j].dispose(camera);
  48397. }
  48398. for (var j = 0; j < this.gaussianBlurVPostProcesses.length; j++) {
  48399. this.gaussianBlurVPostProcesses[j].dispose(camera);
  48400. }
  48401. this.textureAdderFinalPostProcess.dispose(camera);
  48402. this.lensFlarePostProcess.dispose(camera);
  48403. this.lensFlareComposePostProcess.dispose(camera);
  48404. this.depthOfFieldPostProcess.dispose(camera);
  48405. this.motionBlurPostProcess.dispose(camera);
  48406. }
  48407. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  48408. _super.prototype.dispose.call(this);
  48409. };
  48410. // Serialize rendering pipeline
  48411. StandardRenderingPipeline.prototype.serialize = function () {
  48412. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  48413. serializationObject.customType = "StandardRenderingPipeline";
  48414. return serializationObject;
  48415. };
  48416. // Parse serialized pipeline
  48417. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  48418. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  48419. };
  48420. return StandardRenderingPipeline;
  48421. }(BABYLON.PostProcessRenderPipeline));
  48422. // Luminance steps
  48423. StandardRenderingPipeline.LuminanceSteps = 6;
  48424. __decorate([
  48425. BABYLON.serialize()
  48426. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  48427. __decorate([
  48428. BABYLON.serialize()
  48429. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  48430. __decorate([
  48431. BABYLON.serialize()
  48432. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  48433. __decorate([
  48434. BABYLON.serialize()
  48435. ], StandardRenderingPipeline.prototype, "gaussianCoefficient", void 0);
  48436. __decorate([
  48437. BABYLON.serialize()
  48438. ], StandardRenderingPipeline.prototype, "gaussianMean", void 0);
  48439. __decorate([
  48440. BABYLON.serialize()
  48441. ], StandardRenderingPipeline.prototype, "gaussianStandardDeviation", void 0);
  48442. __decorate([
  48443. BABYLON.serialize()
  48444. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  48445. __decorate([
  48446. BABYLON.serializeAsTexture("lensTexture")
  48447. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  48448. __decorate([
  48449. BABYLON.serialize()
  48450. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  48451. __decorate([
  48452. BABYLON.serialize()
  48453. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  48454. __decorate([
  48455. BABYLON.serialize()
  48456. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  48457. __decorate([
  48458. BABYLON.serializeAsTexture("lensColorTexture")
  48459. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  48460. __decorate([
  48461. BABYLON.serialize()
  48462. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  48463. __decorate([
  48464. BABYLON.serialize()
  48465. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  48466. __decorate([
  48467. BABYLON.serialize()
  48468. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  48469. __decorate([
  48470. BABYLON.serialize()
  48471. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  48472. __decorate([
  48473. BABYLON.serializeAsTexture("lensStarTexture")
  48474. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  48475. __decorate([
  48476. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  48477. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  48478. __decorate([
  48479. BABYLON.serialize()
  48480. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  48481. __decorate([
  48482. BABYLON.serialize()
  48483. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  48484. __decorate([
  48485. BABYLON.serialize()
  48486. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  48487. __decorate([
  48488. BABYLON.serialize()
  48489. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  48490. __decorate([
  48491. BABYLON.serialize()
  48492. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  48493. __decorate([
  48494. BABYLON.serialize()
  48495. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  48496. __decorate([
  48497. BABYLON.serialize()
  48498. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  48499. __decorate([
  48500. BABYLON.serialize()
  48501. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  48502. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  48503. })(BABYLON || (BABYLON = {}));
  48504. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  48505. var BABYLON;
  48506. (function (BABYLON) {
  48507. var BlurPostProcess = (function (_super) {
  48508. __extends(BlurPostProcess, _super);
  48509. function BlurPostProcess(name, direction, blurWidth, options, camera, samplingMode, engine, reusable) {
  48510. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  48511. var _this = _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  48512. _this.direction = direction;
  48513. _this.blurWidth = blurWidth;
  48514. _this.onApplyObservable.add(function (effect) {
  48515. effect.setFloat2("screenSize", _this.width, _this.height);
  48516. effect.setVector2("direction", _this.direction);
  48517. effect.setFloat("blurWidth", _this.blurWidth);
  48518. });
  48519. return _this;
  48520. }
  48521. return BlurPostProcess;
  48522. }(BABYLON.PostProcess));
  48523. BABYLON.BlurPostProcess = BlurPostProcess;
  48524. })(BABYLON || (BABYLON = {}));
  48525. //# sourceMappingURL=babylon.blurPostProcess.js.map
  48526. var BABYLON;
  48527. (function (BABYLON) {
  48528. var RefractionPostProcess = (function (_super) {
  48529. __extends(RefractionPostProcess, _super);
  48530. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  48531. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  48532. _this.color = color;
  48533. _this.depth = depth;
  48534. _this.colorLevel = colorLevel;
  48535. _this.onActivateObservable.add(function (cam) {
  48536. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  48537. });
  48538. _this.onApplyObservable.add(function (effect) {
  48539. effect.setColor3("baseColor", _this.color);
  48540. effect.setFloat("depth", _this.depth);
  48541. effect.setFloat("colorLevel", _this.colorLevel);
  48542. effect.setTexture("refractionSampler", _this._refRexture);
  48543. });
  48544. return _this;
  48545. }
  48546. // Methods
  48547. RefractionPostProcess.prototype.dispose = function (camera) {
  48548. if (this._refRexture) {
  48549. this._refRexture.dispose();
  48550. }
  48551. _super.prototype.dispose.call(this, camera);
  48552. };
  48553. return RefractionPostProcess;
  48554. }(BABYLON.PostProcess));
  48555. BABYLON.RefractionPostProcess = RefractionPostProcess;
  48556. })(BABYLON || (BABYLON = {}));
  48557. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  48558. var BABYLON;
  48559. (function (BABYLON) {
  48560. var BlackAndWhitePostProcess = (function (_super) {
  48561. __extends(BlackAndWhitePostProcess, _super);
  48562. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  48563. return _super.call(this, name, "blackAndWhite", null, null, options, camera, samplingMode, engine, reusable) || this;
  48564. }
  48565. return BlackAndWhitePostProcess;
  48566. }(BABYLON.PostProcess));
  48567. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  48568. })(BABYLON || (BABYLON = {}));
  48569. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  48570. var BABYLON;
  48571. (function (BABYLON) {
  48572. var ConvolutionPostProcess = (function (_super) {
  48573. __extends(ConvolutionPostProcess, _super);
  48574. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  48575. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  48576. _this.kernel = kernel;
  48577. _this.onApply = function (effect) {
  48578. effect.setFloat2("screenSize", _this.width, _this.height);
  48579. effect.setArray("kernel", _this.kernel);
  48580. };
  48581. return _this;
  48582. }
  48583. return ConvolutionPostProcess;
  48584. }(BABYLON.PostProcess));
  48585. // Statics
  48586. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  48587. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  48588. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  48589. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  48590. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  48591. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  48592. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  48593. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  48594. })(BABYLON || (BABYLON = {}));
  48595. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  48596. var BABYLON;
  48597. (function (BABYLON) {
  48598. var FilterPostProcess = (function (_super) {
  48599. __extends(FilterPostProcess, _super);
  48600. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  48601. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  48602. _this.kernelMatrix = kernelMatrix;
  48603. _this.onApply = function (effect) {
  48604. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  48605. };
  48606. return _this;
  48607. }
  48608. return FilterPostProcess;
  48609. }(BABYLON.PostProcess));
  48610. BABYLON.FilterPostProcess = FilterPostProcess;
  48611. })(BABYLON || (BABYLON = {}));
  48612. //# sourceMappingURL=babylon.filterPostProcess.js.map
  48613. var BABYLON;
  48614. (function (BABYLON) {
  48615. var FxaaPostProcess = (function (_super) {
  48616. __extends(FxaaPostProcess, _super);
  48617. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable) {
  48618. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable) || this;
  48619. _this.onSizeChangedObservable.add(function () {
  48620. _this.texelWidth = 1.0 / _this.width;
  48621. _this.texelHeight = 1.0 / _this.height;
  48622. });
  48623. _this.onApplyObservable.add(function (effect) {
  48624. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  48625. });
  48626. return _this;
  48627. }
  48628. return FxaaPostProcess;
  48629. }(BABYLON.PostProcess));
  48630. BABYLON.FxaaPostProcess = FxaaPostProcess;
  48631. })(BABYLON || (BABYLON = {}));
  48632. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  48633. var BABYLON;
  48634. (function (BABYLON) {
  48635. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  48636. var VolumetricLightScatteringPostProcess = (function (_super) {
  48637. __extends(VolumetricLightScatteringPostProcess, _super);
  48638. /**
  48639. * @constructor
  48640. * @param {string} name - The post-process name
  48641. * @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)
  48642. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  48643. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  48644. * @param {number} samples - The post-process quality, default 100
  48645. * @param {number} samplingMode - The post-process filtering mode
  48646. * @param {BABYLON.Engine} engine - The babylon engine
  48647. * @param {boolean} reusable - If the post-process is reusable
  48648. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  48649. */
  48650. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  48651. if (samples === void 0) { samples = 100; }
  48652. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  48653. 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;
  48654. _this._screenCoordinates = BABYLON.Vector2.Zero();
  48655. /**
  48656. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  48657. * @type {Vector3}
  48658. */
  48659. _this.customMeshPosition = BABYLON.Vector3.Zero();
  48660. /**
  48661. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  48662. * @type {boolean}
  48663. */
  48664. _this.useCustomMeshPosition = false;
  48665. /**
  48666. * If the post-process should inverse the light scattering direction
  48667. * @type {boolean}
  48668. */
  48669. _this.invert = true;
  48670. /**
  48671. * Array containing the excluded meshes not rendered in the internal pass
  48672. */
  48673. _this.excludedMeshes = new Array();
  48674. /**
  48675. * Controls the overall intensity of the post-process
  48676. * @type {number}
  48677. */
  48678. _this.exposure = 0.3;
  48679. /**
  48680. * Dissipates each sample's contribution in range [0, 1]
  48681. * @type {number}
  48682. */
  48683. _this.decay = 0.96815;
  48684. /**
  48685. * Controls the overall intensity of each sample
  48686. * @type {number}
  48687. */
  48688. _this.weight = 0.58767;
  48689. /**
  48690. * Controls the density of each sample
  48691. * @type {number}
  48692. */
  48693. _this.density = 0.926;
  48694. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  48695. var engine = scene.getEngine();
  48696. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  48697. // Configure mesh
  48698. _this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  48699. // Configure
  48700. _this._createPass(scene, ratio.passRatio || ratio);
  48701. _this.onActivate = function (camera) {
  48702. if (!_this.isSupported) {
  48703. _this.dispose(camera);
  48704. }
  48705. _this.onActivate = null;
  48706. };
  48707. _this.onApplyObservable.add(function (effect) {
  48708. _this._updateMeshScreenCoordinates(scene);
  48709. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  48710. effect.setFloat("exposure", _this.exposure);
  48711. effect.setFloat("decay", _this.decay);
  48712. effect.setFloat("weight", _this.weight);
  48713. effect.setFloat("density", _this.density);
  48714. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  48715. });
  48716. return _this;
  48717. }
  48718. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  48719. get: function () {
  48720. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  48721. return false;
  48722. },
  48723. set: function (useDiffuseColor) {
  48724. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  48725. },
  48726. enumerable: true,
  48727. configurable: true
  48728. });
  48729. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  48730. var mesh = subMesh.getMesh();
  48731. // Render this.mesh as default
  48732. if (mesh === this.mesh) {
  48733. return mesh.material.isReady(mesh);
  48734. }
  48735. var defines = [];
  48736. var attribs = [BABYLON.VertexBuffer.PositionKind];
  48737. var material = subMesh.getMaterial();
  48738. var needUV = false;
  48739. // Alpha test
  48740. if (material) {
  48741. if (material.needAlphaTesting()) {
  48742. defines.push("#define ALPHATEST");
  48743. }
  48744. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  48745. attribs.push(BABYLON.VertexBuffer.UVKind);
  48746. defines.push("#define UV1");
  48747. }
  48748. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  48749. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  48750. defines.push("#define UV2");
  48751. }
  48752. }
  48753. // Bones
  48754. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  48755. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  48756. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  48757. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  48758. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  48759. }
  48760. else {
  48761. defines.push("#define NUM_BONE_INFLUENCERS 0");
  48762. }
  48763. // Instances
  48764. if (useInstances) {
  48765. defines.push("#define INSTANCES");
  48766. attribs.push("world0");
  48767. attribs.push("world1");
  48768. attribs.push("world2");
  48769. attribs.push("world3");
  48770. }
  48771. // Get correct effect
  48772. var join = defines.join("\n");
  48773. if (this._cachedDefines !== join) {
  48774. this._cachedDefines = join;
  48775. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  48776. }
  48777. return this._volumetricLightScatteringPass.isReady();
  48778. };
  48779. /**
  48780. * Sets the new light position for light scattering effect
  48781. * @param {BABYLON.Vector3} The new custom light position
  48782. */
  48783. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  48784. this.customMeshPosition = position;
  48785. };
  48786. /**
  48787. * Returns the light position for light scattering effect
  48788. * @return {BABYLON.Vector3} The custom light position
  48789. */
  48790. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  48791. return this.customMeshPosition;
  48792. };
  48793. /**
  48794. * Disposes the internal assets and detaches the post-process from the camera
  48795. */
  48796. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  48797. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  48798. if (rttIndex !== -1) {
  48799. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  48800. }
  48801. this._volumetricLightScatteringRTT.dispose();
  48802. _super.prototype.dispose.call(this, camera);
  48803. };
  48804. /**
  48805. * Returns the render target texture used by the post-process
  48806. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  48807. */
  48808. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  48809. return this._volumetricLightScatteringRTT;
  48810. };
  48811. // Private methods
  48812. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  48813. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  48814. return true;
  48815. }
  48816. return false;
  48817. };
  48818. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  48819. var _this = this;
  48820. var engine = scene.getEngine();
  48821. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  48822. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48823. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48824. this._volumetricLightScatteringRTT.renderList = null;
  48825. this._volumetricLightScatteringRTT.renderParticles = false;
  48826. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  48827. // Custom render function for submeshes
  48828. var renderSubMesh = function (subMesh) {
  48829. var mesh = subMesh.getRenderingMesh();
  48830. if (_this._meshExcluded(mesh)) {
  48831. return;
  48832. }
  48833. var scene = mesh.getScene();
  48834. var engine = scene.getEngine();
  48835. // Culling
  48836. engine.setState(subMesh.getMaterial().backFaceCulling);
  48837. // Managing instances
  48838. var batch = mesh._getInstancesRenderList(subMesh._id);
  48839. if (batch.mustReturn) {
  48840. return;
  48841. }
  48842. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  48843. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  48844. var effect = _this._volumetricLightScatteringPass;
  48845. if (mesh === _this.mesh) {
  48846. if (subMesh.effect) {
  48847. effect = subMesh.effect;
  48848. }
  48849. else {
  48850. effect = subMesh.getMaterial().getEffect();
  48851. }
  48852. }
  48853. engine.enableEffect(effect);
  48854. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  48855. if (mesh === _this.mesh) {
  48856. subMesh.getMaterial().bind(mesh.getWorldMatrix(), mesh);
  48857. }
  48858. else {
  48859. var material = subMesh.getMaterial();
  48860. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  48861. // Alpha test
  48862. if (material && material.needAlphaTesting()) {
  48863. var alphaTexture = material.getAlphaTestTexture();
  48864. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  48865. if (alphaTexture) {
  48866. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  48867. }
  48868. }
  48869. // Bones
  48870. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  48871. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  48872. }
  48873. }
  48874. // Draw
  48875. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  48876. }
  48877. };
  48878. // Render target texture callbacks
  48879. var savedSceneClearColor;
  48880. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  48881. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  48882. savedSceneClearColor = scene.clearColor;
  48883. scene.clearColor = sceneClearColor;
  48884. });
  48885. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  48886. scene.clearColor = savedSceneClearColor;
  48887. });
  48888. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  48889. var engine = scene.getEngine();
  48890. var index;
  48891. for (index = 0; index < opaqueSubMeshes.length; index++) {
  48892. renderSubMesh(opaqueSubMeshes.data[index]);
  48893. }
  48894. engine.setAlphaTesting(true);
  48895. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  48896. renderSubMesh(alphaTestSubMeshes.data[index]);
  48897. }
  48898. engine.setAlphaTesting(false);
  48899. if (transparentSubMeshes.length) {
  48900. // Sort sub meshes
  48901. for (index = 0; index < transparentSubMeshes.length; index++) {
  48902. var submesh = transparentSubMeshes.data[index];
  48903. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  48904. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  48905. }
  48906. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  48907. sortedArray.sort(function (a, b) {
  48908. // Alpha index first
  48909. if (a._alphaIndex > b._alphaIndex) {
  48910. return 1;
  48911. }
  48912. if (a._alphaIndex < b._alphaIndex) {
  48913. return -1;
  48914. }
  48915. // Then distance to camera
  48916. if (a._distanceToCamera < b._distanceToCamera) {
  48917. return 1;
  48918. }
  48919. if (a._distanceToCamera > b._distanceToCamera) {
  48920. return -1;
  48921. }
  48922. return 0;
  48923. });
  48924. // Render sub meshes
  48925. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  48926. for (index = 0; index < sortedArray.length; index++) {
  48927. renderSubMesh(sortedArray[index]);
  48928. }
  48929. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  48930. }
  48931. };
  48932. };
  48933. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  48934. var transform = scene.getTransformMatrix();
  48935. var meshPosition;
  48936. if (this.useCustomMeshPosition) {
  48937. meshPosition = this.customMeshPosition;
  48938. }
  48939. else if (this.attachedNode) {
  48940. meshPosition = this.attachedNode.position;
  48941. }
  48942. else {
  48943. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  48944. }
  48945. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  48946. this._screenCoordinates.x = pos.x / this._viewPort.width;
  48947. this._screenCoordinates.y = pos.y / this._viewPort.height;
  48948. if (this.invert)
  48949. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  48950. };
  48951. // Static methods
  48952. /**
  48953. * Creates a default mesh for the Volumeric Light Scattering post-process
  48954. * @param {string} The mesh name
  48955. * @param {BABYLON.Scene} The scene where to create the mesh
  48956. * @return {BABYLON.Mesh} the default mesh
  48957. */
  48958. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  48959. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  48960. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  48961. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  48962. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  48963. mesh.material = material;
  48964. return mesh;
  48965. };
  48966. return VolumetricLightScatteringPostProcess;
  48967. }(BABYLON.PostProcess));
  48968. __decorate([
  48969. BABYLON.serializeAsVector3()
  48970. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  48971. __decorate([
  48972. BABYLON.serialize()
  48973. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  48974. __decorate([
  48975. BABYLON.serialize()
  48976. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  48977. __decorate([
  48978. BABYLON.serializeAsMeshReference()
  48979. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  48980. __decorate([
  48981. BABYLON.serialize()
  48982. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  48983. __decorate([
  48984. BABYLON.serialize()
  48985. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  48986. __decorate([
  48987. BABYLON.serialize()
  48988. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  48989. __decorate([
  48990. BABYLON.serialize()
  48991. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  48992. __decorate([
  48993. BABYLON.serialize()
  48994. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  48995. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  48996. })(BABYLON || (BABYLON = {}));
  48997. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  48998. //
  48999. // This post-process allows the modification of rendered colors by using
  49000. // a 'look-up table' (LUT). This effect is also called Color Grading.
  49001. //
  49002. // The object needs to be provided an url to a texture containing the color
  49003. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  49004. // Use an image editing software to tweak the LUT to match your needs.
  49005. //
  49006. // For an example of a color LUT, see here:
  49007. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  49008. // For explanations on color grading, see here:
  49009. // http://udn.epicgames.com/Three/ColorGrading.html
  49010. //
  49011. var BABYLON;
  49012. (function (BABYLON) {
  49013. var ColorCorrectionPostProcess = (function (_super) {
  49014. __extends(ColorCorrectionPostProcess, _super);
  49015. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  49016. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  49017. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  49018. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  49019. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49020. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49021. _this.onApply = function (effect) {
  49022. effect.setTexture("colorTable", _this._colorTableTexture);
  49023. };
  49024. return _this;
  49025. }
  49026. return ColorCorrectionPostProcess;
  49027. }(BABYLON.PostProcess));
  49028. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  49029. })(BABYLON || (BABYLON = {}));
  49030. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  49031. var BABYLON;
  49032. (function (BABYLON) {
  49033. var TonemappingOperator;
  49034. (function (TonemappingOperator) {
  49035. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  49036. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  49037. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  49038. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  49039. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  49040. ;
  49041. var TonemapPostProcess = (function (_super) {
  49042. __extends(TonemapPostProcess, _super);
  49043. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  49044. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  49045. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  49046. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat) || this;
  49047. _this._operator = _operator;
  49048. _this.exposureAdjustment = exposureAdjustment;
  49049. var defines = "#define ";
  49050. if (_this._operator === TonemappingOperator.Hable)
  49051. defines += "HABLE_TONEMAPPING";
  49052. else if (_this._operator === TonemappingOperator.Reinhard)
  49053. defines += "REINHARD_TONEMAPPING";
  49054. else if (_this._operator === TonemappingOperator.HejiDawson)
  49055. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  49056. else if (_this._operator === TonemappingOperator.Photographic)
  49057. defines += "PHOTOGRAPHIC_TONEMAPPING";
  49058. //sadly a second call to create the effect.
  49059. _this.updateEffect(defines);
  49060. _this.onApply = function (effect) {
  49061. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  49062. };
  49063. return _this;
  49064. }
  49065. return TonemapPostProcess;
  49066. }(BABYLON.PostProcess));
  49067. BABYLON.TonemapPostProcess = TonemapPostProcess;
  49068. })(BABYLON || (BABYLON = {}));
  49069. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  49070. var BABYLON;
  49071. (function (BABYLON) {
  49072. var DisplayPassPostProcess = (function (_super) {
  49073. __extends(DisplayPassPostProcess, _super);
  49074. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  49075. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  49076. }
  49077. return DisplayPassPostProcess;
  49078. }(BABYLON.PostProcess));
  49079. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  49080. })(BABYLON || (BABYLON = {}));
  49081. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  49082. /// <reference path="..\babylon.node.ts" />
  49083. var BABYLON;
  49084. (function (BABYLON) {
  49085. var Bone = (function (_super) {
  49086. __extends(Bone, _super);
  49087. function Bone(name, skeleton, parentBone, matrix, restPose) {
  49088. var _this = _super.call(this, name, skeleton.getScene()) || this;
  49089. _this.name = name;
  49090. _this.children = new Array();
  49091. _this.animations = new Array();
  49092. _this._worldTransform = new BABYLON.Matrix();
  49093. _this._absoluteTransform = new BABYLON.Matrix();
  49094. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  49095. _this._scaleMatrix = BABYLON.Matrix.Identity();
  49096. _this._scaleVector = new BABYLON.Vector3(1, 1, 1);
  49097. _this._negateScaleChildren = new BABYLON.Vector3(1, 1, 1);
  49098. _this._scalingDeterminant = 1;
  49099. _this._skeleton = skeleton;
  49100. _this._localMatrix = matrix;
  49101. _this._baseMatrix = matrix.clone();
  49102. _this._restPose = restPose ? restPose : matrix.clone();
  49103. skeleton.bones.push(_this);
  49104. if (parentBone) {
  49105. _this._parent = parentBone;
  49106. parentBone.children.push(_this);
  49107. }
  49108. else {
  49109. _this._parent = null;
  49110. }
  49111. _this._updateDifferenceMatrix();
  49112. if (_this.getAbsoluteTransform().determinant() < 0) {
  49113. _this._scalingDeterminant *= -1;
  49114. }
  49115. return _this;
  49116. }
  49117. Object.defineProperty(Bone.prototype, "_matrix", {
  49118. get: function () {
  49119. return this._localMatrix;
  49120. },
  49121. set: function (val) {
  49122. if (this._localMatrix) {
  49123. this._localMatrix.copyFrom(val);
  49124. }
  49125. else {
  49126. this._localMatrix = val;
  49127. }
  49128. },
  49129. enumerable: true,
  49130. configurable: true
  49131. });
  49132. // Members
  49133. Bone.prototype.getParent = function () {
  49134. return this._parent;
  49135. };
  49136. Bone.prototype.getLocalMatrix = function () {
  49137. return this._localMatrix;
  49138. };
  49139. Bone.prototype.getBaseMatrix = function () {
  49140. return this._baseMatrix;
  49141. };
  49142. Bone.prototype.getRestPose = function () {
  49143. return this._restPose;
  49144. };
  49145. Bone.prototype.returnToRest = function () {
  49146. this.updateMatrix(this._restPose.clone());
  49147. };
  49148. Bone.prototype.getWorldMatrix = function () {
  49149. return this._worldTransform;
  49150. };
  49151. Bone.prototype.getInvertedAbsoluteTransform = function () {
  49152. return this._invertedAbsoluteTransform;
  49153. };
  49154. Bone.prototype.getAbsoluteTransform = function () {
  49155. return this._absoluteTransform;
  49156. };
  49157. Object.defineProperty(Bone.prototype, "position", {
  49158. // Properties (matches AbstractMesh properties)
  49159. get: function () {
  49160. return this.getPosition();
  49161. },
  49162. set: function (newPosition) {
  49163. this.setPosition(newPosition);
  49164. },
  49165. enumerable: true,
  49166. configurable: true
  49167. });
  49168. Object.defineProperty(Bone.prototype, "rotation", {
  49169. get: function () {
  49170. return this.getRotation();
  49171. },
  49172. set: function (newRotation) {
  49173. this.setRotation(newRotation);
  49174. },
  49175. enumerable: true,
  49176. configurable: true
  49177. });
  49178. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  49179. get: function () {
  49180. return this.getRotationQuaternion();
  49181. },
  49182. set: function (newRotation) {
  49183. this.setRotationQuaternion(newRotation);
  49184. },
  49185. enumerable: true,
  49186. configurable: true
  49187. });
  49188. Object.defineProperty(Bone.prototype, "scaling", {
  49189. get: function () {
  49190. return this.getScale();
  49191. },
  49192. set: function (newScaling) {
  49193. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  49194. },
  49195. enumerable: true,
  49196. configurable: true
  49197. });
  49198. // Methods
  49199. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  49200. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  49201. this._baseMatrix = matrix.clone();
  49202. this._localMatrix = matrix.clone();
  49203. this._skeleton._markAsDirty();
  49204. if (updateDifferenceMatrix) {
  49205. this._updateDifferenceMatrix();
  49206. }
  49207. };
  49208. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  49209. if (!rootMatrix) {
  49210. rootMatrix = this._baseMatrix;
  49211. }
  49212. if (this._parent) {
  49213. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  49214. }
  49215. else {
  49216. this._absoluteTransform.copyFrom(rootMatrix);
  49217. }
  49218. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  49219. for (var index = 0; index < this.children.length; index++) {
  49220. this.children[index]._updateDifferenceMatrix();
  49221. }
  49222. };
  49223. Bone.prototype.markAsDirty = function () {
  49224. this._currentRenderId++;
  49225. this._skeleton._markAsDirty();
  49226. };
  49227. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  49228. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  49229. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  49230. // all animation may be coming from a library skeleton, so may need to create animation
  49231. if (this.animations.length === 0) {
  49232. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  49233. this.animations[0].setKeys([]);
  49234. }
  49235. // get animation info / verify there is such a range from the source bone
  49236. var sourceRange = source.animations[0].getRange(rangeName);
  49237. if (!sourceRange) {
  49238. return false;
  49239. }
  49240. var from = sourceRange.from;
  49241. var to = sourceRange.to;
  49242. var sourceKeys = source.animations[0].getKeys();
  49243. // rescaling prep
  49244. var sourceBoneLength = source.length;
  49245. var sourceParent = source.getParent();
  49246. var parent = this.getParent();
  49247. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  49248. var parentRatio = parentScalingReqd ? parent.length / sourceParent.length : null;
  49249. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  49250. var destKeys = this.animations[0].getKeys();
  49251. // loop vars declaration
  49252. var orig;
  49253. var origTranslation;
  49254. var mat;
  49255. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  49256. orig = sourceKeys[key];
  49257. if (orig.frame >= from && orig.frame <= to) {
  49258. if (rescaleAsRequired) {
  49259. mat = orig.value.clone();
  49260. // scale based on parent ratio, when bone has parent
  49261. if (parentScalingReqd) {
  49262. origTranslation = mat.getTranslation();
  49263. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  49264. // scale based on skeleton dimension ratio when root bone, and value is passed
  49265. }
  49266. else if (dimensionsScalingReqd) {
  49267. origTranslation = mat.getTranslation();
  49268. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  49269. // use original when root bone, and no data for skelDimensionsRatio
  49270. }
  49271. else {
  49272. mat = orig.value;
  49273. }
  49274. }
  49275. else {
  49276. mat = orig.value;
  49277. }
  49278. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  49279. }
  49280. }
  49281. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  49282. return true;
  49283. };
  49284. /**
  49285. * Translate the bone in local or world space.
  49286. * @param vec The amount to translate the bone.
  49287. * @param space The space that the translation is in.
  49288. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  49289. */
  49290. Bone.prototype.translate = function (vec, space, mesh) {
  49291. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  49292. var lm = this.getLocalMatrix();
  49293. if (space == BABYLON.Space.LOCAL) {
  49294. lm.m[12] += vec.x;
  49295. lm.m[13] += vec.y;
  49296. lm.m[14] += vec.z;
  49297. }
  49298. else {
  49299. var wm;
  49300. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  49301. if (mesh) {
  49302. wm = mesh.getWorldMatrix();
  49303. }
  49304. this._skeleton.computeAbsoluteTransforms();
  49305. var tmat = Bone._tmpMats[0];
  49306. var tvec = Bone._tmpVecs[0];
  49307. if (mesh) {
  49308. tmat.copyFrom(this._parent.getAbsoluteTransform());
  49309. tmat.multiplyToRef(wm, tmat);
  49310. }
  49311. else {
  49312. tmat.copyFrom(this._parent.getAbsoluteTransform());
  49313. }
  49314. tmat.m[12] = 0;
  49315. tmat.m[13] = 0;
  49316. tmat.m[14] = 0;
  49317. tmat.invert();
  49318. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  49319. lm.m[12] += tvec.x;
  49320. lm.m[13] += tvec.y;
  49321. lm.m[14] += tvec.z;
  49322. }
  49323. this.markAsDirty();
  49324. };
  49325. /**
  49326. * Set the postion of the bone in local or world space.
  49327. * @param position The position to set the bone.
  49328. * @param space The space that the position is in.
  49329. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  49330. */
  49331. Bone.prototype.setPosition = function (position, space, mesh) {
  49332. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  49333. var lm = this.getLocalMatrix();
  49334. if (space == BABYLON.Space.LOCAL) {
  49335. lm.m[12] = position.x;
  49336. lm.m[13] = position.y;
  49337. lm.m[14] = position.z;
  49338. }
  49339. else {
  49340. var wm;
  49341. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  49342. if (mesh) {
  49343. wm = mesh.getWorldMatrix();
  49344. }
  49345. this._skeleton.computeAbsoluteTransforms();
  49346. var tmat = Bone._tmpMats[0];
  49347. var vec = Bone._tmpVecs[0];
  49348. if (mesh) {
  49349. tmat.copyFrom(this._parent.getAbsoluteTransform());
  49350. tmat.multiplyToRef(wm, tmat);
  49351. }
  49352. else {
  49353. tmat.copyFrom(this._parent.getAbsoluteTransform());
  49354. }
  49355. tmat.invert();
  49356. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  49357. lm.m[12] = vec.x;
  49358. lm.m[13] = vec.y;
  49359. lm.m[14] = vec.z;
  49360. }
  49361. this.markAsDirty();
  49362. };
  49363. /**
  49364. * Set the absolute postion of the bone (world space).
  49365. * @param position The position to set the bone.
  49366. * @param mesh The mesh that this bone is attached to.
  49367. */
  49368. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  49369. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  49370. };
  49371. /**
  49372. * Set the scale of the bone on the x, y and z axes.
  49373. * @param x The scale of the bone on the x axis.
  49374. * @param x The scale of the bone on the y axis.
  49375. * @param z The scale of the bone on the z axis.
  49376. * @param scaleChildren Set this to true if children of the bone should be scaled.
  49377. */
  49378. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  49379. if (scaleChildren === void 0) { scaleChildren = false; }
  49380. if (this.animations[0] && !this.animations[0].isStopped()) {
  49381. if (!scaleChildren) {
  49382. this._negateScaleChildren.x = 1 / x;
  49383. this._negateScaleChildren.y = 1 / y;
  49384. this._negateScaleChildren.z = 1 / z;
  49385. }
  49386. this._syncScaleVector();
  49387. }
  49388. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  49389. };
  49390. /**
  49391. * Scale the bone on the x, y and z axes.
  49392. * @param x The amount to scale the bone on the x axis.
  49393. * @param x The amount to scale the bone on the y axis.
  49394. * @param z The amount to scale the bone on the z axis.
  49395. * @param scaleChildren Set this to true if children of the bone should be scaled.
  49396. */
  49397. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  49398. if (scaleChildren === void 0) { scaleChildren = false; }
  49399. var locMat = this.getLocalMatrix();
  49400. var origLocMat = Bone._tmpMats[0];
  49401. origLocMat.copyFrom(locMat);
  49402. var origLocMatInv = Bone._tmpMats[1];
  49403. origLocMatInv.copyFrom(origLocMat);
  49404. origLocMatInv.invert();
  49405. var scaleMat = Bone._tmpMats[2];
  49406. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  49407. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  49408. this._scaleVector.x *= x;
  49409. this._scaleVector.y *= y;
  49410. this._scaleVector.z *= z;
  49411. locMat.multiplyToRef(origLocMatInv, locMat);
  49412. locMat.multiplyToRef(scaleMat, locMat);
  49413. locMat.multiplyToRef(origLocMat, locMat);
  49414. var parent = this.getParent();
  49415. if (parent) {
  49416. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  49417. }
  49418. else {
  49419. this.getAbsoluteTransform().copyFrom(locMat);
  49420. }
  49421. var len = this.children.length;
  49422. scaleMat.invert();
  49423. for (var i = 0; i < len; i++) {
  49424. var child = this.children[i];
  49425. var cm = child.getLocalMatrix();
  49426. cm.multiplyToRef(scaleMat, cm);
  49427. var lm = child.getLocalMatrix();
  49428. lm.m[12] *= x;
  49429. lm.m[13] *= y;
  49430. lm.m[14] *= z;
  49431. }
  49432. this.computeAbsoluteTransforms();
  49433. if (scaleChildren) {
  49434. for (var i = 0; i < len; i++) {
  49435. this.children[i].scale(x, y, z, scaleChildren);
  49436. }
  49437. }
  49438. this.markAsDirty();
  49439. };
  49440. /**
  49441. * Set the yaw, pitch, and roll of the bone in local or world space.
  49442. * @param yaw The rotation of the bone on the y axis.
  49443. * @param pitch The rotation of the bone on the x axis.
  49444. * @param roll The rotation of the bone on the z axis.
  49445. * @param space The space that the axes of rotation are in.
  49446. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  49447. */
  49448. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  49449. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  49450. var rotMat = Bone._tmpMats[0];
  49451. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  49452. var rotMatInv = Bone._tmpMats[1];
  49453. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  49454. rotMatInv.multiplyToRef(rotMat, rotMat);
  49455. this._rotateWithMatrix(rotMat, space, mesh);
  49456. };
  49457. /**
  49458. * Rotate the bone on an axis in local or world space.
  49459. * @param axis The axis to rotate the bone on.
  49460. * @param amount The amount to rotate the bone.
  49461. * @param space The space that the axis is in.
  49462. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  49463. */
  49464. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  49465. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  49466. var rmat = Bone._tmpMats[0];
  49467. rmat.m[12] = 0;
  49468. rmat.m[13] = 0;
  49469. rmat.m[14] = 0;
  49470. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  49471. this._rotateWithMatrix(rmat, space, mesh);
  49472. };
  49473. /**
  49474. * Set the rotation of the bone to a particular axis angle in local or world space.
  49475. * @param axis The axis to rotate the bone on.
  49476. * @param angle The angle that the bone should be rotated to.
  49477. * @param space The space that the axis is in.
  49478. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  49479. */
  49480. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  49481. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  49482. var rotMat = Bone._tmpMats[0];
  49483. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  49484. var rotMatInv = Bone._tmpMats[1];
  49485. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  49486. rotMatInv.multiplyToRef(rotMat, rotMat);
  49487. this._rotateWithMatrix(rotMat, space, mesh);
  49488. };
  49489. /**
  49490. * Set the euler rotation of the bone in local of world space.
  49491. * @param rotation The euler rotation that the bone should be set to.
  49492. * @param space The space that the rotation is in.
  49493. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  49494. */
  49495. Bone.prototype.setRotation = function (rotation, space, mesh) {
  49496. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  49497. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  49498. };
  49499. /**
  49500. * Set the quaternion rotation of the bone in local of world space.
  49501. * @param quat The quaternion rotation that the bone should be set to.
  49502. * @param space The space that the rotation is in.
  49503. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  49504. */
  49505. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  49506. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  49507. var rotMatInv = Bone._tmpMats[0];
  49508. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  49509. var rotMat = Bone._tmpMats[1];
  49510. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  49511. rotMatInv.multiplyToRef(rotMat, rotMat);
  49512. this._rotateWithMatrix(rotMat, space, mesh);
  49513. };
  49514. /**
  49515. * Set the rotation matrix of the bone in local of world space.
  49516. * @param rotMat The rotation matrix that the bone should be set to.
  49517. * @param space The space that the rotation is in.
  49518. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  49519. */
  49520. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  49521. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  49522. var rotMatInv = Bone._tmpMats[0];
  49523. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  49524. var rotMat2 = Bone._tmpMats[1];
  49525. rotMat2.copyFrom(rotMat);
  49526. rotMatInv.multiplyToRef(rotMat, rotMat2);
  49527. this._rotateWithMatrix(rotMat2, space, mesh);
  49528. };
  49529. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  49530. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  49531. var lmat = this.getLocalMatrix();
  49532. var lx = lmat.m[12];
  49533. var ly = lmat.m[13];
  49534. var lz = lmat.m[14];
  49535. var parent = this.getParent();
  49536. var parentScale = Bone._tmpMats[3];
  49537. var parentScaleInv = Bone._tmpMats[4];
  49538. if (parent) {
  49539. if (space == BABYLON.Space.WORLD) {
  49540. if (mesh) {
  49541. parentScale.copyFrom(mesh.getWorldMatrix());
  49542. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  49543. }
  49544. else {
  49545. parentScale.copyFrom(parent.getAbsoluteTransform());
  49546. }
  49547. }
  49548. else {
  49549. parentScale = parent._scaleMatrix;
  49550. }
  49551. parentScaleInv.copyFrom(parentScale);
  49552. parentScaleInv.invert();
  49553. lmat.multiplyToRef(parentScale, lmat);
  49554. lmat.multiplyToRef(rmat, lmat);
  49555. lmat.multiplyToRef(parentScaleInv, lmat);
  49556. }
  49557. else {
  49558. if (space == BABYLON.Space.WORLD && mesh) {
  49559. parentScale.copyFrom(mesh.getWorldMatrix());
  49560. parentScaleInv.copyFrom(parentScale);
  49561. parentScaleInv.invert();
  49562. lmat.multiplyToRef(parentScale, lmat);
  49563. lmat.multiplyToRef(rmat, lmat);
  49564. lmat.multiplyToRef(parentScaleInv, lmat);
  49565. }
  49566. else {
  49567. lmat.multiplyToRef(rmat, lmat);
  49568. }
  49569. }
  49570. lmat.m[12] = lx;
  49571. lmat.m[13] = ly;
  49572. lmat.m[14] = lz;
  49573. this.computeAbsoluteTransforms();
  49574. this.markAsDirty();
  49575. };
  49576. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  49577. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  49578. if (space == BABYLON.Space.WORLD) {
  49579. var scaleMatrix = Bone._tmpMats[2];
  49580. scaleMatrix.copyFrom(this._scaleMatrix);
  49581. rotMatInv.copyFrom(this.getAbsoluteTransform());
  49582. if (mesh) {
  49583. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  49584. var meshScale = Bone._tmpMats[3];
  49585. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  49586. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  49587. }
  49588. rotMatInv.invert();
  49589. scaleMatrix.m[0] *= this._scalingDeterminant;
  49590. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  49591. }
  49592. else {
  49593. rotMatInv.copyFrom(this.getLocalMatrix());
  49594. rotMatInv.invert();
  49595. var scaleMatrix = Bone._tmpMats[2];
  49596. scaleMatrix.copyFrom(this._scaleMatrix);
  49597. if (this._parent) {
  49598. var pscaleMatrix = Bone._tmpMats[3];
  49599. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  49600. pscaleMatrix.invert();
  49601. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  49602. }
  49603. else {
  49604. scaleMatrix.m[0] *= this._scalingDeterminant;
  49605. }
  49606. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  49607. }
  49608. };
  49609. /**
  49610. * Get the scale of the bone
  49611. * @returns the scale of the bone
  49612. */
  49613. Bone.prototype.getScale = function () {
  49614. return this._scaleVector.clone();
  49615. };
  49616. /**
  49617. * Copy the scale of the bone to a vector3.
  49618. * @param result The vector3 to copy the scale to
  49619. */
  49620. Bone.prototype.getScaleToRef = function (result) {
  49621. result.copyFrom(this._scaleVector);
  49622. };
  49623. /**
  49624. * Get the position of the bone in local or world space.
  49625. * @param space The space that the returned position is in.
  49626. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  49627. * @returns The position of the bone
  49628. */
  49629. Bone.prototype.getPosition = function (space, mesh) {
  49630. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  49631. var pos = BABYLON.Vector3.Zero();
  49632. this.getPositionToRef(space, mesh, pos);
  49633. return pos;
  49634. };
  49635. /**
  49636. * Copy the position of the bone to a vector3 in local or world space.
  49637. * @param space The space that the returned position is in.
  49638. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  49639. * @param result The vector3 to copy the position to.
  49640. */
  49641. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  49642. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  49643. if (space == BABYLON.Space.LOCAL) {
  49644. var lm = this.getLocalMatrix();
  49645. result.x = lm.m[12];
  49646. result.y = lm.m[13];
  49647. result.z = lm.m[14];
  49648. }
  49649. else {
  49650. var wm;
  49651. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  49652. if (mesh) {
  49653. wm = mesh.getWorldMatrix();
  49654. }
  49655. this._skeleton.computeAbsoluteTransforms();
  49656. var tmat = Bone._tmpMats[0];
  49657. if (mesh) {
  49658. tmat.copyFrom(this.getAbsoluteTransform());
  49659. tmat.multiplyToRef(wm, tmat);
  49660. }
  49661. else {
  49662. tmat = this.getAbsoluteTransform();
  49663. }
  49664. result.x = tmat.m[12];
  49665. result.y = tmat.m[13];
  49666. result.z = tmat.m[14];
  49667. }
  49668. };
  49669. /**
  49670. * Get the absolute position of the bone (world space).
  49671. * @param mesh The mesh that this bone is attached to.
  49672. * @returns The absolute position of the bone
  49673. */
  49674. Bone.prototype.getAbsolutePosition = function (mesh) {
  49675. var pos = BABYLON.Vector3.Zero();
  49676. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  49677. return pos;
  49678. };
  49679. /**
  49680. * Copy the absolute position of the bone (world space) to the result param.
  49681. * @param mesh The mesh that this bone is attached to.
  49682. * @param result The vector3 to copy the absolute position to.
  49683. */
  49684. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  49685. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  49686. };
  49687. /**
  49688. * Compute the absolute transforms of this bone and its children.
  49689. */
  49690. Bone.prototype.computeAbsoluteTransforms = function () {
  49691. if (this._parent) {
  49692. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  49693. }
  49694. else {
  49695. this._absoluteTransform.copyFrom(this._localMatrix);
  49696. var poseMatrix = this._skeleton.getPoseMatrix();
  49697. if (poseMatrix) {
  49698. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  49699. }
  49700. }
  49701. var children = this.children;
  49702. var len = children.length;
  49703. for (var i = 0; i < len; i++) {
  49704. children[i].computeAbsoluteTransforms();
  49705. }
  49706. };
  49707. Bone.prototype._syncScaleVector = function () {
  49708. var lm = this.getLocalMatrix();
  49709. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  49710. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  49711. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  49712. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  49713. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  49714. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  49715. this._scaleVector.x = xs * Math.sqrt(xsq);
  49716. this._scaleVector.y = ys * Math.sqrt(ysq);
  49717. this._scaleVector.z = zs * Math.sqrt(zsq);
  49718. if (this._parent) {
  49719. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  49720. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  49721. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  49722. }
  49723. 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);
  49724. };
  49725. /**
  49726. * Get the world direction from an axis that is in the local space of the bone.
  49727. * @param localAxis The local direction that is used to compute the world direction.
  49728. * @param mesh The mesh that this bone is attached to.
  49729. * @returns The world direction
  49730. */
  49731. Bone.prototype.getDirection = function (localAxis, mesh) {
  49732. var result = BABYLON.Vector3.Zero();
  49733. this.getDirectionToRef(localAxis, mesh, result);
  49734. return result;
  49735. };
  49736. /**
  49737. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  49738. * @param localAxis The local direction that is used to compute the world direction.
  49739. * @param mesh The mesh that this bone is attached to.
  49740. * @param result The vector3 that the world direction will be copied to.
  49741. */
  49742. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  49743. var wm;
  49744. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  49745. if (mesh) {
  49746. wm = mesh.getWorldMatrix();
  49747. }
  49748. this._skeleton.computeAbsoluteTransforms();
  49749. var mat = Bone._tmpMats[0];
  49750. mat.copyFrom(this.getAbsoluteTransform());
  49751. if (mesh) {
  49752. mat.multiplyToRef(wm, mat);
  49753. }
  49754. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  49755. result.normalize();
  49756. };
  49757. /**
  49758. * Get the euler rotation of the bone in local or world space.
  49759. * @param space The space that the rotation should be in.
  49760. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  49761. * @returns The euler rotation
  49762. */
  49763. Bone.prototype.getRotation = function (space, mesh) {
  49764. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  49765. var result = BABYLON.Vector3.Zero();
  49766. this.getRotationToRef(space, mesh, result);
  49767. return result;
  49768. };
  49769. /**
  49770. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  49771. * @param space The space that the rotation should be in.
  49772. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  49773. * @param result The vector3 that the rotation should be copied to.
  49774. */
  49775. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  49776. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  49777. var quat = Bone._tmpQuat;
  49778. this.getRotationQuaternionToRef(space, mesh, quat);
  49779. quat.toEulerAnglesToRef(result);
  49780. };
  49781. /**
  49782. * Get the quaternion rotation of the bone in either local or world space.
  49783. * @param space The space that the rotation should be in.
  49784. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  49785. * @returns The quaternion rotation
  49786. */
  49787. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  49788. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  49789. var result = BABYLON.Quaternion.Identity();
  49790. this.getRotationQuaternionToRef(space, mesh, result);
  49791. return result;
  49792. };
  49793. /**
  49794. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  49795. * @param space The space that the rotation should be in.
  49796. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  49797. * @param result The quaternion that the rotation should be copied to.
  49798. */
  49799. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  49800. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  49801. if (space == BABYLON.Space.LOCAL) {
  49802. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  49803. }
  49804. else {
  49805. var mat = Bone._tmpMats[0];
  49806. var amat = this.getAbsoluteTransform();
  49807. if (mesh) {
  49808. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  49809. }
  49810. else {
  49811. mat.copyFrom(amat);
  49812. }
  49813. mat.m[0] *= this._scalingDeterminant;
  49814. mat.m[1] *= this._scalingDeterminant;
  49815. mat.m[2] *= this._scalingDeterminant;
  49816. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  49817. }
  49818. };
  49819. /**
  49820. * Get the rotation matrix of the bone in local or world space.
  49821. * @param space The space that the rotation should be in.
  49822. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  49823. * @returns The rotation matrix
  49824. */
  49825. Bone.prototype.getRotationMatrix = function (space, mesh) {
  49826. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  49827. var result = BABYLON.Matrix.Identity();
  49828. this.getRotationMatrixToRef(space, mesh, result);
  49829. return result;
  49830. };
  49831. /**
  49832. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  49833. * @param space The space that the rotation should be in.
  49834. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  49835. * @param result The quaternion that the rotation should be copied to.
  49836. */
  49837. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  49838. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  49839. if (space == BABYLON.Space.LOCAL) {
  49840. this.getLocalMatrix().getRotationMatrixToRef(result);
  49841. }
  49842. else {
  49843. var mat = Bone._tmpMats[0];
  49844. var amat = this.getAbsoluteTransform();
  49845. if (mesh) {
  49846. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  49847. }
  49848. else {
  49849. mat.copyFrom(amat);
  49850. }
  49851. mat.m[0] *= this._scalingDeterminant;
  49852. mat.m[1] *= this._scalingDeterminant;
  49853. mat.m[2] *= this._scalingDeterminant;
  49854. mat.getRotationMatrixToRef(result);
  49855. }
  49856. };
  49857. /**
  49858. * Get the world position of a point that is in the local space of the bone.
  49859. * @param position The local position
  49860. * @param mesh The mesh that this bone is attached to.
  49861. * @returns The world position
  49862. */
  49863. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  49864. var result = BABYLON.Vector3.Zero();
  49865. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  49866. return result;
  49867. };
  49868. /**
  49869. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  49870. * @param position The local position
  49871. * @param mesh The mesh that this bone is attached to.
  49872. * @param result The vector3 that the world position should be copied to.
  49873. */
  49874. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  49875. var wm;
  49876. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  49877. if (mesh) {
  49878. wm = mesh.getWorldMatrix();
  49879. }
  49880. this._skeleton.computeAbsoluteTransforms();
  49881. var tmat = Bone._tmpMats[0];
  49882. if (mesh) {
  49883. tmat.copyFrom(this.getAbsoluteTransform());
  49884. tmat.multiplyToRef(wm, tmat);
  49885. }
  49886. else {
  49887. tmat = this.getAbsoluteTransform();
  49888. }
  49889. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  49890. };
  49891. /**
  49892. * Get the local position of a point that is in world space.
  49893. * @param position The world position
  49894. * @param mesh The mesh that this bone is attached to.
  49895. * @returns The local position
  49896. */
  49897. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  49898. var result = BABYLON.Vector3.Zero();
  49899. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  49900. return result;
  49901. };
  49902. /**
  49903. * Get the local position of a point that is in world space and copy it to the result param.
  49904. * @param position The world position
  49905. * @param mesh The mesh that this bone is attached to.
  49906. * @param result The vector3 that the local position should be copied to.
  49907. */
  49908. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  49909. var wm;
  49910. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  49911. if (mesh) {
  49912. wm = mesh.getWorldMatrix();
  49913. }
  49914. this._skeleton.computeAbsoluteTransforms();
  49915. var tmat = Bone._tmpMats[0];
  49916. tmat.copyFrom(this.getAbsoluteTransform());
  49917. if (mesh) {
  49918. tmat.multiplyToRef(wm, tmat);
  49919. }
  49920. tmat.invert();
  49921. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  49922. };
  49923. return Bone;
  49924. }(BABYLON.Node));
  49925. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  49926. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  49927. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  49928. BABYLON.Bone = Bone;
  49929. })(BABYLON || (BABYLON = {}));
  49930. //# sourceMappingURL=babylon.bone.js.map
  49931. var BABYLON;
  49932. (function (BABYLON) {
  49933. var BoneIKController = (function () {
  49934. function BoneIKController(mesh, bone, options) {
  49935. this.targetPosition = BABYLON.Vector3.Zero();
  49936. this.poleTargetPosition = BABYLON.Vector3.Zero();
  49937. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  49938. this.poleAngle = 0;
  49939. this.slerpAmount = 1;
  49940. this._bone1Quat = BABYLON.Quaternion.Identity();
  49941. this._bone1Mat = BABYLON.Matrix.Identity();
  49942. this._bone2Ang = Math.PI;
  49943. this._maxAngle = Math.PI;
  49944. this._rightHandedSystem = false;
  49945. this._bendAxis = BABYLON.Vector3.Right();
  49946. this._slerping = false;
  49947. this._adjustRoll = 0;
  49948. this._bone2 = bone;
  49949. this._bone1 = bone.getParent();
  49950. this.mesh = mesh;
  49951. var bonePos = bone.getPosition();
  49952. if (bone.getAbsoluteTransform().determinant() > 0) {
  49953. this._rightHandedSystem = true;
  49954. this._bendAxis.x = 0;
  49955. this._bendAxis.y = 0;
  49956. this._bendAxis.z = -1;
  49957. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  49958. this._adjustRoll = Math.PI * .5;
  49959. this._bendAxis.z = 1;
  49960. }
  49961. }
  49962. if (this._bone1.length) {
  49963. var boneScale1 = this._bone1.getScale();
  49964. var boneScale2 = this._bone2.getScale();
  49965. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  49966. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  49967. }
  49968. else if (this._bone1.children[0]) {
  49969. mesh.computeWorldMatrix(true);
  49970. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  49971. var pos2 = this._bone2.getAbsolutePosition(mesh);
  49972. var pos3 = this._bone1.getAbsolutePosition(mesh);
  49973. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  49974. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  49975. }
  49976. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  49977. this.maxAngle = Math.PI;
  49978. if (options) {
  49979. if (options.targetMesh) {
  49980. this.targetMesh = options.targetMesh;
  49981. this.targetMesh.computeWorldMatrix(true);
  49982. }
  49983. if (options.poleTargetMesh) {
  49984. this.poleTargetMesh = options.poleTargetMesh;
  49985. this.poleTargetMesh.computeWorldMatrix(true);
  49986. }
  49987. else if (options.poleTargetBone) {
  49988. this.poleTargetBone = options.poleTargetBone;
  49989. }
  49990. else if (this._bone1.getParent()) {
  49991. this.poleTargetBone = this._bone1.getParent();
  49992. }
  49993. if (options.poleTargetLocalOffset) {
  49994. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  49995. }
  49996. if (options.poleAngle) {
  49997. this.poleAngle = options.poleAngle;
  49998. }
  49999. if (options.bendAxis) {
  50000. this._bendAxis.copyFrom(options.bendAxis);
  50001. }
  50002. if (options.maxAngle) {
  50003. this.maxAngle = options.maxAngle;
  50004. }
  50005. if (options.slerpAmount) {
  50006. this.slerpAmount = options.slerpAmount;
  50007. }
  50008. }
  50009. }
  50010. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  50011. get: function () {
  50012. return this._maxAngle;
  50013. },
  50014. set: function (value) {
  50015. this._setMaxAngle(value);
  50016. },
  50017. enumerable: true,
  50018. configurable: true
  50019. });
  50020. BoneIKController.prototype._setMaxAngle = function (ang) {
  50021. if (ang < 0) {
  50022. ang = 0;
  50023. }
  50024. if (ang > Math.PI || ang == undefined) {
  50025. ang = Math.PI;
  50026. }
  50027. this._maxAngle = ang;
  50028. var a = this._bone1Length;
  50029. var b = this._bone2Length;
  50030. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  50031. };
  50032. BoneIKController.prototype.update = function () {
  50033. var bone1 = this._bone1;
  50034. var target = this.targetPosition;
  50035. var poleTarget = this.poleTargetPosition;
  50036. var mat1 = BoneIKController._tmpMats[0];
  50037. var mat2 = BoneIKController._tmpMats[1];
  50038. if (this.targetMesh) {
  50039. target.copyFrom(this.targetMesh.getAbsolutePosition());
  50040. }
  50041. if (this.poleTargetBone) {
  50042. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  50043. }
  50044. else if (this.poleTargetMesh) {
  50045. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  50046. }
  50047. var bonePos = BoneIKController._tmpVecs[0];
  50048. var zaxis = BoneIKController._tmpVecs[1];
  50049. var xaxis = BoneIKController._tmpVecs[2];
  50050. var yaxis = BoneIKController._tmpVecs[3];
  50051. var upAxis = BoneIKController._tmpVecs[4];
  50052. var _tmpQuat = BoneIKController._tmpQuat;
  50053. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  50054. poleTarget.subtractToRef(bonePos, upAxis);
  50055. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  50056. upAxis.y = 1;
  50057. }
  50058. else {
  50059. upAxis.normalize();
  50060. }
  50061. target.subtractToRef(bonePos, yaxis);
  50062. yaxis.normalize();
  50063. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  50064. zaxis.normalize();
  50065. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  50066. xaxis.normalize();
  50067. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  50068. var a = this._bone1Length;
  50069. var b = this._bone2Length;
  50070. var c = BABYLON.Vector3.Distance(bonePos, target);
  50071. if (this._maxReach > 0) {
  50072. c = Math.min(this._maxReach, c);
  50073. }
  50074. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  50075. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  50076. if (acosa > 1) {
  50077. acosa = 1;
  50078. }
  50079. if (acosb > 1) {
  50080. acosb = 1;
  50081. }
  50082. if (acosa < -1) {
  50083. acosa = -1;
  50084. }
  50085. if (acosb < -1) {
  50086. acosb = -1;
  50087. }
  50088. var angA = Math.acos(acosa);
  50089. var angB = Math.acos(acosb);
  50090. var angC = -angA - angB;
  50091. if (this._rightHandedSystem) {
  50092. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  50093. mat2.multiplyToRef(mat1, mat1);
  50094. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  50095. mat2.multiplyToRef(mat1, mat1);
  50096. }
  50097. else {
  50098. var _tmpVec = BoneIKController._tmpVecs[5];
  50099. _tmpVec.copyFrom(this._bendAxis);
  50100. _tmpVec.x *= -1;
  50101. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  50102. mat2.multiplyToRef(mat1, mat1);
  50103. }
  50104. if (this.poleAngle) {
  50105. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  50106. mat1.multiplyToRef(mat2, mat1);
  50107. }
  50108. if (this.slerpAmount < 1) {
  50109. if (!this._slerping) {
  50110. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  50111. }
  50112. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  50113. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  50114. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  50115. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  50116. this._slerping = true;
  50117. }
  50118. else {
  50119. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  50120. this._bone1Mat.copyFrom(mat1);
  50121. this._slerping = false;
  50122. }
  50123. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  50124. this._bone2Ang = angC;
  50125. };
  50126. return BoneIKController;
  50127. }());
  50128. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  50129. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  50130. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  50131. BABYLON.BoneIKController = BoneIKController;
  50132. })(BABYLON || (BABYLON = {}));
  50133. //# sourceMappingURL=babylon.boneIKController.js.map
  50134. var BABYLON;
  50135. (function (BABYLON) {
  50136. var BoneLookController = (function () {
  50137. /**
  50138. * Create a BoneLookController
  50139. * @param mesh the mesh that the bone belongs to
  50140. * @param bone the bone that will be looking to the target
  50141. * @param target the target Vector3 to look at
  50142. * @param settings optional settings:
  50143. * - maxYaw: the maximum angle the bone will yaw to
  50144. * - minYaw: the minimum angle the bone will yaw to
  50145. * - maxPitch: the maximum angle the bone will pitch to
  50146. * - minPitch: the minimum angle the bone will yaw to
  50147. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  50148. * - upAxis: the up axis of the coordinate system
  50149. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  50150. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  50151. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  50152. * - adjustYaw: used to make an adjustment to the yaw of the bone
  50153. * - adjustPitch: used to make an adjustment to the pitch of the bone
  50154. * - adjustRoll: used to make an adjustment to the roll of the bone
  50155. **/
  50156. function BoneLookController(mesh, bone, target, options) {
  50157. /**
  50158. * The up axis of the coordinate system that is used when the bone is rotated.
  50159. */
  50160. this.upAxis = BABYLON.Vector3.Up();
  50161. /**
  50162. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  50163. */
  50164. this.upAxisSpace = BABYLON.Space.LOCAL;
  50165. /**
  50166. * Used to make an adjustment to the yaw of the bone.
  50167. */
  50168. this.adjustYaw = 0;
  50169. /**
  50170. * Used to make an adjustment to the pitch of the bone.
  50171. */
  50172. this.adjustPitch = 0;
  50173. /**
  50174. * Used to make an adjustment to the roll of the bone.
  50175. */
  50176. this.adjustRoll = 0;
  50177. /**
  50178. * 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).
  50179. */
  50180. this.slerpAmount = 1;
  50181. this._boneQuat = BABYLON.Quaternion.Identity();
  50182. this._slerping = false;
  50183. this._firstFrameSkipped = false;
  50184. this._fowardAxis = BABYLON.Vector3.Forward();
  50185. this.mesh = mesh;
  50186. this.bone = bone;
  50187. this.target = target;
  50188. if (options) {
  50189. if (options.adjustYaw) {
  50190. this.adjustYaw = options.adjustYaw;
  50191. }
  50192. if (options.adjustPitch) {
  50193. this.adjustPitch = options.adjustPitch;
  50194. }
  50195. if (options.adjustRoll) {
  50196. this.adjustRoll = options.adjustRoll;
  50197. }
  50198. if (options.maxYaw != null) {
  50199. this.maxYaw = options.maxYaw;
  50200. }
  50201. else {
  50202. this.maxYaw = Math.PI;
  50203. }
  50204. if (options.minYaw != null) {
  50205. this.minYaw = options.minYaw;
  50206. }
  50207. else {
  50208. this.minYaw = -Math.PI;
  50209. }
  50210. if (options.maxPitch != null) {
  50211. this.maxPitch = options.maxPitch;
  50212. }
  50213. else {
  50214. this.maxPitch = Math.PI;
  50215. }
  50216. if (options.minPitch != null) {
  50217. this.minPitch = options.minPitch;
  50218. }
  50219. else {
  50220. this.minPitch = -Math.PI;
  50221. }
  50222. if (options.slerpAmount != null) {
  50223. this.slerpAmount = options.slerpAmount;
  50224. }
  50225. if (options.upAxis != null) {
  50226. this.upAxis = options.upAxis;
  50227. }
  50228. if (options.upAxisSpace != null) {
  50229. this.upAxisSpace = options.upAxisSpace;
  50230. }
  50231. if (options.yawAxis != null || options.pitchAxis != null) {
  50232. var newYawAxis = BABYLON.Axis.Y;
  50233. var newPitchAxis = BABYLON.Axis.X;
  50234. if (options.yawAxis != null) {
  50235. newYawAxis = options.yawAxis.clone();
  50236. newYawAxis.normalize();
  50237. }
  50238. if (options.pitchAxis != null) {
  50239. newPitchAxis = options.pitchAxis.clone();
  50240. newPitchAxis.normalize();
  50241. }
  50242. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  50243. this._transformYawPitch = BABYLON.Matrix.Identity();
  50244. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  50245. this._transformYawPitchInv = this._transformYawPitch.clone();
  50246. this._transformYawPitch.invert();
  50247. }
  50248. }
  50249. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  50250. this.upAxisSpace = BABYLON.Space.LOCAL;
  50251. }
  50252. }
  50253. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  50254. /**
  50255. * Get/set the minimum yaw angle that the bone can look to.
  50256. */
  50257. get: function () {
  50258. return this._minYaw;
  50259. },
  50260. set: function (value) {
  50261. this._minYaw = value;
  50262. this._minYawSin = Math.sin(value);
  50263. this._minYawCos = Math.cos(value);
  50264. if (this._maxYaw != null) {
  50265. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  50266. this._yawRange = this._maxYaw - this._minYaw;
  50267. }
  50268. },
  50269. enumerable: true,
  50270. configurable: true
  50271. });
  50272. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  50273. /**
  50274. * Get/set the maximum yaw angle that the bone can look to.
  50275. */
  50276. get: function () {
  50277. return this._maxYaw;
  50278. },
  50279. set: function (value) {
  50280. this._maxYaw = value;
  50281. this._maxYawSin = Math.sin(value);
  50282. this._maxYawCos = Math.cos(value);
  50283. if (this._minYaw != null) {
  50284. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  50285. this._yawRange = this._maxYaw - this._minYaw;
  50286. }
  50287. },
  50288. enumerable: true,
  50289. configurable: true
  50290. });
  50291. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  50292. /**
  50293. * Get/set the minimum pitch angle that the bone can look to.
  50294. */
  50295. get: function () {
  50296. return this._minPitch;
  50297. },
  50298. set: function (value) {
  50299. this._minPitch = value;
  50300. this._minPitchTan = Math.tan(value);
  50301. },
  50302. enumerable: true,
  50303. configurable: true
  50304. });
  50305. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  50306. /**
  50307. * Get/set the maximum pitch angle that the bone can look to.
  50308. */
  50309. get: function () {
  50310. return this._maxPitch;
  50311. },
  50312. set: function (value) {
  50313. this._maxPitch = value;
  50314. this._maxPitchTan = Math.tan(value);
  50315. },
  50316. enumerable: true,
  50317. configurable: true
  50318. });
  50319. /**
  50320. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  50321. */
  50322. BoneLookController.prototype.update = function () {
  50323. //skip the first frame when slerping so that the mesh rotation is correct
  50324. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  50325. this._firstFrameSkipped = true;
  50326. return;
  50327. }
  50328. var bone = this.bone;
  50329. var bonePos = BoneLookController._tmpVecs[0];
  50330. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  50331. var target = this.target;
  50332. var _tmpMat1 = BoneLookController._tmpMats[0];
  50333. var _tmpMat2 = BoneLookController._tmpMats[1];
  50334. var mesh = this.mesh;
  50335. var parentBone = bone.getParent();
  50336. var upAxis = BoneLookController._tmpVecs[1];
  50337. upAxis.copyFrom(this.upAxis);
  50338. if (this.upAxisSpace == BABYLON.Space.BONE) {
  50339. if (this._transformYawPitch) {
  50340. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  50341. }
  50342. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  50343. }
  50344. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  50345. mesh.getDirectionToRef(upAxis, upAxis);
  50346. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  50347. upAxis.normalize();
  50348. }
  50349. }
  50350. var checkYaw = false;
  50351. var checkPitch = false;
  50352. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  50353. checkYaw = true;
  50354. }
  50355. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  50356. checkPitch = true;
  50357. }
  50358. if (checkYaw || checkPitch) {
  50359. var spaceMat = BoneLookController._tmpMats[2];
  50360. var spaceMatInv = BoneLookController._tmpMats[3];
  50361. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1) {
  50362. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  50363. }
  50364. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  50365. spaceMat.copyFrom(mesh.getWorldMatrix());
  50366. }
  50367. else {
  50368. var forwardAxis = BoneLookController._tmpVecs[2];
  50369. forwardAxis.copyFrom(this._fowardAxis);
  50370. if (this._transformYawPitch) {
  50371. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  50372. }
  50373. if (parentBone) {
  50374. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  50375. }
  50376. else {
  50377. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  50378. }
  50379. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  50380. rightAxis.normalize();
  50381. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  50382. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  50383. }
  50384. spaceMat.invertToRef(spaceMatInv);
  50385. var xzlen;
  50386. if (checkPitch) {
  50387. var localTarget = BoneLookController._tmpVecs[3];
  50388. target.subtractToRef(bonePos, localTarget);
  50389. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  50390. var xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  50391. var pitch = Math.atan2(localTarget.y, xzlen);
  50392. var newPitch = pitch;
  50393. if (pitch > this._maxPitch) {
  50394. localTarget.y = this._maxPitchTan * xzlen;
  50395. newPitch = this._maxPitch;
  50396. }
  50397. else if (pitch < this._minPitch) {
  50398. localTarget.y = this._minPitchTan * xzlen;
  50399. newPitch = this._minPitch;
  50400. }
  50401. if (pitch != newPitch) {
  50402. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  50403. localTarget.addInPlace(bonePos);
  50404. target = localTarget;
  50405. }
  50406. }
  50407. if (checkYaw) {
  50408. var localTarget = BoneLookController._tmpVecs[4];
  50409. target.subtractToRef(bonePos, localTarget);
  50410. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  50411. var yaw = Math.atan2(localTarget.x, localTarget.z);
  50412. var newYaw = yaw;
  50413. if (yaw > this._maxYaw || yaw < this._minYaw) {
  50414. if (xzlen == null) {
  50415. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  50416. }
  50417. if (this._yawRange > Math.PI) {
  50418. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  50419. localTarget.z = this._maxYawCos * xzlen;
  50420. localTarget.x = this._maxYawSin * xzlen;
  50421. newYaw = this._maxYaw;
  50422. }
  50423. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  50424. localTarget.z = this._minYawCos * xzlen;
  50425. localTarget.x = this._minYawSin * xzlen;
  50426. newYaw = this._minYaw;
  50427. }
  50428. }
  50429. else {
  50430. if (yaw > this._maxYaw) {
  50431. localTarget.z = this._maxYawCos * xzlen;
  50432. localTarget.x = this._maxYawSin * xzlen;
  50433. newYaw = this._maxYaw;
  50434. }
  50435. else if (yaw < this._minYaw) {
  50436. localTarget.z = this._minYawCos * xzlen;
  50437. localTarget.x = this._minYawSin * xzlen;
  50438. newYaw = this._minYaw;
  50439. }
  50440. }
  50441. }
  50442. if (this._slerping && this._yawRange > Math.PI) {
  50443. //are we going to be crossing into the min/max region?
  50444. var boneFwd = BoneLookController._tmpVecs[8];
  50445. boneFwd.copyFrom(BABYLON.Axis.Z);
  50446. if (this._transformYawPitch) {
  50447. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  50448. }
  50449. var boneRotMat = BABYLON.BoneLookController._tmpMats[4];
  50450. this._boneQuat.toRotationMatrix(boneRotMat);
  50451. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  50452. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  50453. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  50454. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  50455. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  50456. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  50457. if (angBtwTar > angBtwMidYaw) {
  50458. if (xzlen == null) {
  50459. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  50460. }
  50461. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  50462. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  50463. if (angBtwMin < angBtwMax) {
  50464. newYaw = boneYaw + Math.PI * .75;
  50465. localTarget.z = Math.cos(newYaw) * xzlen;
  50466. localTarget.x = Math.sin(newYaw) * xzlen;
  50467. }
  50468. else {
  50469. newYaw = boneYaw - Math.PI * .75;
  50470. localTarget.z = Math.cos(newYaw) * xzlen;
  50471. localTarget.x = Math.sin(newYaw) * xzlen;
  50472. }
  50473. }
  50474. }
  50475. if (yaw != newYaw) {
  50476. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  50477. localTarget.addInPlace(bonePos);
  50478. target = localTarget;
  50479. }
  50480. }
  50481. }
  50482. var zaxis = BoneLookController._tmpVecs[5];
  50483. var xaxis = BoneLookController._tmpVecs[6];
  50484. var yaxis = BoneLookController._tmpVecs[7];
  50485. var _tmpQuat = BoneLookController._tmpQuat;
  50486. target.subtractToRef(bonePos, zaxis);
  50487. zaxis.normalize();
  50488. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  50489. xaxis.normalize();
  50490. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  50491. yaxis.normalize();
  50492. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  50493. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  50494. return;
  50495. }
  50496. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  50497. return;
  50498. }
  50499. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  50500. return;
  50501. }
  50502. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  50503. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  50504. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  50505. }
  50506. if (this.slerpAmount < 1) {
  50507. if (!this._slerping) {
  50508. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  50509. }
  50510. if (this._transformYawPitch) {
  50511. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  50512. }
  50513. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  50514. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  50515. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  50516. this._slerping = true;
  50517. }
  50518. else {
  50519. if (this._transformYawPitch) {
  50520. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  50521. }
  50522. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  50523. this._slerping = false;
  50524. }
  50525. };
  50526. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  50527. var angDiff = ang2 - ang1;
  50528. angDiff %= Math.PI * 2;
  50529. if (angDiff > Math.PI) {
  50530. angDiff -= Math.PI * 2;
  50531. }
  50532. else if (angDiff < -Math.PI) {
  50533. angDiff += Math.PI * 2;
  50534. }
  50535. return angDiff;
  50536. };
  50537. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  50538. ang1 %= (2 * Math.PI);
  50539. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  50540. ang2 %= (2 * Math.PI);
  50541. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  50542. var ab = 0;
  50543. if (ang1 < ang2) {
  50544. ab = ang2 - ang1;
  50545. }
  50546. else {
  50547. ab = ang1 - ang2;
  50548. }
  50549. if (ab > Math.PI) {
  50550. ab = Math.PI * 2 - ab;
  50551. }
  50552. return ab;
  50553. };
  50554. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  50555. ang %= (2 * Math.PI);
  50556. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  50557. ang1 %= (2 * Math.PI);
  50558. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  50559. ang2 %= (2 * Math.PI);
  50560. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  50561. if (ang1 < ang2) {
  50562. if (ang > ang1 && ang < ang2) {
  50563. return true;
  50564. }
  50565. }
  50566. else {
  50567. if (ang > ang2 && ang < ang1) {
  50568. return true;
  50569. }
  50570. }
  50571. return false;
  50572. };
  50573. return BoneLookController;
  50574. }());
  50575. 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()];
  50576. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  50577. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  50578. BABYLON.BoneLookController = BoneLookController;
  50579. })(BABYLON || (BABYLON = {}));
  50580. //# sourceMappingURL=babylon.boneLookController.js.map
  50581. var BABYLON;
  50582. (function (BABYLON) {
  50583. var Skeleton = (function () {
  50584. function Skeleton(name, id, scene) {
  50585. this.name = name;
  50586. this.id = id;
  50587. this.bones = new Array();
  50588. this.needInitialSkinMatrix = false;
  50589. this._isDirty = true;
  50590. this._meshesWithPoseMatrix = new Array();
  50591. this._identity = BABYLON.Matrix.Identity();
  50592. this._ranges = {};
  50593. this._lastAbsoluteTransformsUpdateId = -1;
  50594. // Events
  50595. /**
  50596. * An event triggered before computing the skeleton's matrices
  50597. * @type {BABYLON.Observable}
  50598. */
  50599. this.onBeforeComputeObservable = new BABYLON.Observable();
  50600. this.bones = [];
  50601. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  50602. scene.skeletons.push(this);
  50603. //make sure it will recalculate the matrix next time prepare is called.
  50604. this._isDirty = true;
  50605. }
  50606. // Members
  50607. Skeleton.prototype.getTransformMatrices = function (mesh) {
  50608. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  50609. return mesh._bonesTransformMatrices;
  50610. }
  50611. if (!this._transformMatrices) {
  50612. this.prepare();
  50613. }
  50614. return this._transformMatrices;
  50615. };
  50616. Skeleton.prototype.getScene = function () {
  50617. return this._scene;
  50618. };
  50619. // Methods
  50620. /**
  50621. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  50622. */
  50623. Skeleton.prototype.toString = function (fullDetails) {
  50624. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  50625. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  50626. if (fullDetails) {
  50627. ret += ", Ranges: {";
  50628. var first = true;
  50629. for (var name_1 in this._ranges) {
  50630. if (first) {
  50631. ret += ", ";
  50632. first = false;
  50633. }
  50634. ret += name_1;
  50635. }
  50636. ret += "}";
  50637. }
  50638. return ret;
  50639. };
  50640. /**
  50641. * Get bone's index searching by name
  50642. * @param {string} name is bone's name to search for
  50643. * @return {number} Indice of the bone. Returns -1 if not found
  50644. */
  50645. Skeleton.prototype.getBoneIndexByName = function (name) {
  50646. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  50647. if (this.bones[boneIndex].name === name) {
  50648. return boneIndex;
  50649. }
  50650. }
  50651. return -1;
  50652. };
  50653. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  50654. // check name not already in use
  50655. if (!this._ranges[name]) {
  50656. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  50657. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  50658. if (this.bones[i].animations[0]) {
  50659. this.bones[i].animations[0].createRange(name, from, to);
  50660. }
  50661. }
  50662. }
  50663. };
  50664. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  50665. if (deleteFrames === void 0) { deleteFrames = true; }
  50666. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  50667. if (this.bones[i].animations[0]) {
  50668. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  50669. }
  50670. }
  50671. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  50672. };
  50673. Skeleton.prototype.getAnimationRange = function (name) {
  50674. return this._ranges[name];
  50675. };
  50676. /**
  50677. * Returns as an Array, all AnimationRanges defined on this skeleton
  50678. */
  50679. Skeleton.prototype.getAnimationRanges = function () {
  50680. var animationRanges = [];
  50681. var name;
  50682. var i = 0;
  50683. for (name in this._ranges) {
  50684. animationRanges[i] = this._ranges[name];
  50685. i++;
  50686. }
  50687. return animationRanges;
  50688. };
  50689. /**
  50690. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  50691. */
  50692. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  50693. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  50694. if (this._ranges[name] || !source.getAnimationRange(name)) {
  50695. return false;
  50696. }
  50697. var ret = true;
  50698. var frameOffset = this._getHighestAnimationFrame() + 1;
  50699. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  50700. var boneDict = {};
  50701. var sourceBones = source.bones;
  50702. var nBones;
  50703. var i;
  50704. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  50705. boneDict[sourceBones[i].name] = sourceBones[i];
  50706. }
  50707. if (this.bones.length !== sourceBones.length) {
  50708. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  50709. ret = false;
  50710. }
  50711. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  50712. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  50713. var boneName = this.bones[i].name;
  50714. var sourceBone = boneDict[boneName];
  50715. if (sourceBone) {
  50716. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  50717. }
  50718. else {
  50719. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  50720. ret = false;
  50721. }
  50722. }
  50723. // do not call createAnimationRange(), since it also is done to bones, which was already done
  50724. var range = source.getAnimationRange(name);
  50725. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  50726. return ret;
  50727. };
  50728. Skeleton.prototype.returnToRest = function () {
  50729. for (var index = 0; index < this.bones.length; index++) {
  50730. this.bones[index].returnToRest();
  50731. }
  50732. };
  50733. Skeleton.prototype._getHighestAnimationFrame = function () {
  50734. var ret = 0;
  50735. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  50736. if (this.bones[i].animations[0]) {
  50737. var highest = this.bones[i].animations[0].getHighestFrame();
  50738. if (ret < highest) {
  50739. ret = highest;
  50740. }
  50741. }
  50742. }
  50743. return ret;
  50744. };
  50745. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  50746. var range = this.getAnimationRange(name);
  50747. if (!range) {
  50748. return null;
  50749. }
  50750. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  50751. };
  50752. Skeleton.prototype._markAsDirty = function () {
  50753. this._isDirty = true;
  50754. };
  50755. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  50756. this._meshesWithPoseMatrix.push(mesh);
  50757. };
  50758. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  50759. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  50760. if (index > -1) {
  50761. this._meshesWithPoseMatrix.splice(index, 1);
  50762. }
  50763. };
  50764. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  50765. this.onBeforeComputeObservable.notifyObservers(this);
  50766. for (var index = 0; index < this.bones.length; index++) {
  50767. var bone = this.bones[index];
  50768. var parentBone = bone.getParent();
  50769. if (parentBone) {
  50770. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  50771. }
  50772. else {
  50773. if (initialSkinMatrix) {
  50774. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  50775. }
  50776. else {
  50777. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  50778. }
  50779. }
  50780. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
  50781. }
  50782. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  50783. };
  50784. Skeleton.prototype.prepare = function () {
  50785. if (!this._isDirty) {
  50786. return;
  50787. }
  50788. if (this.needInitialSkinMatrix) {
  50789. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  50790. var mesh = this._meshesWithPoseMatrix[index];
  50791. var poseMatrix = mesh.getPoseMatrix();
  50792. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  50793. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  50794. }
  50795. if (this._synchronizedWithMesh !== mesh) {
  50796. this._synchronizedWithMesh = mesh;
  50797. // Prepare bones
  50798. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  50799. var bone = this.bones[boneIndex];
  50800. if (!bone.getParent()) {
  50801. var matrix = bone.getBaseMatrix();
  50802. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  50803. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  50804. }
  50805. }
  50806. }
  50807. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  50808. }
  50809. }
  50810. else {
  50811. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  50812. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  50813. }
  50814. this._computeTransformMatrices(this._transformMatrices, null);
  50815. }
  50816. this._isDirty = false;
  50817. this._scene._activeBones.addCount(this.bones.length, false);
  50818. };
  50819. Skeleton.prototype.getAnimatables = function () {
  50820. if (!this._animatables || this._animatables.length !== this.bones.length) {
  50821. this._animatables = [];
  50822. for (var index = 0; index < this.bones.length; index++) {
  50823. this._animatables.push(this.bones[index]);
  50824. }
  50825. }
  50826. return this._animatables;
  50827. };
  50828. Skeleton.prototype.clone = function (name, id) {
  50829. var result = new Skeleton(name, id || name, this._scene);
  50830. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  50831. for (var index = 0; index < this.bones.length; index++) {
  50832. var source = this.bones[index];
  50833. var parentBone = null;
  50834. if (source.getParent()) {
  50835. var parentIndex = this.bones.indexOf(source.getParent());
  50836. parentBone = result.bones[parentIndex];
  50837. }
  50838. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  50839. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  50840. }
  50841. if (this._ranges) {
  50842. result._ranges = {};
  50843. for (var rangeName in this._ranges) {
  50844. result._ranges[rangeName] = this._ranges[rangeName].clone();
  50845. }
  50846. }
  50847. this._isDirty = true;
  50848. return result;
  50849. };
  50850. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  50851. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  50852. this.bones.forEach(function (bone) {
  50853. bone.animations.forEach(function (animation) {
  50854. animation.enableBlending = true;
  50855. animation.blendingSpeed = blendingSpeed;
  50856. });
  50857. });
  50858. };
  50859. Skeleton.prototype.dispose = function () {
  50860. this._meshesWithPoseMatrix = [];
  50861. // Animations
  50862. this.getScene().stopAnimation(this);
  50863. // Remove from scene
  50864. this.getScene().removeSkeleton(this);
  50865. };
  50866. Skeleton.prototype.serialize = function () {
  50867. var serializationObject = {};
  50868. serializationObject.name = this.name;
  50869. serializationObject.id = this.id;
  50870. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  50871. serializationObject.bones = [];
  50872. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  50873. for (var index = 0; index < this.bones.length; index++) {
  50874. var bone = this.bones[index];
  50875. var serializedBone = {
  50876. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  50877. name: bone.name,
  50878. matrix: bone.getBaseMatrix().toArray(),
  50879. rest: bone.getRestPose().toArray()
  50880. };
  50881. serializationObject.bones.push(serializedBone);
  50882. if (bone.length) {
  50883. serializedBone.length = bone.length;
  50884. }
  50885. if (bone.animations && bone.animations.length > 0) {
  50886. serializedBone.animation = bone.animations[0].serialize();
  50887. }
  50888. serializationObject.ranges = [];
  50889. for (var name in this._ranges) {
  50890. var range = {};
  50891. range.name = name;
  50892. range.from = this._ranges[name].from;
  50893. range.to = this._ranges[name].to;
  50894. serializationObject.ranges.push(range);
  50895. }
  50896. }
  50897. return serializationObject;
  50898. };
  50899. Skeleton.Parse = function (parsedSkeleton, scene) {
  50900. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  50901. if (parsedSkeleton.dimensionsAtRest) {
  50902. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  50903. }
  50904. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  50905. var index;
  50906. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  50907. var parsedBone = parsedSkeleton.bones[index];
  50908. var parentBone = null;
  50909. if (parsedBone.parentBoneIndex > -1) {
  50910. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  50911. }
  50912. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  50913. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  50914. if (parsedBone.length) {
  50915. bone.length = parsedBone.length;
  50916. }
  50917. if (parsedBone.animation) {
  50918. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  50919. }
  50920. }
  50921. // placed after bones, so createAnimationRange can cascade down
  50922. if (parsedSkeleton.ranges) {
  50923. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  50924. var data = parsedSkeleton.ranges[index];
  50925. skeleton.createAnimationRange(data.name, data.from, data.to);
  50926. }
  50927. }
  50928. return skeleton;
  50929. };
  50930. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  50931. if (forceUpdate === void 0) { forceUpdate = false; }
  50932. var renderId = this._scene.getRenderId();
  50933. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  50934. this.bones[0].computeAbsoluteTransforms();
  50935. this._lastAbsoluteTransformsUpdateId = renderId;
  50936. }
  50937. };
  50938. Skeleton.prototype.getPoseMatrix = function () {
  50939. var poseMatrix;
  50940. if (this._meshesWithPoseMatrix.length > 0) {
  50941. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  50942. }
  50943. return poseMatrix;
  50944. };
  50945. return Skeleton;
  50946. }());
  50947. BABYLON.Skeleton = Skeleton;
  50948. })(BABYLON || (BABYLON = {}));
  50949. //# sourceMappingURL=babylon.skeleton.js.map
  50950. var BABYLON;
  50951. (function (BABYLON) {
  50952. var Internals;
  50953. (function (Internals) {
  50954. var FileFaceOrientation = (function () {
  50955. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  50956. this.name = name;
  50957. this.worldAxisForNormal = worldAxisForNormal;
  50958. this.worldAxisForFileX = worldAxisForFileX;
  50959. this.worldAxisForFileY = worldAxisForFileY;
  50960. }
  50961. return FileFaceOrientation;
  50962. }());
  50963. ;
  50964. /**
  50965. * Helper class dealing with the extraction of spherical polynomial dataArray
  50966. * from a cube map.
  50967. */
  50968. var CubeMapToSphericalPolynomialTools = (function () {
  50969. function CubeMapToSphericalPolynomialTools() {
  50970. }
  50971. /**
  50972. * Converts a cubemap to the according Spherical Polynomial data.
  50973. * This extracts the first 3 orders only as they are the only one used in the lighting.
  50974. *
  50975. * @param cubeInfo The Cube map to extract the information from.
  50976. * @return The Spherical Polynomial data.
  50977. */
  50978. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  50979. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  50980. var totalSolidAngle = 0.0;
  50981. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  50982. var du = 2.0 / cubeInfo.size;
  50983. var dv = du;
  50984. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  50985. var minUV = du * 0.5 - 1.0;
  50986. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  50987. var fileFace = this.FileFaces[faceIndex];
  50988. var dataArray = cubeInfo[fileFace.name];
  50989. var v = minUV;
  50990. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  50991. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  50992. // Because SP is still linear, so summation is fine in that basis.
  50993. for (var y = 0; y < cubeInfo.size; y++) {
  50994. var u = minUV;
  50995. for (var x = 0; x < cubeInfo.size; x++) {
  50996. // World direction (not normalised)
  50997. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  50998. worldDirection.normalize();
  50999. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  51000. if (1) {
  51001. var r = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0];
  51002. var g = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1];
  51003. var b = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2];
  51004. var color = new BABYLON.Color3(r, g, b);
  51005. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  51006. }
  51007. else {
  51008. if (faceIndex == 0) {
  51009. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  51010. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  51011. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  51012. }
  51013. else if (faceIndex == 1) {
  51014. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  51015. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  51016. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  51017. }
  51018. else if (faceIndex == 2) {
  51019. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  51020. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  51021. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  51022. }
  51023. else if (faceIndex == 3) {
  51024. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  51025. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  51026. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  51027. }
  51028. else if (faceIndex == 4) {
  51029. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  51030. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  51031. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  51032. }
  51033. else if (faceIndex == 5) {
  51034. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  51035. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  51036. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  51037. }
  51038. 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]);
  51039. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  51040. }
  51041. totalSolidAngle += deltaSolidAngle;
  51042. u += du;
  51043. }
  51044. v += dv;
  51045. }
  51046. }
  51047. var correctSolidAngle = 4.0 * Math.PI; // Solid angle for entire sphere is 4*pi
  51048. var correction = correctSolidAngle / totalSolidAngle;
  51049. sphericalHarmonics.scale(correction);
  51050. // Additionally scale by pi -- audit needed
  51051. sphericalHarmonics.scale(1.0 / Math.PI);
  51052. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  51053. };
  51054. return CubeMapToSphericalPolynomialTools;
  51055. }());
  51056. CubeMapToSphericalPolynomialTools.FileFaces = [
  51057. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  51058. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  51059. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  51060. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  51061. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  51062. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  51063. ];
  51064. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  51065. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  51066. })(BABYLON || (BABYLON = {}));
  51067. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  51068. var BABYLON;
  51069. (function (BABYLON) {
  51070. var Internals;
  51071. (function (Internals) {
  51072. /**
  51073. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  51074. */
  51075. var PanoramaToCubeMapTools = (function () {
  51076. function PanoramaToCubeMapTools() {
  51077. }
  51078. /**
  51079. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  51080. *
  51081. * @param float32Array The source data.
  51082. * @param inputWidth The width of the input panorama.
  51083. * @param inputhHeight The height of the input panorama.
  51084. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  51085. * @return The cubemap data
  51086. */
  51087. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  51088. if (!float32Array) {
  51089. throw "ConvertPanoramaToCubemap: input cannot be null";
  51090. }
  51091. if (float32Array.length != inputWidth * inputHeight * 3) {
  51092. throw "ConvertPanoramaToCubemap: input size is wrong";
  51093. }
  51094. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  51095. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  51096. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  51097. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  51098. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  51099. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  51100. return {
  51101. front: textureFront,
  51102. back: textureBack,
  51103. left: textureLeft,
  51104. right: textureRight,
  51105. up: textureUp,
  51106. down: textureDown,
  51107. size: size
  51108. };
  51109. };
  51110. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  51111. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  51112. var textureArray = new Float32Array(buffer);
  51113. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  51114. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  51115. var dy = 1 / texSize;
  51116. var fy = 0;
  51117. for (var y = 0; y < texSize; y++) {
  51118. var xv1 = faceData[0];
  51119. var xv2 = faceData[2];
  51120. for (var x = 0; x < texSize; x++) {
  51121. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  51122. v.normalize();
  51123. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  51124. // 3 channels per pixels
  51125. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  51126. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  51127. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  51128. xv1 = xv1.add(rotDX1);
  51129. xv2 = xv2.add(rotDX2);
  51130. }
  51131. fy += dy;
  51132. }
  51133. return textureArray;
  51134. };
  51135. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  51136. var theta = Math.atan2(vDir.z, vDir.x);
  51137. var phi = Math.acos(vDir.y);
  51138. while (theta < -Math.PI)
  51139. theta += 2 * Math.PI;
  51140. while (theta > Math.PI)
  51141. theta -= 2 * Math.PI;
  51142. var dx = theta / Math.PI;
  51143. var dy = phi / Math.PI;
  51144. // recenter.
  51145. dx = dx * 0.5 + 0.5;
  51146. var px = Math.round(dx * inputWidth);
  51147. if (px < 0)
  51148. px = 0;
  51149. else if (px >= inputWidth)
  51150. px = inputWidth - 1;
  51151. var py = Math.round(dy * inputHeight);
  51152. if (py < 0)
  51153. py = 0;
  51154. else if (py >= inputHeight)
  51155. py = inputHeight - 1;
  51156. var inputY = (inputHeight - py - 1);
  51157. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  51158. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  51159. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  51160. return {
  51161. r: r,
  51162. g: g,
  51163. b: b
  51164. };
  51165. };
  51166. return PanoramaToCubeMapTools;
  51167. }());
  51168. PanoramaToCubeMapTools.FACE_FRONT = [
  51169. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  51170. new BABYLON.Vector3(1.0, -1.0, -1.0),
  51171. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  51172. new BABYLON.Vector3(1.0, 1.0, -1.0)
  51173. ];
  51174. PanoramaToCubeMapTools.FACE_BACK = [
  51175. new BABYLON.Vector3(1.0, -1.0, 1.0),
  51176. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  51177. new BABYLON.Vector3(1.0, 1.0, 1.0),
  51178. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  51179. ];
  51180. PanoramaToCubeMapTools.FACE_RIGHT = [
  51181. new BABYLON.Vector3(1.0, -1.0, -1.0),
  51182. new BABYLON.Vector3(1.0, -1.0, 1.0),
  51183. new BABYLON.Vector3(1.0, 1.0, -1.0),
  51184. new BABYLON.Vector3(1.0, 1.0, 1.0)
  51185. ];
  51186. PanoramaToCubeMapTools.FACE_LEFT = [
  51187. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  51188. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  51189. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  51190. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  51191. ];
  51192. PanoramaToCubeMapTools.FACE_DOWN = [
  51193. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  51194. new BABYLON.Vector3(1.0, 1.0, -1.0),
  51195. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  51196. new BABYLON.Vector3(1.0, 1.0, 1.0)
  51197. ];
  51198. PanoramaToCubeMapTools.FACE_UP = [
  51199. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  51200. new BABYLON.Vector3(1.0, -1.0, 1.0),
  51201. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  51202. new BABYLON.Vector3(1.0, -1.0, -1.0)
  51203. ];
  51204. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  51205. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  51206. })(BABYLON || (BABYLON = {}));
  51207. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  51208. var BABYLON;
  51209. (function (BABYLON) {
  51210. var Internals;
  51211. (function (Internals) {
  51212. ;
  51213. /**
  51214. * This groups tools to convert HDR texture to native colors array.
  51215. */
  51216. var HDRTools = (function () {
  51217. function HDRTools() {
  51218. }
  51219. HDRTools.Ldexp = function (mantissa, exponent) {
  51220. if (exponent > 1023) {
  51221. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  51222. }
  51223. if (exponent < -1074) {
  51224. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  51225. }
  51226. return mantissa * Math.pow(2, exponent);
  51227. };
  51228. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  51229. if (exponent > 0) {
  51230. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  51231. float32array[index + 0] = red * exponent;
  51232. float32array[index + 1] = green * exponent;
  51233. float32array[index + 2] = blue * exponent;
  51234. }
  51235. else {
  51236. float32array[index + 0] = 0;
  51237. float32array[index + 1] = 0;
  51238. float32array[index + 2] = 0;
  51239. }
  51240. };
  51241. HDRTools.readStringLine = function (uint8array, startIndex) {
  51242. var line = "";
  51243. var character = "";
  51244. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  51245. character = String.fromCharCode(uint8array[i]);
  51246. if (character == "\n") {
  51247. break;
  51248. }
  51249. line += character;
  51250. }
  51251. return line;
  51252. };
  51253. /**
  51254. * Reads header information from an RGBE texture stored in a native array.
  51255. * More information on this format are available here:
  51256. * https://en.wikipedia.org/wiki/RGBE_image_format
  51257. *
  51258. * @param uint8array The binary file stored in native array.
  51259. * @return The header information.
  51260. */
  51261. HDRTools.RGBE_ReadHeader = function (uint8array) {
  51262. var height = 0;
  51263. var width = 0;
  51264. var line = this.readStringLine(uint8array, 0);
  51265. if (line[0] != '#' || line[1] != '?') {
  51266. throw "Bad HDR Format.";
  51267. }
  51268. var endOfHeader = false;
  51269. var findFormat = false;
  51270. var lineIndex = 0;
  51271. do {
  51272. lineIndex += (line.length + 1);
  51273. line = this.readStringLine(uint8array, lineIndex);
  51274. if (line == "FORMAT=32-bit_rle_rgbe") {
  51275. findFormat = true;
  51276. }
  51277. else if (line.length == 0) {
  51278. endOfHeader = true;
  51279. }
  51280. } while (!endOfHeader);
  51281. if (!findFormat) {
  51282. throw "HDR Bad header format, unsupported FORMAT";
  51283. }
  51284. lineIndex += (line.length + 1);
  51285. line = this.readStringLine(uint8array, lineIndex);
  51286. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  51287. var match = sizeRegexp.exec(line);
  51288. // TODO. Support +Y and -X if needed.
  51289. if (match.length < 3) {
  51290. throw "HDR Bad header format, no size";
  51291. }
  51292. width = parseInt(match[2]);
  51293. height = parseInt(match[1]);
  51294. if (width < 8 || width > 0x7fff) {
  51295. throw "HDR Bad header format, unsupported size";
  51296. }
  51297. lineIndex += (line.length + 1);
  51298. return {
  51299. height: height,
  51300. width: width,
  51301. dataPosition: lineIndex
  51302. };
  51303. };
  51304. /**
  51305. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  51306. * This RGBE texture needs to store the information as a panorama.
  51307. *
  51308. * More information on this format are available here:
  51309. * https://en.wikipedia.org/wiki/RGBE_image_format
  51310. *
  51311. * @param buffer The binary file stored in an array buffer.
  51312. * @param size The expected size of the extracted cubemap.
  51313. * @return The Cube Map information.
  51314. */
  51315. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  51316. var uint8array = new Uint8Array(buffer);
  51317. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  51318. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  51319. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  51320. return cubeMapData;
  51321. };
  51322. /**
  51323. * Returns the pixels data extracted from an RGBE texture.
  51324. * This pixels will be stored left to right up to down in the R G B order in one array.
  51325. *
  51326. * More information on this format are available here:
  51327. * https://en.wikipedia.org/wiki/RGBE_image_format
  51328. *
  51329. * @param uint8array The binary file stored in an array buffer.
  51330. * @param hdrInfo The header information of the file.
  51331. * @return The pixels data in RGB right to left up to down order.
  51332. */
  51333. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  51334. // Keep for multi format supports.
  51335. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  51336. };
  51337. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  51338. var num_scanlines = hdrInfo.height;
  51339. var scanline_width = hdrInfo.width;
  51340. var a, b, c, d, count;
  51341. var dataIndex = hdrInfo.dataPosition;
  51342. var index = 0, endIndex = 0, i = 0;
  51343. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  51344. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  51345. // 3 channels of 4 bytes per pixel in float.
  51346. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  51347. var resultArray = new Float32Array(resultBuffer);
  51348. // read in each successive scanline
  51349. while (num_scanlines > 0) {
  51350. a = uint8array[dataIndex++];
  51351. b = uint8array[dataIndex++];
  51352. c = uint8array[dataIndex++];
  51353. d = uint8array[dataIndex++];
  51354. if (a != 2 || b != 2 || (c & 0x80)) {
  51355. // this file is not run length encoded
  51356. throw "HDR Bad header format, not RLE";
  51357. }
  51358. if (((c << 8) | d) != scanline_width) {
  51359. throw "HDR Bad header format, wrong scan line width";
  51360. }
  51361. index = 0;
  51362. // read each of the four channels for the scanline into the buffer
  51363. for (i = 0; i < 4; i++) {
  51364. endIndex = (i + 1) * scanline_width;
  51365. while (index < endIndex) {
  51366. a = uint8array[dataIndex++];
  51367. b = uint8array[dataIndex++];
  51368. if (a > 128) {
  51369. // a run of the same value
  51370. count = a - 128;
  51371. if ((count == 0) || (count > endIndex - index)) {
  51372. throw "HDR Bad Format, bad scanline data (run)";
  51373. }
  51374. while (count-- > 0) {
  51375. scanLineArray[index++] = b;
  51376. }
  51377. }
  51378. else {
  51379. // a non-run
  51380. count = a;
  51381. if ((count == 0) || (count > endIndex - index)) {
  51382. throw "HDR Bad Format, bad scanline data (non-run)";
  51383. }
  51384. scanLineArray[index++] = b;
  51385. if (--count > 0) {
  51386. for (var j = 0; j < count; j++) {
  51387. scanLineArray[index++] = uint8array[dataIndex++];
  51388. }
  51389. }
  51390. }
  51391. }
  51392. }
  51393. // now convert data from buffer into floats
  51394. for (i = 0; i < scanline_width; i++) {
  51395. a = scanLineArray[i];
  51396. b = scanLineArray[i + scanline_width];
  51397. c = scanLineArray[i + 2 * scanline_width];
  51398. d = scanLineArray[i + 3 * scanline_width];
  51399. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  51400. }
  51401. num_scanlines--;
  51402. }
  51403. return resultArray;
  51404. };
  51405. return HDRTools;
  51406. }());
  51407. Internals.HDRTools = HDRTools;
  51408. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  51409. })(BABYLON || (BABYLON = {}));
  51410. //# sourceMappingURL=babylon.hdr.js.map
  51411. //_______________________________________________________________
  51412. // Extracted from CubeMapGen:
  51413. // https://code.google.com/archive/p/cubemapgen/
  51414. //
  51415. // Following https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  51416. //_______________________________________________________________
  51417. var BABYLON;
  51418. (function (BABYLON) {
  51419. var Internals;
  51420. (function (Internals) {
  51421. /**
  51422. * The bounding box information used during the conversion process.
  51423. */
  51424. var CMGBoundinBox = (function () {
  51425. function CMGBoundinBox() {
  51426. this.min = new BABYLON.Vector3(0, 0, 0);
  51427. this.max = new BABYLON.Vector3(0, 0, 0);
  51428. this.clear();
  51429. }
  51430. CMGBoundinBox.prototype.clear = function () {
  51431. this.min.x = CMGBoundinBox.MAX;
  51432. this.min.y = CMGBoundinBox.MAX;
  51433. this.min.z = CMGBoundinBox.MAX;
  51434. this.max.x = CMGBoundinBox.MIN;
  51435. this.max.y = CMGBoundinBox.MIN;
  51436. this.max.z = CMGBoundinBox.MIN;
  51437. };
  51438. CMGBoundinBox.prototype.augment = function (x, y, z) {
  51439. this.min.x = Math.min(this.min.x, x);
  51440. this.min.y = Math.min(this.min.y, y);
  51441. this.min.z = Math.min(this.min.z, z);
  51442. this.max.x = Math.max(this.max.x, x);
  51443. this.max.y = Math.max(this.max.y, y);
  51444. this.max.z = Math.max(this.max.z, z);
  51445. };
  51446. CMGBoundinBox.prototype.clampMin = function (x, y, z) {
  51447. this.min.x = Math.max(this.min.x, x);
  51448. this.min.y = Math.max(this.min.y, y);
  51449. this.min.z = Math.max(this.min.z, z);
  51450. };
  51451. CMGBoundinBox.prototype.clampMax = function (x, y, z) {
  51452. this.max.x = Math.min(this.max.x, x);
  51453. this.max.y = Math.min(this.max.y, y);
  51454. this.max.z = Math.min(this.max.z, z);
  51455. };
  51456. CMGBoundinBox.prototype.empty = function () {
  51457. if ((this.min.x > this.max.y) ||
  51458. (this.min.y > this.max.y) ||
  51459. (this.min.z > this.max.y)) {
  51460. return true;
  51461. }
  51462. else {
  51463. return false;
  51464. }
  51465. };
  51466. return CMGBoundinBox;
  51467. }());
  51468. CMGBoundinBox.MAX = Number.MAX_VALUE;
  51469. CMGBoundinBox.MIN = Number.MIN_VALUE;
  51470. /**
  51471. * Helper class to PreProcess a cubemap in order to generate mipmap according to the level of blur
  51472. * required by the glossinees of a material.
  51473. *
  51474. * This only supports the cosine drop power as well as Warp fixup generation method.
  51475. *
  51476. * This is using the process from CubeMapGen described here:
  51477. * https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  51478. */
  51479. var PMREMGenerator = (function () {
  51480. /**
  51481. * Constructor of the generator.
  51482. *
  51483. * @param input The different faces data from the original cubemap in the order X+ X- Y+ Y- Z+ Z-
  51484. * @param inputSize The size of the cubemap faces
  51485. * @param outputSize The size of the output cubemap faces
  51486. * @param maxNumMipLevels The max number of mip map to generate (0 means all)
  51487. * @param numChannels The number of channels stored in the cubemap (3 for RBGE for instance)
  51488. * @param isFloat Specifies if the input texture is in float or int (hdr is usually in float)
  51489. * @param specularPower The max specular level of the desired cubemap
  51490. * @param cosinePowerDropPerMip The amount of drop the specular power will follow on each mip
  51491. * @param excludeBase Specifies wether to process the level 0 (original level) or not
  51492. * @param fixup Specifies wether to apply the edge fixup algorythm or not
  51493. */
  51494. function PMREMGenerator(input, inputSize, outputSize, maxNumMipLevels, numChannels, isFloat, specularPower, cosinePowerDropPerMip, excludeBase, fixup) {
  51495. this.input = input;
  51496. this.inputSize = inputSize;
  51497. this.outputSize = outputSize;
  51498. this.maxNumMipLevels = maxNumMipLevels;
  51499. this.numChannels = numChannels;
  51500. this.isFloat = isFloat;
  51501. this.specularPower = specularPower;
  51502. this.cosinePowerDropPerMip = cosinePowerDropPerMip;
  51503. this.excludeBase = excludeBase;
  51504. this.fixup = fixup;
  51505. this._outputSurface = [];
  51506. this._numMipLevels = 0;
  51507. }
  51508. /**
  51509. * Launches the filter process and return the result.
  51510. *
  51511. * @return the filter cubemap in the form mip0 [faces1..6] .. mipN [faces1..6]
  51512. */
  51513. PMREMGenerator.prototype.filterCubeMap = function () {
  51514. // Init cubemap processor
  51515. this.init();
  51516. // Filters the cubemap
  51517. this.filterCubeMapMipChain();
  51518. // Returns the filtered mips.
  51519. return this._outputSurface;
  51520. };
  51521. PMREMGenerator.prototype.init = function () {
  51522. var i;
  51523. var j;
  51524. var mipLevelSize;
  51525. //if nax num mip levels is set to 0, set it to generate the entire mip chain
  51526. if (this.maxNumMipLevels == 0) {
  51527. this.maxNumMipLevels = PMREMGenerator.CP_MAX_MIPLEVELS;
  51528. }
  51529. //first miplevel size
  51530. mipLevelSize = this.outputSize;
  51531. //Iterate over mip chain, and init ArrayBufferView for mip-chain
  51532. for (j = 0; j < this.maxNumMipLevels; j++) {
  51533. this._outputSurface.length++;
  51534. this._outputSurface[j] = [];
  51535. //Iterate over faces for output images
  51536. for (i = 0; i < 6; i++) {
  51537. this._outputSurface[j].length++;
  51538. // Initializes a new array for the output.
  51539. if (this.isFloat) {
  51540. this._outputSurface[j][i] = new Float32Array(mipLevelSize * mipLevelSize * this.numChannels);
  51541. }
  51542. else {
  51543. this._outputSurface[j][i] = new Uint32Array(mipLevelSize * mipLevelSize * this.numChannels);
  51544. }
  51545. }
  51546. //next mip level is half size
  51547. mipLevelSize >>= 1;
  51548. this._numMipLevels++;
  51549. //terminate if mip chain becomes too small
  51550. if (mipLevelSize == 0) {
  51551. this.maxNumMipLevels = j;
  51552. return;
  51553. }
  51554. }
  51555. };
  51556. //--------------------------------------------------------------------------------------
  51557. //Cube map filtering and mip chain generation.
  51558. // the cube map filtereing is specified using a number of parameters:
  51559. // Filtering per miplevel is specified using 2D cone angle (in degrees) that
  51560. // indicates the region of the hemisphere to filter over for each tap.
  51561. //
  51562. // Note that the top mip level is also a filtered version of the original input images
  51563. // as well in order to create mip chains for diffuse environment illumination.
  51564. // The cone angle for the top level is specified by a_BaseAngle. This can be used to
  51565. // generate mipchains used to store the resutls of preintegration across the hemisphere.
  51566. //
  51567. // Then the mip angle used to genreate the next level of the mip chain from the first level
  51568. // is a_InitialMipAngle
  51569. //
  51570. // The angle for the subsequent levels of the mip chain are specified by their parents
  51571. // filtering angle and a per-level scale and bias
  51572. // newAngle = oldAngle * a_MipAnglePerLevelScale;
  51573. //
  51574. //--------------------------------------------------------------------------------------
  51575. PMREMGenerator.prototype.filterCubeMapMipChain = function () {
  51576. // First, take count of the lighting model to modify SpecularPower
  51577. // 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;
  51578. // var refSpecularPower = this.specularPower; // Only Phong BRDF yet. This explains the line below using this.specularpower.
  51579. //Cone angle start (for generating subsequent mip levels)
  51580. var currentSpecularPower = this.specularPower;
  51581. //Build filter lookup tables based on the source miplevel size
  51582. this.precomputeFilterLookupTables(this.inputSize);
  51583. // Note that we need to filter the first level before generating mipmap
  51584. // So LevelIndex == 0 is base filtering hen LevelIndex > 0 is mipmap generation
  51585. for (var levelIndex = 0; levelIndex < this._numMipLevels; levelIndex++) {
  51586. // TODO : Write a function to copy and scale the base mipmap in output
  51587. // I am just lazy here and just put a high specular power value, and do some if.
  51588. if (this.excludeBase && (levelIndex == 0)) {
  51589. // 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).
  51590. currentSpecularPower = 100000.0;
  51591. }
  51592. // Special case for cosine power mipmap chain. For quality requirement, we always process the current mipmap from the top mipmap
  51593. var srcCubeImage = this.input;
  51594. var dstCubeImage = this._outputSurface[levelIndex];
  51595. var dstSize = this.outputSize >> levelIndex;
  51596. // Compute required angle.
  51597. var angle = this.getBaseFilterAngle(currentSpecularPower);
  51598. // filter cube surfaces
  51599. this.filterCubeSurfaces(srcCubeImage, this.inputSize, dstCubeImage, dstSize, angle, currentSpecularPower);
  51600. // fix seams
  51601. if (this.fixup) {
  51602. this.fixupCubeEdges(dstCubeImage, dstSize);
  51603. }
  51604. // Decrease the specular power to generate the mipmap chain
  51605. // TODO : Use another method for Exclude (see first comment at start of the function
  51606. if (this.excludeBase && (levelIndex == 0)) {
  51607. currentSpecularPower = this.specularPower;
  51608. }
  51609. currentSpecularPower *= this.cosinePowerDropPerMip;
  51610. }
  51611. };
  51612. //--------------------------------------------------------------------------------------
  51613. // This function return the BaseFilterAngle require by PMREMGenerator to its FilterExtends
  51614. // It allow to optimize the texel to access base on the specular power.
  51615. //--------------------------------------------------------------------------------------
  51616. PMREMGenerator.prototype.getBaseFilterAngle = function (cosinePower) {
  51617. // We want to find the alpha such that:
  51618. // cos(alpha)^cosinePower = epsilon
  51619. // That's: acos(epsilon^(1/cosinePower))
  51620. var threshold = 0.000001; // Empirical threshold (Work perfectly, didn't check for a more big number, may get some performance and still god approximation)
  51621. var angle = 180.0;
  51622. angle = Math.acos(Math.pow(threshold, 1.0 / cosinePower));
  51623. angle *= 180.0 / Math.PI; // Convert to degree
  51624. angle *= 2.0; // * 2.0f because PMREMGenerator divide by 2 later
  51625. return angle;
  51626. };
  51627. //--------------------------------------------------------------------------------------
  51628. //Builds the following lookup tables prior to filtering:
  51629. // -normalizer cube map
  51630. // -tap weight lookup table
  51631. //
  51632. //--------------------------------------------------------------------------------------
  51633. PMREMGenerator.prototype.precomputeFilterLookupTables = function (srcCubeMapWidth) {
  51634. var srcTexelAngle;
  51635. var iCubeFace;
  51636. //clear pre-existing normalizer cube map
  51637. this._normCubeMap = [];
  51638. //Normalized vectors per cubeface and per-texel solid angle
  51639. this.buildNormalizerSolidAngleCubemap(srcCubeMapWidth);
  51640. };
  51641. //--------------------------------------------------------------------------------------
  51642. //Builds a normalizer cubemap, with the texels solid angle stored in the fourth component
  51643. //
  51644. //Takes in a cube face size, and an array of 6 surfaces to write the cube faces into
  51645. //
  51646. //Note that this normalizer cube map stores the vectors in unbiased -1 to 1 range.
  51647. // if _bx2 style scaled and biased vectors are needed, uncomment the SCALE and BIAS
  51648. // below
  51649. //--------------------------------------------------------------------------------------
  51650. PMREMGenerator.prototype.buildNormalizerSolidAngleCubemap = function (size) {
  51651. var iCubeFace;
  51652. var u;
  51653. var v;
  51654. //iterate over cube faces
  51655. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  51656. //First three channels for norm cube, and last channel for solid angle
  51657. this._normCubeMap.push(new Float32Array(size * size * 4));
  51658. //fast texture walk, build normalizer cube map
  51659. var facesData = this.input[iCubeFace];
  51660. for (v = 0; v < size; v++) {
  51661. for (u = 0; u < size; u++) {
  51662. var vect = this.texelCoordToVect(iCubeFace, u, v, size, this.fixup);
  51663. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 0] = vect.x;
  51664. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 1] = vect.y;
  51665. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 2] = vect.z;
  51666. var solidAngle = this.texelCoordSolidAngle(iCubeFace, u, v, size);
  51667. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 4] = solidAngle;
  51668. }
  51669. }
  51670. }
  51671. };
  51672. //--------------------------------------------------------------------------------------
  51673. // Convert cubemap face texel coordinates and face idx to 3D vector
  51674. // note the U and V coords are integer coords and range from 0 to size-1
  51675. // this routine can be used to generate a normalizer cube map
  51676. //--------------------------------------------------------------------------------------
  51677. // SL BEGIN
  51678. PMREMGenerator.prototype.texelCoordToVect = function (faceIdx, u, v, size, fixup) {
  51679. var nvcU;
  51680. var nvcV;
  51681. var tempVec;
  51682. // Change from original AMD code
  51683. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  51684. // + 0.5f is for texel center addressing
  51685. nvcU = (2.0 * (u + 0.5) / size) - 1.0;
  51686. nvcV = (2.0 * (v + 0.5) / size) - 1.0;
  51687. // warp fixup
  51688. if (fixup && size > 1) {
  51689. // Code from Nvtt : http://code.google.com/p/nvidia-texture-tools/source/browse/trunk/src/nvtt/CubeSurface.cpp
  51690. var a = Math.pow(size, 2.0) / Math.pow(size - 1, 3.0);
  51691. nvcU = a * Math.pow(nvcU, 3) + nvcU;
  51692. nvcV = a * Math.pow(nvcV, 3) + nvcV;
  51693. }
  51694. // Get current vector
  51695. // generate x,y,z vector (xform 2d NVC coord to 3D vector)
  51696. // U contribution
  51697. var UVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  51698. PMREMGenerator._vectorTemp.x = UVec[0] * nvcU;
  51699. PMREMGenerator._vectorTemp.y = UVec[1] * nvcU;
  51700. PMREMGenerator._vectorTemp.z = UVec[2] * nvcU;
  51701. // V contribution and Sum
  51702. var VVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  51703. PMREMGenerator._vectorTemp.x += VVec[0] * nvcV;
  51704. PMREMGenerator._vectorTemp.y += VVec[1] * nvcV;
  51705. PMREMGenerator._vectorTemp.z += VVec[2] * nvcV;
  51706. //add face axis
  51707. var faceAxis = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_FACEAXIS];
  51708. PMREMGenerator._vectorTemp.x += faceAxis[0];
  51709. PMREMGenerator._vectorTemp.y += faceAxis[1];
  51710. PMREMGenerator._vectorTemp.z += faceAxis[2];
  51711. //normalize vector
  51712. PMREMGenerator._vectorTemp.normalize();
  51713. return PMREMGenerator._vectorTemp;
  51714. };
  51715. //--------------------------------------------------------------------------------------
  51716. // Convert 3D vector to cubemap face texel coordinates and face idx
  51717. // note the U and V coords are integer coords and range from 0 to size-1
  51718. // this routine can be used to generate a normalizer cube map
  51719. //
  51720. // returns face IDX and texel coords
  51721. //--------------------------------------------------------------------------------------
  51722. // SL BEGIN
  51723. /*
  51724. Mapping Texture Coordinates to Cube Map Faces
  51725. Because there are multiple faces, the mapping of texture coordinates to positions on cube map faces
  51726. is more complicated than the other texturing targets. The EXT_texture_cube_map extension is purposefully
  51727. designed to be consistent with DirectX 7's cube map arrangement. This is also consistent with the cube
  51728. map arrangement in Pixar's RenderMan package.
  51729. For cube map texturing, the (s,t,r) texture coordinates are treated as a direction vector (rx,ry,rz)
  51730. emanating from the center of a cube. (The q coordinate can be ignored since it merely scales the vector
  51731. without affecting the direction.) At texture application time, the interpolated per-fragment (s,t,r)
  51732. selects one of the cube map face's 2D mipmap sets based on the largest magnitude coordinate direction
  51733. the major axis direction). The target column in the table below explains how the major axis direction
  51734. maps to the 2D image of a particular cube map target.
  51735. major axis
  51736. direction target sc tc ma
  51737. ---------- --------------------------------- --- --- ---
  51738. +rx GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT -rz -ry rx
  51739. -rx GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT +rz -ry rx
  51740. +ry GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT +rx +rz ry
  51741. -ry GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT +rx -rz ry
  51742. +rz GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT +rx -ry rz
  51743. -rz GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT -rx -ry rz
  51744. Using the sc, tc, and ma determined by the major axis direction as specified in the table above,
  51745. an updated (s,t) is calculated as follows
  51746. s = ( sc/|ma| + 1 ) / 2
  51747. t = ( tc/|ma| + 1 ) / 2
  51748. If |ma| is zero or very nearly zero, the results of the above two equations need not be defined
  51749. (though the result may not lead to GL interruption or termination). Once the cube map face's 2D mipmap
  51750. set and (s,t) is determined, texture fetching and filtering proceeds like standard OpenGL 2D texturing.
  51751. */
  51752. // Note this method return U and V in range from 0 to size-1
  51753. // SL END
  51754. // Store the information in vector3 for convenience (faceindex, u, v)
  51755. PMREMGenerator.prototype.vectToTexelCoord = function (x, y, z, size) {
  51756. var maxCoord;
  51757. var faceIdx;
  51758. //absolute value 3
  51759. var absX = Math.abs(x);
  51760. var absY = Math.abs(y);
  51761. var absZ = Math.abs(z);
  51762. if (absX >= absY && absX >= absZ) {
  51763. maxCoord = absX;
  51764. if (x >= 0) {
  51765. faceIdx = PMREMGenerator.CP_FACE_X_POS;
  51766. }
  51767. else {
  51768. faceIdx = PMREMGenerator.CP_FACE_X_NEG;
  51769. }
  51770. }
  51771. else if (absY >= absX && absY >= absZ) {
  51772. maxCoord = absY;
  51773. if (y >= 0) {
  51774. faceIdx = PMREMGenerator.CP_FACE_Y_POS;
  51775. }
  51776. else {
  51777. faceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  51778. }
  51779. }
  51780. else {
  51781. maxCoord = absZ;
  51782. if (z >= 0) {
  51783. faceIdx = PMREMGenerator.CP_FACE_Z_POS;
  51784. }
  51785. else {
  51786. faceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  51787. }
  51788. }
  51789. //divide through by max coord so face vector lies on cube face
  51790. var scale = 1 / maxCoord;
  51791. x *= scale;
  51792. y *= scale;
  51793. z *= scale;
  51794. var temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  51795. var nvcU = temp[0] * x + temp[1] * y + temp[2] * z;
  51796. temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  51797. var nvcV = temp[0] * x + temp[1] * y + temp[2] * z;
  51798. // Modify original AMD code to return value from 0 to Size - 1
  51799. var u = Math.floor((size - 1) * 0.5 * (nvcU + 1.0));
  51800. var v = Math.floor((size - 1) * 0.5 * (nvcV + 1.0));
  51801. PMREMGenerator._vectorTemp.x = faceIdx;
  51802. PMREMGenerator._vectorTemp.y = u;
  51803. PMREMGenerator._vectorTemp.z = v;
  51804. return PMREMGenerator._vectorTemp;
  51805. };
  51806. //--------------------------------------------------------------------------------------
  51807. //Original code from Ignacio CastaÒo
  51808. // This formula is from Manne ÷hrstrˆm's thesis.
  51809. // Take two coordiantes in the range [-1, 1] that define a portion of a
  51810. // cube face and return the area of the projection of that portion on the
  51811. // surface of the sphere.
  51812. //--------------------------------------------------------------------------------------
  51813. PMREMGenerator.prototype.areaElement = function (x, y) {
  51814. return Math.atan2(x * y, Math.sqrt(x * x + y * y + 1));
  51815. };
  51816. PMREMGenerator.prototype.texelCoordSolidAngle = function (faceIdx, u, v, size) {
  51817. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  51818. // (+ 0.5f is for texel center addressing)
  51819. u = (2.0 * (u + 0.5) / size) - 1.0;
  51820. v = (2.0 * (v + 0.5) / size) - 1.0;
  51821. // Shift from a demi texel, mean 1.0f / a_Size with U and V in [-1..1]
  51822. var invResolution = 1.0 / size;
  51823. // U and V are the -1..1 texture coordinate on the current face.
  51824. // Get projected area for this texel
  51825. var x0 = u - invResolution;
  51826. var y0 = v - invResolution;
  51827. var x1 = u + invResolution;
  51828. var y1 = v + invResolution;
  51829. var solidAngle = this.areaElement(x0, y0) - this.areaElement(x0, y1) - this.areaElement(x1, y0) + this.areaElement(x1, y1);
  51830. return solidAngle;
  51831. };
  51832. //--------------------------------------------------------------------------------------
  51833. //The key to the speed of these filtering routines is to quickly define a per-face
  51834. // bounding box of pixels which enclose all the taps in the filter kernel efficiently.
  51835. // Later these pixels are selectively processed based on their dot products to see if
  51836. // they reside within the filtering cone.
  51837. //
  51838. //This is done by computing the smallest per-texel angle to get a conservative estimate
  51839. // of the number of texels needed to be covered in width and height order to filter the
  51840. // region. the bounding box for the center taps face is defined first, and if the
  51841. // filtereing region bleeds onto the other faces, bounding boxes for the other faces are
  51842. // defined next
  51843. //--------------------------------------------------------------------------------------
  51844. PMREMGenerator.prototype.filterCubeSurfaces = function (srcCubeMap, srcSize, dstCubeMap, dstSize, filterConeAngle, specularPower) {
  51845. // note that pixels within these regions may be rejected
  51846. // based on the anlge
  51847. var iCubeFace;
  51848. var u;
  51849. var v;
  51850. // bounding box per face to specify region to process
  51851. var filterExtents = [];
  51852. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  51853. filterExtents.push(new CMGBoundinBox());
  51854. }
  51855. // min angle a src texel can cover (in degrees)
  51856. var srcTexelAngle = (180.0 / (Math.PI) * Math.atan2(1.0, srcSize));
  51857. // angle about center tap to define filter cone
  51858. // filter angle is 1/2 the cone angle
  51859. var filterAngle = filterConeAngle / 2.0;
  51860. //ensure filter angle is larger than a texel
  51861. if (filterAngle < srcTexelAngle) {
  51862. filterAngle = srcTexelAngle;
  51863. }
  51864. //ensure filter cone is always smaller than the hemisphere
  51865. if (filterAngle > 90.0) {
  51866. filterAngle = 90.0;
  51867. }
  51868. // the maximum number of texels in 1D the filter cone angle will cover
  51869. // used to determine bounding box size for filter extents
  51870. var filterSize = Math.ceil(filterAngle / srcTexelAngle);
  51871. // ensure conservative region always covers at least one texel
  51872. if (filterSize < 1) {
  51873. filterSize = 1;
  51874. }
  51875. // dotProdThresh threshold based on cone angle to determine whether or not taps
  51876. // reside within the cone angle
  51877. var dotProdThresh = Math.cos((Math.PI / 180.0) * filterAngle);
  51878. // process required faces
  51879. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  51880. //iterate over dst cube map face texel
  51881. for (v = 0; v < dstSize; v++) {
  51882. for (u = 0; u < dstSize; u++) {
  51883. //get center tap direction
  51884. var centerTapDir = this.texelCoordToVect(iCubeFace, u, v, dstSize, this.fixup).clone();
  51885. //clear old per-face filter extents
  51886. this.clearFilterExtents(filterExtents);
  51887. //define per-face filter extents
  51888. this.determineFilterExtents(centerTapDir, srcSize, filterSize, filterExtents);
  51889. //perform filtering of src faces using filter extents
  51890. var vect = this.processFilterExtents(centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower);
  51891. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 0] = vect.x;
  51892. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 1] = vect.y;
  51893. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 2] = vect.z;
  51894. }
  51895. }
  51896. }
  51897. };
  51898. //--------------------------------------------------------------------------------------
  51899. //Clear filter extents for the 6 cube map faces
  51900. //--------------------------------------------------------------------------------------
  51901. PMREMGenerator.prototype.clearFilterExtents = function (filterExtents) {
  51902. for (var iCubeFaces = 0; iCubeFaces < 6; iCubeFaces++) {
  51903. filterExtents[iCubeFaces].clear();
  51904. }
  51905. };
  51906. //--------------------------------------------------------------------------------------
  51907. //Define per-face bounding box filter extents
  51908. //
  51909. // These define conservative texel regions in each of the faces the filter can possibly
  51910. // process. When the pixels in the regions are actually processed, the dot product
  51911. // between the tap vector and the center tap vector is used to determine the weight of
  51912. // the tap and whether or not the tap is within the cone.
  51913. //
  51914. //--------------------------------------------------------------------------------------
  51915. PMREMGenerator.prototype.determineFilterExtents = function (centerTapDir, srcSize, bboxSize, filterExtents) {
  51916. //neighboring face and bleed over amount, and width of BBOX for
  51917. // left, right, top, and bottom edges of this face
  51918. var bleedOverAmount = [0, 0, 0, 0];
  51919. var bleedOverBBoxMin = [0, 0, 0, 0];
  51920. var bleedOverBBoxMax = [0, 0, 0, 0];
  51921. var neighborFace;
  51922. var neighborEdge;
  51923. var oppositeFaceIdx;
  51924. //get face idx, and u, v info from center tap dir
  51925. var result = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize);
  51926. var faceIdx = result.x;
  51927. var u = result.y;
  51928. var v = result.z;
  51929. //define bbox size within face
  51930. filterExtents[faceIdx].augment(u - bboxSize, v - bboxSize, 0);
  51931. filterExtents[faceIdx].augment(u + bboxSize, v + bboxSize, 0);
  51932. filterExtents[faceIdx].clampMin(0, 0, 0);
  51933. filterExtents[faceIdx].clampMax(srcSize - 1, srcSize - 1, 0);
  51934. //u and v extent in face corresponding to center tap
  51935. var minU = filterExtents[faceIdx].min.x;
  51936. var minV = filterExtents[faceIdx].min.y;
  51937. var maxU = filterExtents[faceIdx].max.x;
  51938. var maxV = filterExtents[faceIdx].max.y;
  51939. //bleed over amounts for face across u=0 edge (left)
  51940. bleedOverAmount[0] = (bboxSize - u);
  51941. bleedOverBBoxMin[0] = minV;
  51942. bleedOverBBoxMax[0] = maxV;
  51943. //bleed over amounts for face across u=1 edge (right)
  51944. bleedOverAmount[1] = (u + bboxSize) - (srcSize - 1);
  51945. bleedOverBBoxMin[1] = minV;
  51946. bleedOverBBoxMax[1] = maxV;
  51947. //bleed over to face across v=0 edge (up)
  51948. bleedOverAmount[2] = (bboxSize - v);
  51949. bleedOverBBoxMin[2] = minU;
  51950. bleedOverBBoxMax[2] = maxU;
  51951. //bleed over to face across v=1 edge (down)
  51952. bleedOverAmount[3] = (v + bboxSize) - (srcSize - 1);
  51953. bleedOverBBoxMin[3] = minU;
  51954. bleedOverBBoxMax[3] = maxU;
  51955. //compute bleed over regions in neighboring faces
  51956. for (var i = 0; i < 4; i++) {
  51957. if (bleedOverAmount[i] > 0) {
  51958. neighborFace = PMREMGenerator._sgCubeNgh[faceIdx][i][0];
  51959. neighborEdge = PMREMGenerator._sgCubeNgh[faceIdx][i][1];
  51960. //For certain types of edge abutments, the bleedOverBBoxMin, and bleedOverBBoxMax need to
  51961. // be flipped: the cases are
  51962. // if a left edge mates with a left or bottom edge on the neighbor
  51963. // if a top edge mates with a top or right edge on the neighbor
  51964. // if a right edge mates with a right or top edge on the neighbor
  51965. // if a bottom edge mates with a bottom or left edge on the neighbor
  51966. //Seeing as the edges are enumerated as follows
  51967. // left =0
  51968. // right =1
  51969. // top =2
  51970. // bottom =3
  51971. //
  51972. // so if the edge enums are the same, or the sum of the enums == 3,
  51973. // the bbox needs to be flipped
  51974. if ((i == neighborEdge) || ((i + neighborEdge) == 3)) {
  51975. bleedOverBBoxMin[i] = (srcSize - 1) - bleedOverBBoxMin[i];
  51976. bleedOverBBoxMax[i] = (srcSize - 1) - bleedOverBBoxMax[i];
  51977. }
  51978. //The way the bounding box is extended onto the neighboring face
  51979. // depends on which edge of neighboring face abuts with this one
  51980. switch (PMREMGenerator._sgCubeNgh[faceIdx][i][1]) {
  51981. case PMREMGenerator.CP_EDGE_LEFT:
  51982. filterExtents[neighborFace].augment(0, bleedOverBBoxMin[i], 0);
  51983. filterExtents[neighborFace].augment(bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  51984. break;
  51985. case PMREMGenerator.CP_EDGE_RIGHT:
  51986. filterExtents[neighborFace].augment((srcSize - 1), bleedOverBBoxMin[i], 0);
  51987. filterExtents[neighborFace].augment((srcSize - 1) - bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  51988. break;
  51989. case PMREMGenerator.CP_EDGE_TOP:
  51990. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], 0, 0);
  51991. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], bleedOverAmount[i], 0);
  51992. break;
  51993. case PMREMGenerator.CP_EDGE_BOTTOM:
  51994. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], (srcSize - 1), 0);
  51995. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], (srcSize - 1) - bleedOverAmount[i], 0);
  51996. break;
  51997. }
  51998. //clamp filter extents in non-center tap faces to remain within surface
  51999. filterExtents[neighborFace].clampMin(0, 0, 0);
  52000. filterExtents[neighborFace].clampMax(srcSize - 1, srcSize - 1, 0);
  52001. }
  52002. //If the bleed over amount bleeds past the adjacent face onto the opposite face
  52003. // from the center tap face, then process the opposite face entirely for now.
  52004. //Note that the cases in which this happens, what usually happens is that
  52005. // more than one edge bleeds onto the opposite face, and the bounding box
  52006. // encompasses the entire cube map face.
  52007. if (bleedOverAmount[i] > srcSize) {
  52008. //determine opposite face
  52009. switch (faceIdx) {
  52010. case PMREMGenerator.CP_FACE_X_POS:
  52011. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_NEG;
  52012. break;
  52013. case PMREMGenerator.CP_FACE_X_NEG:
  52014. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_POS;
  52015. break;
  52016. case PMREMGenerator.CP_FACE_Y_POS:
  52017. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  52018. break;
  52019. case PMREMGenerator.CP_FACE_Y_NEG:
  52020. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_POS;
  52021. break;
  52022. case PMREMGenerator.CP_FACE_Z_POS:
  52023. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  52024. break;
  52025. case PMREMGenerator.CP_FACE_Z_NEG:
  52026. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_POS;
  52027. break;
  52028. default:
  52029. break;
  52030. }
  52031. //just encompass entire face for now
  52032. filterExtents[oppositeFaceIdx].augment(0, 0, 0);
  52033. filterExtents[oppositeFaceIdx].augment((srcSize - 1), (srcSize - 1), 0);
  52034. }
  52035. }
  52036. };
  52037. //--------------------------------------------------------------------------------------
  52038. //ProcessFilterExtents
  52039. // Process bounding box in each cube face
  52040. //
  52041. //--------------------------------------------------------------------------------------
  52042. PMREMGenerator.prototype.processFilterExtents = function (centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower) {
  52043. //accumulators are 64-bit floats in order to have the precision needed
  52044. // over a summation of a large number of pixels
  52045. var dstAccum = [0, 0, 0, 0];
  52046. var weightAccum = 0;
  52047. var k = 0;
  52048. var nSrcChannels = this.numChannels;
  52049. // norm cube map and srcCubeMap have same face width
  52050. var faceWidth = srcSize;
  52051. //amount to add to pointer to move to next scanline in images
  52052. var normCubePitch = faceWidth * 4; // 4 channels in normCubeMap.
  52053. var srcCubePitch = faceWidth * this.numChannels; // numChannels correponds to the cubemap number of channel
  52054. var IsPhongBRDF = 1; // Only works in Phong BRDF yet.
  52055. //(a_LightingModel == CP_LIGHTINGMODEL_PHONG_BRDF || a_LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? 1 : 0; // This value will be added to the specular power
  52056. // iterate over cubefaces
  52057. for (var iFaceIdx = 0; iFaceIdx < 6; iFaceIdx++) {
  52058. //if bbox is non empty
  52059. if (!filterExtents[iFaceIdx].empty()) {
  52060. var uStart = filterExtents[iFaceIdx].min.x;
  52061. var vStart = filterExtents[iFaceIdx].min.y;
  52062. var uEnd = filterExtents[iFaceIdx].max.x;
  52063. var vEnd = filterExtents[iFaceIdx].max.y;
  52064. var startIndexNormCubeMap = (4 * ((vStart * faceWidth) + uStart));
  52065. var startIndexSrcCubeMap = (this.numChannels * ((vStart * faceWidth) + uStart));
  52066. //note that <= is used to ensure filter extents always encompass at least one pixel if bbox is non empty
  52067. for (var v = vStart; v <= vEnd; v++) {
  52068. var normCubeRowWalk = 0;
  52069. var srcCubeRowWalk = 0;
  52070. for (var u = uStart; u <= uEnd; u++) {
  52071. //pointer to direction in cube map associated with texel
  52072. var texelVectX = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 0];
  52073. var texelVectY = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 1];
  52074. var texelVectZ = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 2];
  52075. //check dot product to see if texel is within cone
  52076. var tapDotProd = texelVectX * centerTapDir.x +
  52077. texelVectY * centerTapDir.y +
  52078. texelVectZ * centerTapDir.z;
  52079. if (tapDotProd >= dotProdThresh && tapDotProd > 0.0) {
  52080. //solid angle stored in 4th channel of normalizer/solid angle cube map
  52081. var weight = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 3];
  52082. // Here we decide if we use a Phong/Blinn or a Phong/Blinn BRDF.
  52083. // Phong/Blinn BRDF is just the Phong/Blinn model multiply by the cosine of the lambert law
  52084. // so just adding one to specularpower do the trick.
  52085. weight *= Math.pow(tapDotProd, (specularPower + IsPhongBRDF));
  52086. //iterate over channels
  52087. for (k = 0; k < nSrcChannels; k++) {
  52088. dstAccum[k] += weight * srcCubeMap[iFaceIdx][startIndexSrcCubeMap + srcCubeRowWalk];
  52089. srcCubeRowWalk++;
  52090. }
  52091. weightAccum += weight; //accumulate weight
  52092. }
  52093. else {
  52094. //step across source pixel
  52095. srcCubeRowWalk += nSrcChannels;
  52096. }
  52097. normCubeRowWalk += 4; // 4 channels per norm cube map.
  52098. }
  52099. startIndexNormCubeMap += normCubePitch;
  52100. startIndexSrcCubeMap += srcCubePitch;
  52101. }
  52102. }
  52103. }
  52104. //divide through by weights if weight is non zero
  52105. if (weightAccum != 0.0) {
  52106. PMREMGenerator._vectorTemp.x = (dstAccum[0] / weightAccum);
  52107. PMREMGenerator._vectorTemp.y = (dstAccum[1] / weightAccum);
  52108. PMREMGenerator._vectorTemp.z = (dstAccum[2] / weightAccum);
  52109. if (this.numChannels > 3) {
  52110. PMREMGenerator._vectorTemp.w = (dstAccum[3] / weightAccum);
  52111. }
  52112. }
  52113. else {
  52114. // otherwise sample nearest
  52115. // get face idx and u, v texel coordinate in face
  52116. var coord = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize).clone();
  52117. PMREMGenerator._vectorTemp.x = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 0];
  52118. PMREMGenerator._vectorTemp.y = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 1];
  52119. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 2];
  52120. if (this.numChannels > 3) {
  52121. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 3];
  52122. }
  52123. }
  52124. return PMREMGenerator._vectorTemp;
  52125. };
  52126. //--------------------------------------------------------------------------------------
  52127. // Fixup cube edges
  52128. //
  52129. // average texels on cube map faces across the edges
  52130. // WARP/BENT Method Only.
  52131. //--------------------------------------------------------------------------------------
  52132. PMREMGenerator.prototype.fixupCubeEdges = function (cubeMap, cubeMapSize) {
  52133. var k;
  52134. var j;
  52135. var i;
  52136. var iFace;
  52137. var iCorner = 0;
  52138. var cornerNumPtrs = [0, 0, 0, 0, 0, 0, 0, 0]; //indexed by corner and face idx
  52139. var faceCornerStartIndicies = [[], [], [], []]; //corner pointers for face keeping track of the face they belong to.
  52140. // note that if functionality to filter across the three texels for each corner, then
  52141. //indexed by corner and face idx. the array contains the face the start points belongs to.
  52142. var cornerPtr = [
  52143. [[], [], []],
  52144. [[], [], []],
  52145. [[], [], []],
  52146. [[], [], []],
  52147. [[], [], []],
  52148. [[], [], []],
  52149. [[], [], []],
  52150. [[], [], []]
  52151. ];
  52152. //if there is no fixup, or fixup width = 0, do nothing
  52153. if (cubeMapSize < 1) {
  52154. return;
  52155. }
  52156. //special case 1x1 cubemap, average face colors
  52157. if (cubeMapSize == 1) {
  52158. //iterate over channels
  52159. for (k = 0; k < this.numChannels; k++) {
  52160. var accum = 0.0;
  52161. //iterate over faces to accumulate face colors
  52162. for (iFace = 0; iFace < 6; iFace++) {
  52163. accum += cubeMap[iFace][k];
  52164. }
  52165. //compute average over 6 face colors
  52166. accum /= 6.0;
  52167. //iterate over faces to distribute face colors
  52168. for (iFace = 0; iFace < 6; iFace++) {
  52169. cubeMap[iFace][k] = accum;
  52170. }
  52171. }
  52172. return;
  52173. }
  52174. //iterate over faces to collect list of corner texel pointers
  52175. for (iFace = 0; iFace < 6; iFace++) {
  52176. //the 4 corner pointers for this face
  52177. faceCornerStartIndicies[0] = [iFace, 0];
  52178. faceCornerStartIndicies[1] = [iFace, ((cubeMapSize - 1) * this.numChannels)];
  52179. faceCornerStartIndicies[2] = [iFace, ((cubeMapSize) * (cubeMapSize - 1) * this.numChannels)];
  52180. faceCornerStartIndicies[3] = [iFace, ((((cubeMapSize) * (cubeMapSize - 1)) + (cubeMapSize - 1)) * this.numChannels)];
  52181. //iterate over face corners to collect cube corner pointers
  52182. for (iCorner = 0; iCorner < 4; iCorner++) {
  52183. var corner = PMREMGenerator._sgCubeCornerList[iFace][iCorner];
  52184. cornerPtr[corner][cornerNumPtrs[corner]] = faceCornerStartIndicies[iCorner];
  52185. cornerNumPtrs[corner]++;
  52186. }
  52187. }
  52188. //iterate over corners to average across corner tap values
  52189. for (iCorner = 0; iCorner < 8; iCorner++) {
  52190. for (k = 0; k < this.numChannels; k++) {
  52191. var cornerTapAccum = 0.0;
  52192. //iterate over corner texels and average results
  52193. for (i = 0; i < 3; i++) {
  52194. cornerTapAccum += cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k]; // Get in the cube map face the start point + channel.
  52195. }
  52196. //divide by 3 to compute average of corner tap values
  52197. cornerTapAccum *= (1.0 / 3.0);
  52198. //iterate over corner texels and average results
  52199. for (i = 0; i < 3; i++) {
  52200. cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k] = cornerTapAccum;
  52201. }
  52202. }
  52203. }
  52204. //iterate over the twelve edges of the cube to average across edges
  52205. for (i = 0; i < 12; i++) {
  52206. var face = PMREMGenerator._sgCubeEdgeList[i][0];
  52207. var edge = PMREMGenerator._sgCubeEdgeList[i][1];
  52208. var neighborFace = PMREMGenerator._sgCubeNgh[face][edge][0];
  52209. var neighborEdge = PMREMGenerator._sgCubeNgh[face][edge][1];
  52210. var edgeStartIndex = 0; // a_CubeMap[face].m_ImgData;
  52211. var neighborEdgeStartIndex = 0; // a_CubeMap[neighborFace].m_ImgData;
  52212. var edgeWalk = 0;
  52213. var neighborEdgeWalk = 0;
  52214. //Determine walking pointers based on edge type
  52215. // e.g. CP_EDGE_LEFT, CP_EDGE_RIGHT, CP_EDGE_TOP, CP_EDGE_BOTTOM
  52216. switch (edge) {
  52217. case PMREMGenerator.CP_EDGE_LEFT:
  52218. // no change to faceEdgeStartPtr
  52219. edgeWalk = this.numChannels * cubeMapSize;
  52220. break;
  52221. case PMREMGenerator.CP_EDGE_RIGHT:
  52222. edgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  52223. edgeWalk = this.numChannels * cubeMapSize;
  52224. break;
  52225. case PMREMGenerator.CP_EDGE_TOP:
  52226. // no change to faceEdgeStartPtr
  52227. edgeWalk = this.numChannels;
  52228. break;
  52229. case PMREMGenerator.CP_EDGE_BOTTOM:
  52230. edgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  52231. edgeWalk = this.numChannels;
  52232. break;
  52233. }
  52234. //For certain types of edge abutments, the neighbor edge walk needs to
  52235. // be flipped: the cases are
  52236. // if a left edge mates with a left or bottom edge on the neighbor
  52237. // if a top edge mates with a top or right edge on the neighbor
  52238. // if a right edge mates with a right or top edge on the neighbor
  52239. // if a bottom edge mates with a bottom or left edge on the neighbor
  52240. //Seeing as the edges are enumerated as follows
  52241. // left =0
  52242. // right =1
  52243. // top =2
  52244. // bottom =3
  52245. //
  52246. //If the edge enums are the same, or the sum of the enums == 3,
  52247. // the neighbor edge walk needs to be flipped
  52248. if ((edge == neighborEdge) || ((edge + neighborEdge) == 3)) {
  52249. switch (neighborEdge) {
  52250. case PMREMGenerator.CP_EDGE_LEFT:
  52251. neighborEdgeStartIndex += (cubeMapSize - 1) * (cubeMapSize) * this.numChannels;
  52252. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  52253. break;
  52254. case PMREMGenerator.CP_EDGE_RIGHT:
  52255. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  52256. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  52257. break;
  52258. case PMREMGenerator.CP_EDGE_TOP:
  52259. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  52260. neighborEdgeWalk = -this.numChannels;
  52261. break;
  52262. case PMREMGenerator.CP_EDGE_BOTTOM:
  52263. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  52264. neighborEdgeWalk = -this.numChannels;
  52265. break;
  52266. }
  52267. }
  52268. else {
  52269. //swapped direction neighbor edge walk
  52270. switch (neighborEdge) {
  52271. case PMREMGenerator.CP_EDGE_LEFT:
  52272. //no change to neighborEdgeStartPtr for this case since it points
  52273. // to the upper left corner already
  52274. neighborEdgeWalk = this.numChannels * cubeMapSize;
  52275. break;
  52276. case PMREMGenerator.CP_EDGE_RIGHT:
  52277. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  52278. neighborEdgeWalk = this.numChannels * cubeMapSize;
  52279. break;
  52280. case PMREMGenerator.CP_EDGE_TOP:
  52281. //no change to neighborEdgeStartPtr for this case since it points
  52282. // to the upper left corner already
  52283. neighborEdgeWalk = this.numChannels;
  52284. break;
  52285. case PMREMGenerator.CP_EDGE_BOTTOM:
  52286. neighborEdgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  52287. neighborEdgeWalk = this.numChannels;
  52288. break;
  52289. }
  52290. }
  52291. //Perform edge walk, to average across the 12 edges and smoothly propagate change to
  52292. //nearby neighborhood
  52293. //step ahead one texel on edge
  52294. edgeStartIndex += edgeWalk;
  52295. neighborEdgeStartIndex += neighborEdgeWalk;
  52296. // note that this loop does not process the corner texels, since they have already been
  52297. // averaged across faces across earlier
  52298. for (j = 1; j < (cubeMapSize - 1); j++) {
  52299. //for each set of taps along edge, average them
  52300. // and rewrite the results into the edges
  52301. for (k = 0; k < this.numChannels; k++) {
  52302. var edgeTap = cubeMap[face][edgeStartIndex + k];
  52303. var neighborEdgeTap = cubeMap[neighborFace][neighborEdgeStartIndex + k];
  52304. //compute average of tap intensity values
  52305. var avgTap = 0.5 * (edgeTap + neighborEdgeTap);
  52306. //propagate average of taps to edge taps
  52307. cubeMap[face][edgeStartIndex + k] = avgTap;
  52308. cubeMap[neighborFace][neighborEdgeStartIndex + k] = avgTap;
  52309. }
  52310. edgeStartIndex += edgeWalk;
  52311. neighborEdgeStartIndex += neighborEdgeWalk;
  52312. }
  52313. }
  52314. };
  52315. return PMREMGenerator;
  52316. }());
  52317. PMREMGenerator.CP_MAX_MIPLEVELS = 16;
  52318. PMREMGenerator.CP_UDIR = 0;
  52319. PMREMGenerator.CP_VDIR = 1;
  52320. PMREMGenerator.CP_FACEAXIS = 2;
  52321. //used to index cube faces
  52322. PMREMGenerator.CP_FACE_X_POS = 0;
  52323. PMREMGenerator.CP_FACE_X_NEG = 1;
  52324. PMREMGenerator.CP_FACE_Y_POS = 2;
  52325. PMREMGenerator.CP_FACE_Y_NEG = 3;
  52326. PMREMGenerator.CP_FACE_Z_POS = 4;
  52327. PMREMGenerator.CP_FACE_Z_NEG = 5;
  52328. //used to index image edges
  52329. // NOTE.. the actual number corresponding to the edge is important
  52330. // do not change these, or the code will break
  52331. //
  52332. // CP_EDGE_LEFT is u = 0
  52333. // CP_EDGE_RIGHT is u = width-1
  52334. // CP_EDGE_TOP is v = 0
  52335. // CP_EDGE_BOTTOM is v = height-1
  52336. PMREMGenerator.CP_EDGE_LEFT = 0;
  52337. PMREMGenerator.CP_EDGE_RIGHT = 1;
  52338. PMREMGenerator.CP_EDGE_TOP = 2;
  52339. PMREMGenerator.CP_EDGE_BOTTOM = 3;
  52340. //corners of CUBE map (P or N specifys if it corresponds to the
  52341. // positive or negative direction each of X, Y, and Z
  52342. PMREMGenerator.CP_CORNER_NNN = 0;
  52343. PMREMGenerator.CP_CORNER_NNP = 1;
  52344. PMREMGenerator.CP_CORNER_NPN = 2;
  52345. PMREMGenerator.CP_CORNER_NPP = 3;
  52346. PMREMGenerator.CP_CORNER_PNN = 4;
  52347. PMREMGenerator.CP_CORNER_PNP = 5;
  52348. PMREMGenerator.CP_CORNER_PPN = 6;
  52349. PMREMGenerator.CP_CORNER_PPP = 7;
  52350. PMREMGenerator._vectorTemp = new BABYLON.Vector4(0, 0, 0, 0);
  52351. //3x2 matrices that map cube map indexing vectors in 3d
  52352. // (after face selection and divide through by the
  52353. // _ABSOLUTE VALUE_ of the max coord)
  52354. // into NVC space
  52355. //Note this currently assumes the D3D cube face ordering and orientation
  52356. PMREMGenerator._sgFace2DMapping = [
  52357. //XPOS face
  52358. [[0, 0, -1],
  52359. [0, -1, 0],
  52360. [1, 0, 0]],
  52361. //XNEG face
  52362. [[0, 0, 1],
  52363. [0, -1, 0],
  52364. [-1, 0, 0]],
  52365. //YPOS face
  52366. [[1, 0, 0],
  52367. [0, 0, 1],
  52368. [0, 1, 0]],
  52369. //YNEG face
  52370. [[1, 0, 0],
  52371. [0, 0, -1],
  52372. [0, -1, 0]],
  52373. //ZPOS face
  52374. [[1, 0, 0],
  52375. [0, -1, 0],
  52376. [0, 0, 1]],
  52377. //ZNEG face
  52378. [[-1, 0, 0],
  52379. [0, -1, 0],
  52380. [0, 0, -1]],
  52381. ];
  52382. //------------------------------------------------------------------------------
  52383. // D3D cube map face specification
  52384. // mapping from 3D x,y,z cube map lookup coordinates
  52385. // to 2D within face u,v coordinates
  52386. //
  52387. // --------------------> U direction
  52388. // | (within-face texture space)
  52389. // | _____
  52390. // | | |
  52391. // | | +Y |
  52392. // | _____|_____|_____ _____
  52393. // | | | | | |
  52394. // | | -X | +Z | +X | -Z |
  52395. // | |_____|_____|_____|_____|
  52396. // | | |
  52397. // | | -Y |
  52398. // | |_____|
  52399. // |
  52400. // v V direction
  52401. // (within-face texture space)
  52402. //------------------------------------------------------------------------------
  52403. //Information about neighbors and how texture coorrdinates change across faces
  52404. // in ORDER of left, right, top, bottom (e.g. edges corresponding to u=0,
  52405. // u=1, v=0, v=1 in the 2D coordinate system of the particular face.
  52406. //Note this currently assumes the D3D cube face ordering and orientation
  52407. PMREMGenerator._sgCubeNgh = [
  52408. //XPOS face
  52409. [[PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_RIGHT],
  52410. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_LEFT],
  52411. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_RIGHT],
  52412. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_RIGHT]],
  52413. //XNEG face
  52414. [[PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  52415. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_LEFT],
  52416. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_LEFT],
  52417. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_LEFT]],
  52418. //YPOS face
  52419. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  52420. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  52421. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  52422. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP]],
  52423. //YNEG face
  52424. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  52425. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  52426. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  52427. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]],
  52428. //ZPOS face
  52429. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  52430. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  52431. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  52432. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_TOP]],
  52433. //ZNEG face
  52434. [[PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  52435. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  52436. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_TOP],
  52437. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_BOTTOM]]
  52438. ];
  52439. //The 12 edges of the cubemap, (entries are used to index into the neighbor table)
  52440. // this table is used to average over the edges.
  52441. PMREMGenerator._sgCubeEdgeList = [
  52442. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  52443. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  52444. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  52445. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  52446. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  52447. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  52448. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  52449. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  52450. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP],
  52451. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  52452. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  52453. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]
  52454. ];
  52455. //Information about which of the 8 cube corners are correspond to the
  52456. // the 4 corners in each cube face
  52457. // the order is upper left, upper right, lower left, lower right
  52458. PMREMGenerator._sgCubeCornerList = [
  52459. [PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_PNN],
  52460. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_NNP],
  52461. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP],
  52462. [PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_PNN],
  52463. [PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP],
  52464. [PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PNN, PMREMGenerator.CP_CORNER_NNN] // ZNEG face
  52465. ];
  52466. Internals.PMREMGenerator = PMREMGenerator;
  52467. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  52468. })(BABYLON || (BABYLON = {}));
  52469. //# sourceMappingURL=babylon.pmremgenerator.js.map
  52470. var BABYLON;
  52471. (function (BABYLON) {
  52472. /**
  52473. * This represents a texture coming from an HDR input.
  52474. *
  52475. * The only supported format is currently panorama picture stored in RGBE format.
  52476. * Example of such files can be found on HDRLib: http://hdrlib.com/
  52477. */
  52478. var HDRCubeTexture = (function (_super) {
  52479. __extends(HDRCubeTexture, _super);
  52480. /**
  52481. * Instantiates an HDRTexture from the following parameters.
  52482. *
  52483. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  52484. * @param scene The scene the texture will be used in
  52485. * @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.
  52486. * @param noMipmap Forces to not generate the mipmap if true
  52487. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  52488. * @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)
  52489. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  52490. */
  52491. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  52492. if (noMipmap === void 0) { noMipmap = false; }
  52493. if (generateHarmonics === void 0) { generateHarmonics = true; }
  52494. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  52495. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  52496. if (onLoad === void 0) { onLoad = null; }
  52497. if (onError === void 0) { onError = null; }
  52498. var _this = _super.call(this, scene) || this;
  52499. _this._useInGammaSpace = false;
  52500. _this._generateHarmonics = true;
  52501. _this._isBABYLONPreprocessed = false;
  52502. _this._onLoad = null;
  52503. _this._onError = null;
  52504. /**
  52505. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  52506. */
  52507. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  52508. /**
  52509. * The spherical polynomial data extracted from the texture.
  52510. */
  52511. _this.sphericalPolynomial = null;
  52512. /**
  52513. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  52514. * This is usefull at run time to apply the good shader.
  52515. */
  52516. _this.isPMREM = false;
  52517. if (!url) {
  52518. return _this;
  52519. }
  52520. _this.name = url;
  52521. _this.url = url;
  52522. _this.hasAlpha = false;
  52523. _this.isCube = true;
  52524. _this._textureMatrix = BABYLON.Matrix.Identity();
  52525. _this._onLoad = onLoad;
  52526. _this._onError = onError;
  52527. if (size) {
  52528. _this._isBABYLONPreprocessed = false;
  52529. _this._noMipmap = noMipmap;
  52530. _this._size = size;
  52531. _this._useInGammaSpace = useInGammaSpace;
  52532. _this._usePMREMGenerator = usePMREMGenerator &&
  52533. scene.getEngine().getCaps().textureLOD &&
  52534. _this.getScene().getEngine().getCaps().textureFloat &&
  52535. !_this._useInGammaSpace;
  52536. }
  52537. else {
  52538. _this._isBABYLONPreprocessed = true;
  52539. _this._noMipmap = false;
  52540. _this._useInGammaSpace = false;
  52541. _this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD &&
  52542. _this.getScene().getEngine().getCaps().textureFloat &&
  52543. !_this._useInGammaSpace;
  52544. }
  52545. _this.isPMREM = _this._usePMREMGenerator;
  52546. _this._texture = _this._getFromCache(url, _this._noMipmap);
  52547. if (!_this._texture) {
  52548. if (!scene.useDelayedTextureLoading) {
  52549. _this.loadTexture();
  52550. }
  52551. else {
  52552. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  52553. }
  52554. }
  52555. return _this;
  52556. }
  52557. /**
  52558. * Occurs when the file is a preprocessed .babylon.hdr file.
  52559. */
  52560. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  52561. var _this = this;
  52562. var mipLevels = 0;
  52563. var floatArrayView = null;
  52564. var mipmapGenerator = (!this._useInGammaSpace && this.getScene().getEngine().getCaps().textureFloat) ? function (data) {
  52565. var mips = [];
  52566. var startIndex = 30;
  52567. for (var level = 0; level < mipLevels; level++) {
  52568. mips.push([]);
  52569. // Fill each pixel of the mip level.
  52570. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  52571. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  52572. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  52573. mips[level].push(faceData);
  52574. startIndex += faceSize;
  52575. }
  52576. }
  52577. return mips;
  52578. } : null;
  52579. var callback = function (buffer) {
  52580. // Create Native Array Views
  52581. var intArrayView = new Int32Array(buffer);
  52582. floatArrayView = new Float32Array(buffer);
  52583. // Fill header.
  52584. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  52585. _this._size = intArrayView[1]; // CubeMap max mip face size.
  52586. // Update Texture Information.
  52587. _this.getScene().getEngine().updateTextureSize(_this._texture, _this._size, _this._size);
  52588. // Fill polynomial information.
  52589. _this.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  52590. _this.sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  52591. _this.sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  52592. _this.sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  52593. _this.sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  52594. _this.sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  52595. _this.sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  52596. _this.sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  52597. _this.sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  52598. _this.sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  52599. // Fill pixel data.
  52600. mipLevels = intArrayView[29]; // Number of mip levels.
  52601. var startIndex = 30;
  52602. var data = [];
  52603. var faceSize = Math.pow(_this._size, 2) * 3;
  52604. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  52605. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  52606. startIndex += faceSize;
  52607. }
  52608. var results = [];
  52609. var byteArray = null;
  52610. // Push each faces.
  52611. for (var k = 0; k < 6; k++) {
  52612. var dataFace = null;
  52613. // If special cases.
  52614. if (!mipmapGenerator) {
  52615. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y... if no mipmapgenerator...
  52616. dataFace = data[j];
  52617. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  52618. // 3 channels of 1 bytes per pixel in bytes.
  52619. var byteBuffer = new ArrayBuffer(faceSize);
  52620. byteArray = new Uint8Array(byteBuffer);
  52621. }
  52622. for (var i = 0; i < _this._size * _this._size; i++) {
  52623. // Put in gamma space if requested.
  52624. if (_this._useInGammaSpace) {
  52625. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  52626. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  52627. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  52628. }
  52629. // Convert to int texture for fallback.
  52630. if (byteArray) {
  52631. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  52632. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  52633. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  52634. // May use luminance instead if the result is not accurate.
  52635. var max = Math.max(Math.max(r, g), b);
  52636. if (max > 255) {
  52637. var scale = 255 / max;
  52638. r *= scale;
  52639. g *= scale;
  52640. b *= scale;
  52641. }
  52642. byteArray[(i * 3) + 0] = r;
  52643. byteArray[(i * 3) + 1] = g;
  52644. byteArray[(i * 3) + 2] = b;
  52645. }
  52646. }
  52647. }
  52648. else {
  52649. dataFace = data[k];
  52650. }
  52651. // Fill the array accordingly.
  52652. if (byteArray) {
  52653. results.push(byteArray);
  52654. }
  52655. else {
  52656. results.push(dataFace);
  52657. }
  52658. }
  52659. return results;
  52660. };
  52661. 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);
  52662. };
  52663. /**
  52664. * Occurs when the file is raw .hdr file.
  52665. */
  52666. HDRCubeTexture.prototype.loadHDRTexture = function () {
  52667. var _this = this;
  52668. var callback = function (buffer) {
  52669. // Extract the raw linear data.
  52670. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  52671. // Generate harmonics if needed.
  52672. if (_this._generateHarmonics) {
  52673. _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  52674. }
  52675. var results = [];
  52676. var byteArray = null;
  52677. // Push each faces.
  52678. for (var j = 0; j < 6; j++) {
  52679. // Create uintarray fallback.
  52680. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  52681. // 3 channels of 1 bytes per pixel in bytes.
  52682. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  52683. byteArray = new Uint8Array(byteBuffer);
  52684. }
  52685. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  52686. // If special cases.
  52687. if (_this._useInGammaSpace || byteArray) {
  52688. for (var i = 0; i < _this._size * _this._size; i++) {
  52689. // Put in gamma space if requested.
  52690. if (_this._useInGammaSpace) {
  52691. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  52692. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  52693. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  52694. }
  52695. // Convert to int texture for fallback.
  52696. if (byteArray) {
  52697. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  52698. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  52699. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  52700. // May use luminance instead if the result is not accurate.
  52701. var max = Math.max(Math.max(r, g), b);
  52702. if (max > 255) {
  52703. var scale = 255 / max;
  52704. r *= scale;
  52705. g *= scale;
  52706. b *= scale;
  52707. }
  52708. byteArray[(i * 3) + 0] = r;
  52709. byteArray[(i * 3) + 1] = g;
  52710. byteArray[(i * 3) + 2] = b;
  52711. }
  52712. }
  52713. }
  52714. if (byteArray) {
  52715. results.push(byteArray);
  52716. }
  52717. else {
  52718. results.push(dataFace);
  52719. }
  52720. }
  52721. return results;
  52722. };
  52723. var mipmapGenerator = null;
  52724. if (!this._noMipmap &&
  52725. this._usePMREMGenerator) {
  52726. mipmapGenerator = function (data) {
  52727. // Custom setup of the generator matching with the PBR shader values.
  52728. var generator = new BABYLON.Internals.PMREMGenerator(data, _this._size, _this._size, 0, 3, _this.getScene().getEngine().getCaps().textureFloat, 2048, 0.25, false, true);
  52729. return generator.filterCubeMap();
  52730. };
  52731. }
  52732. 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);
  52733. };
  52734. /**
  52735. * Starts the loading process of the texture.
  52736. */
  52737. HDRCubeTexture.prototype.loadTexture = function () {
  52738. if (this._isBABYLONPreprocessed) {
  52739. this.loadBabylonTexture();
  52740. }
  52741. else {
  52742. this.loadHDRTexture();
  52743. }
  52744. };
  52745. HDRCubeTexture.prototype.clone = function () {
  52746. var size = this._isBABYLONPreprocessed ? null : this._size;
  52747. var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  52748. // Base texture
  52749. newTexture.level = this.level;
  52750. newTexture.wrapU = this.wrapU;
  52751. newTexture.wrapV = this.wrapV;
  52752. newTexture.coordinatesIndex = this.coordinatesIndex;
  52753. newTexture.coordinatesMode = this.coordinatesMode;
  52754. return newTexture;
  52755. };
  52756. // Methods
  52757. HDRCubeTexture.prototype.delayLoad = function () {
  52758. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  52759. return;
  52760. }
  52761. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  52762. this._texture = this._getFromCache(this.url, this._noMipmap);
  52763. if (!this._texture) {
  52764. this.loadTexture();
  52765. }
  52766. };
  52767. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  52768. return this._textureMatrix;
  52769. };
  52770. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  52771. var texture = null;
  52772. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  52773. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  52774. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  52775. texture.name = parsedTexture.name;
  52776. texture.hasAlpha = parsedTexture.hasAlpha;
  52777. texture.level = parsedTexture.level;
  52778. texture.coordinatesMode = parsedTexture.coordinatesMode;
  52779. }
  52780. return texture;
  52781. };
  52782. HDRCubeTexture.prototype.serialize = function () {
  52783. if (!this.name) {
  52784. return null;
  52785. }
  52786. var serializationObject = {};
  52787. serializationObject.name = this.name;
  52788. serializationObject.hasAlpha = this.hasAlpha;
  52789. serializationObject.isCube = true;
  52790. serializationObject.level = this.level;
  52791. serializationObject.size = this._size;
  52792. serializationObject.coordinatesMode = this.coordinatesMode;
  52793. serializationObject.useInGammaSpace = this._useInGammaSpace;
  52794. serializationObject.generateHarmonics = this._generateHarmonics;
  52795. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  52796. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  52797. serializationObject.customType = "BABYLON.HDRCubeTexture";
  52798. serializationObject.noMipmap = this._noMipmap;
  52799. return serializationObject;
  52800. };
  52801. /**
  52802. * Saves as a file the data contained in the texture in a binary format.
  52803. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  52804. * as the spherical used in the lighting.
  52805. * @param url The HDR file url.
  52806. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  52807. * @param onError Method called if any error happens during download.
  52808. * @return The packed binary data.
  52809. */
  52810. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  52811. if (onError === void 0) { onError = null; }
  52812. var callback = function (buffer) {
  52813. var data = new Blob([buffer], { type: 'application/octet-stream' });
  52814. // Returns a URL you can use as a href.
  52815. var objUrl = window.URL.createObjectURL(data);
  52816. // Simulates a link to it and click to dowload.
  52817. var a = document.createElement("a");
  52818. document.body.appendChild(a);
  52819. a.style.display = "none";
  52820. a.href = objUrl;
  52821. a.download = "envmap.babylon.hdr";
  52822. a.click();
  52823. };
  52824. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  52825. };
  52826. /**
  52827. * Serializes the data contained in the texture in a binary format.
  52828. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  52829. * as the spherical used in the lighting.
  52830. * @param url The HDR file url.
  52831. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  52832. * @param onError Method called if any error happens during download.
  52833. * @return The packed binary data.
  52834. */
  52835. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  52836. if (onError === void 0) { onError = null; }
  52837. // Needs the url tho create the texture.
  52838. if (!url) {
  52839. return null;
  52840. }
  52841. // Check Power of two size.
  52842. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  52843. return null;
  52844. }
  52845. var getDataCallback = function (dataBuffer) {
  52846. // Extract the raw linear data.
  52847. var cubeData = BABYLON.Internals.HDRTools.GetCubeMapTextureData(dataBuffer, size);
  52848. // Generate harmonics if needed.
  52849. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(cubeData);
  52850. // Generate seamless faces
  52851. var mipGeneratorArray = [];
  52852. // Data are known to be in +X +Y +Z -X -Y -Z
  52853. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  52854. mipGeneratorArray.push(cubeData.right); // +X
  52855. mipGeneratorArray.push(cubeData.left); // -X
  52856. mipGeneratorArray.push(cubeData.up); // +Y
  52857. mipGeneratorArray.push(cubeData.down); // -Y
  52858. mipGeneratorArray.push(cubeData.front); // +Z
  52859. mipGeneratorArray.push(cubeData.back); // -Z
  52860. // Custom setup of the generator matching with the PBR shader values.
  52861. var generator = new BABYLON.Internals.PMREMGenerator(mipGeneratorArray, size, size, 0, 3, true, 2048, 0.25, false, true);
  52862. var mippedData = generator.filterCubeMap();
  52863. // Compute required byte length.
  52864. var byteLength = 1 * 4; // Raw Data Version int32.
  52865. byteLength += 4; // CubeMap max mip face size int32.
  52866. byteLength += (9 * 3 * 4); // Spherical polynomial byte length 9 Vector 3 of floats.
  52867. // Add data size.
  52868. byteLength += 4; // Number of mip levels int32.
  52869. for (var level = 0; level < mippedData.length; level++) {
  52870. var mipSize = size >> level;
  52871. byteLength += (6 * mipSize * mipSize * 3 * 4); // 6 faces of size squared rgb float pixels.
  52872. }
  52873. // Prepare binary structure.
  52874. var buffer = new ArrayBuffer(byteLength);
  52875. var intArrayView = new Int32Array(buffer);
  52876. var floatArrayView = new Float32Array(buffer);
  52877. // Fill header.
  52878. intArrayView[0] = 1; // Version 1.
  52879. intArrayView[1] = size; // CubeMap max mip face size.
  52880. // Fill polynomial information.
  52881. sphericalPolynomial.x.toArray(floatArrayView, 2);
  52882. sphericalPolynomial.y.toArray(floatArrayView, 5);
  52883. sphericalPolynomial.z.toArray(floatArrayView, 8);
  52884. sphericalPolynomial.xx.toArray(floatArrayView, 11);
  52885. sphericalPolynomial.yy.toArray(floatArrayView, 14);
  52886. sphericalPolynomial.zz.toArray(floatArrayView, 17);
  52887. sphericalPolynomial.xy.toArray(floatArrayView, 20);
  52888. sphericalPolynomial.yz.toArray(floatArrayView, 23);
  52889. sphericalPolynomial.zx.toArray(floatArrayView, 26);
  52890. // Fill pixel data.
  52891. intArrayView[29] = mippedData.length; // Number of mip levels.
  52892. var startIndex = 30;
  52893. for (var level = 0; level < mippedData.length; level++) {
  52894. // Fill each pixel of the mip level.
  52895. var faceSize = Math.pow(size >> level, 2) * 3;
  52896. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  52897. floatArrayView.set(mippedData[level][faceIndex], startIndex);
  52898. startIndex += faceSize;
  52899. }
  52900. }
  52901. // Callback.
  52902. callback(buffer);
  52903. };
  52904. // Download and process.
  52905. BABYLON.Tools.LoadFile(url, function (data) {
  52906. getDataCallback(data);
  52907. }, null, null, true, onError);
  52908. };
  52909. return HDRCubeTexture;
  52910. }(BABYLON.BaseTexture));
  52911. HDRCubeTexture._facesMapping = [
  52912. "right",
  52913. "up",
  52914. "front",
  52915. "left",
  52916. "down",
  52917. "back"
  52918. ];
  52919. BABYLON.HDRCubeTexture = HDRCubeTexture;
  52920. })(BABYLON || (BABYLON = {}));
  52921. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  52922. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  52923. // Huge respect for a such great lib.
  52924. // Earcut license:
  52925. // Copyright (c) 2016, Mapbox
  52926. //
  52927. // Permission to use, copy, modify, and/or distribute this software for any purpose
  52928. // with or without fee is hereby granted, provided that the above copyright notice
  52929. // and this permission notice appear in all copies.
  52930. //
  52931. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  52932. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  52933. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  52934. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  52935. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  52936. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  52937. // THIS SOFTWARE.
  52938. var Earcut;
  52939. (function (Earcut) {
  52940. /**
  52941. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  52942. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  52943. * @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).
  52944. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  52945. */
  52946. function earcut(data, holeIndices, dim) {
  52947. dim = dim || 2;
  52948. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = [];
  52949. if (!outerNode)
  52950. return triangles;
  52951. var minX, minY, maxX, maxY, x, y, size;
  52952. if (hasHoles)
  52953. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  52954. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  52955. if (data.length > 80 * dim) {
  52956. minX = maxX = data[0];
  52957. minY = maxY = data[1];
  52958. for (var i = dim; i < outerLen; i += dim) {
  52959. x = data[i];
  52960. y = data[i + 1];
  52961. if (x < minX)
  52962. minX = x;
  52963. if (y < minY)
  52964. minY = y;
  52965. if (x > maxX)
  52966. maxX = x;
  52967. if (y > maxY)
  52968. maxY = y;
  52969. }
  52970. // minX, minY and size are later used to transform coords into integers for z-order calculation
  52971. size = Math.max(maxX - minX, maxY - minY);
  52972. }
  52973. earcutLinked(outerNode, triangles, dim, minX, minY, size, undefined);
  52974. return triangles;
  52975. }
  52976. Earcut.earcut = earcut;
  52977. // create a circular doubly linked list from polygon points in the specified winding order
  52978. function linkedList(data, start, end, dim, clockwise) {
  52979. var i, last;
  52980. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  52981. for (i = start; i < end; i += dim)
  52982. last = insertNode(i, data[i], data[i + 1], last);
  52983. }
  52984. else {
  52985. for (i = end - dim; i >= start; i -= dim)
  52986. last = insertNode(i, data[i], data[i + 1], last);
  52987. }
  52988. if (last && equals(last, last.next)) {
  52989. removeNode(last);
  52990. last = last.next;
  52991. }
  52992. return last;
  52993. }
  52994. // eliminate colinear or duplicate points
  52995. function filterPoints(start, end) {
  52996. if (!start)
  52997. return start;
  52998. if (!end)
  52999. end = start;
  53000. var p = start, again;
  53001. do {
  53002. again = false;
  53003. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  53004. removeNode(p);
  53005. p = end = p.prev;
  53006. if (p === p.next)
  53007. return null;
  53008. again = true;
  53009. }
  53010. else {
  53011. p = p.next;
  53012. }
  53013. } while (again || p !== end);
  53014. return end;
  53015. }
  53016. // main ear slicing loop which triangulates a polygon (given as a linked list)
  53017. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  53018. if (!ear)
  53019. return;
  53020. // interlink polygon nodes in z-order
  53021. if (!pass && size)
  53022. indexCurve(ear, minX, minY, size);
  53023. var stop = ear, prev, next;
  53024. // iterate through ears, slicing them one by one
  53025. while (ear.prev !== ear.next) {
  53026. prev = ear.prev;
  53027. next = ear.next;
  53028. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  53029. // cut off the triangle
  53030. triangles.push(prev.i / dim);
  53031. triangles.push(ear.i / dim);
  53032. triangles.push(next.i / dim);
  53033. removeNode(ear);
  53034. // skipping the next vertice leads to less sliver triangles
  53035. ear = next.next;
  53036. stop = next.next;
  53037. continue;
  53038. }
  53039. ear = next;
  53040. // if we looped through the whole remaining polygon and can't find any more ears
  53041. if (ear === stop) {
  53042. // try filtering points and slicing again
  53043. if (!pass) {
  53044. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  53045. // if this didn't work, try curing all small self-intersections locally
  53046. }
  53047. else if (pass === 1) {
  53048. ear = cureLocalIntersections(ear, triangles, dim);
  53049. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  53050. // as a last resort, try splitting the remaining polygon into two
  53051. }
  53052. else if (pass === 2) {
  53053. splitEarcut(ear, triangles, dim, minX, minY, size);
  53054. }
  53055. break;
  53056. }
  53057. }
  53058. }
  53059. // check whether a polygon node forms a valid ear with adjacent nodes
  53060. function isEar(ear) {
  53061. var a = ear.prev, b = ear, c = ear.next;
  53062. if (area(a, b, c) >= 0)
  53063. return false; // reflex, can't be an ear
  53064. // now make sure we don't have other points inside the potential ear
  53065. var p = ear.next.next;
  53066. while (p !== ear.prev) {
  53067. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  53068. area(p.prev, p, p.next) >= 0)
  53069. return false;
  53070. p = p.next;
  53071. }
  53072. return true;
  53073. }
  53074. function isEarHashed(ear, minX, minY, size) {
  53075. var a = ear.prev, b = ear, c = ear.next;
  53076. if (area(a, b, c) >= 0)
  53077. return false; // reflex, can't be an ear
  53078. // triangle bbox; min & max are calculated like this for speed
  53079. 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);
  53080. // z-order range for the current triangle bbox;
  53081. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  53082. // first look for points inside the triangle in increasing z-order
  53083. var p = ear.nextZ;
  53084. while (p && p.z <= maxZ) {
  53085. if (p !== ear.prev &&
  53086. p !== ear.next &&
  53087. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  53088. area(p.prev, p, p.next) >= 0)
  53089. return false;
  53090. p = p.nextZ;
  53091. }
  53092. // then look for points in decreasing z-order
  53093. p = ear.prevZ;
  53094. while (p && p.z >= minZ) {
  53095. if (p !== ear.prev &&
  53096. p !== ear.next &&
  53097. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  53098. area(p.prev, p, p.next) >= 0)
  53099. return false;
  53100. p = p.prevZ;
  53101. }
  53102. return true;
  53103. }
  53104. // go through all polygon nodes and cure small local self-intersections
  53105. function cureLocalIntersections(start, triangles, dim) {
  53106. var p = start;
  53107. do {
  53108. var a = p.prev, b = p.next.next;
  53109. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  53110. triangles.push(a.i / dim);
  53111. triangles.push(p.i / dim);
  53112. triangles.push(b.i / dim);
  53113. // remove two nodes involved
  53114. removeNode(p);
  53115. removeNode(p.next);
  53116. p = start = b;
  53117. }
  53118. p = p.next;
  53119. } while (p !== start);
  53120. return p;
  53121. }
  53122. // try splitting polygon into two and triangulate them independently
  53123. function splitEarcut(start, triangles, dim, minX, minY, size) {
  53124. // look for a valid diagonal that divides the polygon into two
  53125. var a = start;
  53126. do {
  53127. var b = a.next.next;
  53128. while (b !== a.prev) {
  53129. if (a.i !== b.i && isValidDiagonal(a, b)) {
  53130. // split the polygon in two by the diagonal
  53131. var c = splitPolygon(a, b);
  53132. // filter colinear points around the cuts
  53133. a = filterPoints(a, a.next);
  53134. c = filterPoints(c, c.next);
  53135. // run earcut on each half
  53136. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  53137. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  53138. return;
  53139. }
  53140. b = b.next;
  53141. }
  53142. a = a.next;
  53143. } while (a !== start);
  53144. }
  53145. // link every hole into the outer loop, producing a single-ring polygon without holes
  53146. function eliminateHoles(data, holeIndices, outerNode, dim) {
  53147. var queue = [], i, len, start, end, list;
  53148. for (i = 0, len = holeIndices.length; i < len; i++) {
  53149. start = holeIndices[i] * dim;
  53150. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  53151. list = linkedList(data, start, end, dim, false);
  53152. if (list === list.next)
  53153. list.steiner = true;
  53154. queue.push(getLeftmost(list));
  53155. }
  53156. queue.sort(compareX);
  53157. // process holes from left to right
  53158. for (i = 0; i < queue.length; i++) {
  53159. eliminateHole(queue[i], outerNode);
  53160. outerNode = filterPoints(outerNode, outerNode.next);
  53161. }
  53162. return outerNode;
  53163. }
  53164. function compareX(a, b) {
  53165. return a.x - b.x;
  53166. }
  53167. // find a bridge between vertices that connects hole with an outer ring and and link it
  53168. function eliminateHole(hole, outerNode) {
  53169. outerNode = findHoleBridge(hole, outerNode);
  53170. if (outerNode) {
  53171. var b = splitPolygon(outerNode, hole);
  53172. filterPoints(b, b.next);
  53173. }
  53174. }
  53175. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  53176. function findHoleBridge(hole, outerNode) {
  53177. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  53178. // find a segment intersected by a ray from the hole's leftmost point to the left;
  53179. // segment's endpoint with lesser x will be potential connection point
  53180. do {
  53181. if (hy <= p.y && hy >= p.next.y) {
  53182. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  53183. if (x <= hx && x > qx) {
  53184. qx = x;
  53185. if (x === hx) {
  53186. if (hy === p.y)
  53187. return p;
  53188. if (hy === p.next.y)
  53189. return p.next;
  53190. }
  53191. m = p.x < p.next.x ? p : p.next;
  53192. }
  53193. }
  53194. p = p.next;
  53195. } while (p !== outerNode);
  53196. if (!m)
  53197. return null;
  53198. if (hx === qx)
  53199. return m.prev; // hole touches outer segment; pick lower endpoint
  53200. // look for points inside the triangle of hole point, segment intersection and endpoint;
  53201. // if there are no points found, we have a valid connection;
  53202. // otherwise choose the point of the minimum angle with the ray as connection point
  53203. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  53204. p = m.next;
  53205. while (p !== stop) {
  53206. if (hx >= p.x &&
  53207. p.x >= mx &&
  53208. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  53209. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  53210. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  53211. m = p;
  53212. tanMin = tan;
  53213. }
  53214. }
  53215. p = p.next;
  53216. }
  53217. return m;
  53218. }
  53219. // interlink polygon nodes in z-order
  53220. function indexCurve(start, minX, minY, size) {
  53221. var p = start;
  53222. do {
  53223. if (p.z === null)
  53224. p.z = zOrder(p.x, p.y, minX, minY, size);
  53225. p.prevZ = p.prev;
  53226. p.nextZ = p.next;
  53227. p = p.next;
  53228. } while (p !== start);
  53229. p.prevZ.nextZ = null;
  53230. p.prevZ = null;
  53231. sortLinked(p);
  53232. }
  53233. // Simon Tatham's linked list merge sort algorithm
  53234. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  53235. function sortLinked(list) {
  53236. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  53237. do {
  53238. p = list;
  53239. list = null;
  53240. tail = null;
  53241. numMerges = 0;
  53242. while (p) {
  53243. numMerges++;
  53244. q = p;
  53245. pSize = 0;
  53246. for (i = 0; i < inSize; i++) {
  53247. pSize++;
  53248. q = q.nextZ;
  53249. if (!q)
  53250. break;
  53251. }
  53252. qSize = inSize;
  53253. while (pSize > 0 || (qSize > 0 && q)) {
  53254. if (pSize === 0) {
  53255. e = q;
  53256. q = q.nextZ;
  53257. qSize--;
  53258. }
  53259. else if (qSize === 0 || !q) {
  53260. e = p;
  53261. p = p.nextZ;
  53262. pSize--;
  53263. }
  53264. else if (p.z <= q.z) {
  53265. e = p;
  53266. p = p.nextZ;
  53267. pSize--;
  53268. }
  53269. else {
  53270. e = q;
  53271. q = q.nextZ;
  53272. qSize--;
  53273. }
  53274. if (tail)
  53275. tail.nextZ = e;
  53276. else
  53277. list = e;
  53278. e.prevZ = tail;
  53279. tail = e;
  53280. }
  53281. p = q;
  53282. }
  53283. tail.nextZ = null;
  53284. inSize *= 2;
  53285. } while (numMerges > 1);
  53286. return list;
  53287. }
  53288. // z-order of a point given coords and size of the data bounding box
  53289. function zOrder(x, y, minX, minY, size) {
  53290. // coords are transformed into non-negative 15-bit integer range
  53291. x = 32767 * (x - minX) / size;
  53292. y = 32767 * (y - minY) / size;
  53293. x = (x | (x << 8)) & 0x00FF00FF;
  53294. x = (x | (x << 4)) & 0x0F0F0F0F;
  53295. x = (x | (x << 2)) & 0x33333333;
  53296. x = (x | (x << 1)) & 0x55555555;
  53297. y = (y | (y << 8)) & 0x00FF00FF;
  53298. y = (y | (y << 4)) & 0x0F0F0F0F;
  53299. y = (y | (y << 2)) & 0x33333333;
  53300. y = (y | (y << 1)) & 0x55555555;
  53301. return x | (y << 1);
  53302. }
  53303. // find the leftmost node of a polygon ring
  53304. function getLeftmost(start) {
  53305. var p = start, leftmost = start;
  53306. do {
  53307. if (p.x < leftmost.x)
  53308. leftmost = p;
  53309. p = p.next;
  53310. } while (p !== start);
  53311. return leftmost;
  53312. }
  53313. // check if a point lies within a convex triangle
  53314. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  53315. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  53316. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  53317. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  53318. }
  53319. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  53320. function isValidDiagonal(a, b) {
  53321. return a.next.i !== b.i &&
  53322. a.prev.i !== b.i &&
  53323. !intersectsPolygon(a, b) &&
  53324. locallyInside(a, b) &&
  53325. locallyInside(b, a) &&
  53326. middleInside(a, b);
  53327. }
  53328. // signed area of a triangle
  53329. function area(p, q, r) {
  53330. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  53331. }
  53332. // check if two points are equal
  53333. function equals(p1, p2) {
  53334. return p1.x === p2.x && p1.y === p2.y;
  53335. }
  53336. // check if two segments intersect
  53337. function intersects(p1, q1, p2, q2) {
  53338. if ((equals(p1, q1) && equals(p2, q2)) ||
  53339. (equals(p1, q2) && equals(p2, q1)))
  53340. return true;
  53341. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  53342. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  53343. }
  53344. // check if a polygon diagonal intersects any polygon segments
  53345. function intersectsPolygon(a, b) {
  53346. var p = a;
  53347. do {
  53348. if (p.i !== a.i &&
  53349. p.next.i !== a.i &&
  53350. p.i !== b.i &&
  53351. p.next.i !== b.i &&
  53352. intersects(p, p.next, a, b))
  53353. return true;
  53354. p = p.next;
  53355. } while (p !== a);
  53356. return false;
  53357. }
  53358. // check if a polygon diagonal is locally inside the polygon
  53359. function locallyInside(a, b) {
  53360. return area(a.prev, a, a.next) < 0
  53361. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  53362. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  53363. }
  53364. // check if the middle point of a polygon diagonal is inside the polygon
  53365. function middleInside(a, b) {
  53366. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  53367. do {
  53368. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  53369. inside = !inside;
  53370. p = p.next;
  53371. } while (p !== a);
  53372. return inside;
  53373. }
  53374. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  53375. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  53376. function splitPolygon(a, b) {
  53377. 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;
  53378. a.next = b;
  53379. b.prev = a;
  53380. a2.next = an;
  53381. an.prev = a2;
  53382. b2.next = a2;
  53383. a2.prev = b2;
  53384. bp.next = b2;
  53385. b2.prev = bp;
  53386. return b2;
  53387. }
  53388. // create a node and optionally link it with previous one (in a circular doubly linked list)
  53389. function insertNode(i, x, y, last) {
  53390. var p = new Node(i, x, y);
  53391. if (!last) {
  53392. p.prev = p;
  53393. p.next = p;
  53394. }
  53395. else {
  53396. p.next = last.next;
  53397. p.prev = last;
  53398. last.next.prev = p;
  53399. last.next = p;
  53400. }
  53401. return p;
  53402. }
  53403. function removeNode(p) {
  53404. p.next.prev = p.prev;
  53405. p.prev.next = p.next;
  53406. if (p.prevZ)
  53407. p.prevZ.nextZ = p.nextZ;
  53408. if (p.nextZ)
  53409. p.nextZ.prevZ = p.prevZ;
  53410. }
  53411. function Node(i, x, y) {
  53412. // vertice index in coordinates array
  53413. this.i = i;
  53414. // vertex coordinates
  53415. this.x = x;
  53416. this.y = y;
  53417. // previous and next vertice nodes in a polygon ring
  53418. this.prev = null;
  53419. this.next = null;
  53420. // z-order curve value
  53421. this.z = null;
  53422. // previous and next nodes in z-order
  53423. this.prevZ = null;
  53424. this.nextZ = null;
  53425. // indicates whether this is a steiner point
  53426. this.steiner = false;
  53427. }
  53428. /**
  53429. * return a percentage difference between the polygon area and its triangulation area;
  53430. * used to verify correctness of triangulation
  53431. */
  53432. function deviation(data, holeIndices, dim, triangles) {
  53433. var hasHoles = holeIndices && holeIndices.length;
  53434. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  53435. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  53436. if (hasHoles) {
  53437. for (var i = 0, len = holeIndices.length; i < len; i++) {
  53438. var start = holeIndices[i] * dim;
  53439. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  53440. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  53441. }
  53442. }
  53443. var trianglesArea = 0;
  53444. for (i = 0; i < triangles.length; i += 3) {
  53445. var a = triangles[i] * dim;
  53446. var b = triangles[i + 1] * dim;
  53447. var c = triangles[i + 2] * dim;
  53448. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  53449. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  53450. }
  53451. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  53452. }
  53453. Earcut.deviation = deviation;
  53454. ;
  53455. function signedArea(data, start, end, dim) {
  53456. var sum = 0;
  53457. for (var i = start, j = end - dim; i < end; i += dim) {
  53458. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  53459. j = i;
  53460. }
  53461. return sum;
  53462. }
  53463. /**
  53464. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  53465. */
  53466. function flatten(data) {
  53467. var dim = data[0][0].length, result = { vertices: [], holes: [], dimensions: dim }, holeIndex = 0;
  53468. for (var i = 0; i < data.length; i++) {
  53469. for (var j = 0; j < data[i].length; j++) {
  53470. for (var d = 0; d < dim; d++)
  53471. result.vertices.push(data[i][j][d]);
  53472. }
  53473. if (i > 0) {
  53474. holeIndex += data[i - 1].length;
  53475. result.holes.push(holeIndex);
  53476. }
  53477. }
  53478. return result;
  53479. }
  53480. Earcut.flatten = flatten;
  53481. ;
  53482. })(Earcut || (Earcut = {}));
  53483. //# sourceMappingURL=babylon.earcut.js.map
  53484. /// <reference path="..\Math\babylon.math.ts" />
  53485. var BABYLON;
  53486. (function (BABYLON) {
  53487. var IndexedVector2 = (function (_super) {
  53488. __extends(IndexedVector2, _super);
  53489. function IndexedVector2(original, index) {
  53490. var _this = _super.call(this, original.x, original.y) || this;
  53491. _this.index = index;
  53492. return _this;
  53493. }
  53494. return IndexedVector2;
  53495. }(BABYLON.Vector2));
  53496. var PolygonPoints = (function () {
  53497. function PolygonPoints() {
  53498. this.elements = new Array();
  53499. }
  53500. PolygonPoints.prototype.add = function (originalPoints) {
  53501. var _this = this;
  53502. var result = new Array();
  53503. originalPoints.forEach(function (point) {
  53504. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  53505. var newPoint = new IndexedVector2(point, _this.elements.length);
  53506. result.push(newPoint);
  53507. _this.elements.push(newPoint);
  53508. }
  53509. });
  53510. return result;
  53511. };
  53512. PolygonPoints.prototype.computeBounds = function () {
  53513. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  53514. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  53515. this.elements.forEach(function (point) {
  53516. // x
  53517. if (point.x < lmin.x) {
  53518. lmin.x = point.x;
  53519. }
  53520. else if (point.x > lmax.x) {
  53521. lmax.x = point.x;
  53522. }
  53523. // y
  53524. if (point.y < lmin.y) {
  53525. lmin.y = point.y;
  53526. }
  53527. else if (point.y > lmax.y) {
  53528. lmax.y = point.y;
  53529. }
  53530. });
  53531. return {
  53532. min: lmin,
  53533. max: lmax,
  53534. width: lmax.x - lmin.x,
  53535. height: lmax.y - lmin.y
  53536. };
  53537. };
  53538. return PolygonPoints;
  53539. }());
  53540. var Polygon = (function () {
  53541. function Polygon() {
  53542. }
  53543. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  53544. return [
  53545. new BABYLON.Vector2(xmin, ymin),
  53546. new BABYLON.Vector2(xmax, ymin),
  53547. new BABYLON.Vector2(xmax, ymax),
  53548. new BABYLON.Vector2(xmin, ymax)
  53549. ];
  53550. };
  53551. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  53552. if (cx === void 0) { cx = 0; }
  53553. if (cy === void 0) { cy = 0; }
  53554. if (numberOfSides === void 0) { numberOfSides = 32; }
  53555. var result = new Array();
  53556. var angle = 0;
  53557. var increment = (Math.PI * 2) / numberOfSides;
  53558. for (var i = 0; i < numberOfSides; i++) {
  53559. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  53560. angle -= increment;
  53561. }
  53562. return result;
  53563. };
  53564. Polygon.Parse = function (input) {
  53565. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  53566. var i, result = [];
  53567. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  53568. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  53569. }
  53570. return result;
  53571. };
  53572. Polygon.StartingAt = function (x, y) {
  53573. return BABYLON.Path2.StartingAt(x, y);
  53574. };
  53575. return Polygon;
  53576. }());
  53577. BABYLON.Polygon = Polygon;
  53578. var PolygonMeshBuilder = (function () {
  53579. function PolygonMeshBuilder(name, contours, scene) {
  53580. this._points = new PolygonPoints();
  53581. this._outlinepoints = new PolygonPoints();
  53582. this._holes = [];
  53583. this._epoints = new Array();
  53584. this._eholes = new Array();
  53585. this._name = name;
  53586. this._scene = scene;
  53587. var points;
  53588. if (contours instanceof BABYLON.Path2) {
  53589. points = contours.getPoints();
  53590. }
  53591. else {
  53592. points = contours;
  53593. }
  53594. this._addToepoint(points);
  53595. this._points.add(points);
  53596. this._outlinepoints.add(points);
  53597. }
  53598. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  53599. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  53600. var p = points_1[_i];
  53601. this._epoints.push(p.x, p.y);
  53602. }
  53603. };
  53604. PolygonMeshBuilder.prototype.addHole = function (hole) {
  53605. this._points.add(hole);
  53606. var holepoints = new PolygonPoints();
  53607. holepoints.add(hole);
  53608. this._holes.push(holepoints);
  53609. this._eholes.push(this._epoints.length / 2);
  53610. this._addToepoint(hole);
  53611. return this;
  53612. };
  53613. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  53614. var _this = this;
  53615. if (updatable === void 0) { updatable = false; }
  53616. var result = new BABYLON.Mesh(this._name, this._scene);
  53617. var normals = [];
  53618. var positions = [];
  53619. var uvs = [];
  53620. var bounds = this._points.computeBounds();
  53621. this._points.elements.forEach(function (p) {
  53622. normals.push(0, 1.0, 0);
  53623. positions.push(p.x, 0, p.y);
  53624. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  53625. });
  53626. var indices = [];
  53627. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  53628. for (var i = 0; i < res.length; i++) {
  53629. indices.push(res[i]);
  53630. }
  53631. if (depth > 0) {
  53632. var positionscount = (positions.length / 3); //get the current pointcount
  53633. this._points.elements.forEach(function (p) {
  53634. normals.push(0, -1.0, 0);
  53635. positions.push(p.x, -depth, p.y);
  53636. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  53637. });
  53638. var totalCount = indices.length;
  53639. for (var i = 0; i < totalCount; i += 3) {
  53640. var i0 = indices[i + 0];
  53641. var i1 = indices[i + 1];
  53642. var i2 = indices[i + 2];
  53643. indices.push(i2 + positionscount);
  53644. indices.push(i1 + positionscount);
  53645. indices.push(i0 + positionscount);
  53646. }
  53647. //Add the sides
  53648. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  53649. this._holes.forEach(function (hole) {
  53650. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  53651. });
  53652. }
  53653. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  53654. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  53655. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  53656. result.setIndices(indices);
  53657. return result;
  53658. };
  53659. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  53660. var StartIndex = positions.length / 3;
  53661. var ulength = 0;
  53662. for (var i = 0; i < points.elements.length; i++) {
  53663. var p = points.elements[i];
  53664. var p1;
  53665. if ((i + 1) > points.elements.length - 1) {
  53666. p1 = points.elements[0];
  53667. }
  53668. else {
  53669. p1 = points.elements[i + 1];
  53670. }
  53671. positions.push(p.x, 0, p.y);
  53672. positions.push(p.x, -depth, p.y);
  53673. positions.push(p1.x, 0, p1.y);
  53674. positions.push(p1.x, -depth, p1.y);
  53675. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  53676. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  53677. var v3 = v2.subtract(v1);
  53678. var v4 = new BABYLON.Vector3(0, 1, 0);
  53679. var vn = BABYLON.Vector3.Cross(v3, v4);
  53680. vn = vn.normalize();
  53681. uvs.push(ulength / bounds.width, 0);
  53682. uvs.push(ulength / bounds.width, 1);
  53683. ulength += v3.length();
  53684. uvs.push((ulength / bounds.width), 0);
  53685. uvs.push((ulength / bounds.width), 1);
  53686. if (!flip) {
  53687. normals.push(-vn.x, -vn.y, -vn.z);
  53688. normals.push(-vn.x, -vn.y, -vn.z);
  53689. normals.push(-vn.x, -vn.y, -vn.z);
  53690. normals.push(-vn.x, -vn.y, -vn.z);
  53691. indices.push(StartIndex);
  53692. indices.push(StartIndex + 1);
  53693. indices.push(StartIndex + 2);
  53694. indices.push(StartIndex + 1);
  53695. indices.push(StartIndex + 3);
  53696. indices.push(StartIndex + 2);
  53697. }
  53698. else {
  53699. normals.push(vn.x, vn.y, vn.z);
  53700. normals.push(vn.x, vn.y, vn.z);
  53701. normals.push(vn.x, vn.y, vn.z);
  53702. normals.push(vn.x, vn.y, vn.z);
  53703. indices.push(StartIndex);
  53704. indices.push(StartIndex + 2);
  53705. indices.push(StartIndex + 1);
  53706. indices.push(StartIndex + 1);
  53707. indices.push(StartIndex + 2);
  53708. indices.push(StartIndex + 3);
  53709. }
  53710. StartIndex += 4;
  53711. }
  53712. ;
  53713. };
  53714. return PolygonMeshBuilder;
  53715. }());
  53716. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  53717. })(BABYLON || (BABYLON = {}));
  53718. //# sourceMappingURL=babylon.polygonMesh.js.map
  53719. var BABYLON;
  53720. (function (BABYLON) {
  53721. // Unique ID when we import meshes from Babylon to CSG
  53722. var currentCSGMeshId = 0;
  53723. // # class Vertex
  53724. // Represents a vertex of a polygon. Use your own vertex class instead of this
  53725. // one to provide additional features like texture coordinates and vertex
  53726. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  53727. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  53728. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  53729. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  53730. // is not used anywhere else.
  53731. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  53732. var Vertex = (function () {
  53733. function Vertex(pos, normal, uv) {
  53734. this.pos = pos;
  53735. this.normal = normal;
  53736. this.uv = uv;
  53737. }
  53738. Vertex.prototype.clone = function () {
  53739. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  53740. };
  53741. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  53742. // orientation of a polygon is flipped.
  53743. Vertex.prototype.flip = function () {
  53744. this.normal = this.normal.scale(-1);
  53745. };
  53746. // Create a new vertex between this vertex and `other` by linearly
  53747. // interpolating all properties using a parameter of `t`. Subclasses should
  53748. // override this to interpolate additional properties.
  53749. Vertex.prototype.interpolate = function (other, t) {
  53750. 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));
  53751. };
  53752. return Vertex;
  53753. }());
  53754. // # class Plane
  53755. // Represents a plane in 3D space.
  53756. var Plane = (function () {
  53757. function Plane(normal, w) {
  53758. this.normal = normal;
  53759. this.w = w;
  53760. }
  53761. Plane.FromPoints = function (a, b, c) {
  53762. var v0 = c.subtract(a);
  53763. var v1 = b.subtract(a);
  53764. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  53765. return null;
  53766. }
  53767. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  53768. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  53769. };
  53770. Plane.prototype.clone = function () {
  53771. return new Plane(this.normal.clone(), this.w);
  53772. };
  53773. Plane.prototype.flip = function () {
  53774. this.normal.scaleInPlace(-1);
  53775. this.w = -this.w;
  53776. };
  53777. // Split `polygon` by this plane if needed, then put the polygon or polygon
  53778. // fragments in the appropriate lists. Coplanar polygons go into either
  53779. // `coplanarFront` or `coplanarBack` depending on their orientation with
  53780. // respect to this plane. Polygons in front or in back of this plane go into
  53781. // either `front` or `back`.
  53782. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  53783. var COPLANAR = 0;
  53784. var FRONT = 1;
  53785. var BACK = 2;
  53786. var SPANNING = 3;
  53787. // Classify each point as well as the entire polygon into one of the above
  53788. // four classes.
  53789. var polygonType = 0;
  53790. var types = [];
  53791. var i;
  53792. var t;
  53793. for (i = 0; i < polygon.vertices.length; i++) {
  53794. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  53795. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  53796. polygonType |= type;
  53797. types.push(type);
  53798. }
  53799. // Put the polygon in the correct list, splitting it when necessary.
  53800. switch (polygonType) {
  53801. case COPLANAR:
  53802. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  53803. break;
  53804. case FRONT:
  53805. front.push(polygon);
  53806. break;
  53807. case BACK:
  53808. back.push(polygon);
  53809. break;
  53810. case SPANNING:
  53811. var f = [], b = [];
  53812. for (i = 0; i < polygon.vertices.length; i++) {
  53813. var j = (i + 1) % polygon.vertices.length;
  53814. var ti = types[i], tj = types[j];
  53815. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  53816. if (ti !== BACK)
  53817. f.push(vi);
  53818. if (ti !== FRONT)
  53819. b.push(ti !== BACK ? vi.clone() : vi);
  53820. if ((ti | tj) === SPANNING) {
  53821. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  53822. var v = vi.interpolate(vj, t);
  53823. f.push(v);
  53824. b.push(v.clone());
  53825. }
  53826. }
  53827. var poly;
  53828. if (f.length >= 3) {
  53829. poly = new Polygon(f, polygon.shared);
  53830. if (poly.plane)
  53831. front.push(poly);
  53832. }
  53833. if (b.length >= 3) {
  53834. poly = new Polygon(b, polygon.shared);
  53835. if (poly.plane)
  53836. back.push(poly);
  53837. }
  53838. break;
  53839. }
  53840. };
  53841. return Plane;
  53842. }());
  53843. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  53844. // point is on the plane.
  53845. Plane.EPSILON = 1e-5;
  53846. // # class Polygon
  53847. // Represents a convex polygon. The vertices used to initialize a polygon must
  53848. // be coplanar and form a convex loop.
  53849. //
  53850. // Each convex polygon has a `shared` property, which is shared between all
  53851. // polygons that are clones of each other or were split from the same polygon.
  53852. // This can be used to define per-polygon properties (such as surface color).
  53853. var Polygon = (function () {
  53854. function Polygon(vertices, shared) {
  53855. this.vertices = vertices;
  53856. this.shared = shared;
  53857. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  53858. }
  53859. Polygon.prototype.clone = function () {
  53860. var vertices = this.vertices.map(function (v) { return v.clone(); });
  53861. return new Polygon(vertices, this.shared);
  53862. };
  53863. Polygon.prototype.flip = function () {
  53864. this.vertices.reverse().map(function (v) { v.flip(); });
  53865. this.plane.flip();
  53866. };
  53867. return Polygon;
  53868. }());
  53869. // # class Node
  53870. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  53871. // by picking a polygon to split along. That polygon (and all other coplanar
  53872. // polygons) are added directly to that node and the other polygons are added to
  53873. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  53874. // no distinction between internal and leaf nodes.
  53875. var Node = (function () {
  53876. function Node(polygons) {
  53877. this.plane = null;
  53878. this.front = null;
  53879. this.back = null;
  53880. this.polygons = [];
  53881. if (polygons) {
  53882. this.build(polygons);
  53883. }
  53884. }
  53885. Node.prototype.clone = function () {
  53886. var node = new Node();
  53887. node.plane = this.plane && this.plane.clone();
  53888. node.front = this.front && this.front.clone();
  53889. node.back = this.back && this.back.clone();
  53890. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  53891. return node;
  53892. };
  53893. // Convert solid space to empty space and empty space to solid space.
  53894. Node.prototype.invert = function () {
  53895. for (var i = 0; i < this.polygons.length; i++) {
  53896. this.polygons[i].flip();
  53897. }
  53898. if (this.plane) {
  53899. this.plane.flip();
  53900. }
  53901. if (this.front) {
  53902. this.front.invert();
  53903. }
  53904. if (this.back) {
  53905. this.back.invert();
  53906. }
  53907. var temp = this.front;
  53908. this.front = this.back;
  53909. this.back = temp;
  53910. };
  53911. // Recursively remove all polygons in `polygons` that are inside this BSP
  53912. // tree.
  53913. Node.prototype.clipPolygons = function (polygons) {
  53914. if (!this.plane)
  53915. return polygons.slice();
  53916. var front = [], back = [];
  53917. for (var i = 0; i < polygons.length; i++) {
  53918. this.plane.splitPolygon(polygons[i], front, back, front, back);
  53919. }
  53920. if (this.front) {
  53921. front = this.front.clipPolygons(front);
  53922. }
  53923. if (this.back) {
  53924. back = this.back.clipPolygons(back);
  53925. }
  53926. else {
  53927. back = [];
  53928. }
  53929. return front.concat(back);
  53930. };
  53931. // Remove all polygons in this BSP tree that are inside the other BSP tree
  53932. // `bsp`.
  53933. Node.prototype.clipTo = function (bsp) {
  53934. this.polygons = bsp.clipPolygons(this.polygons);
  53935. if (this.front)
  53936. this.front.clipTo(bsp);
  53937. if (this.back)
  53938. this.back.clipTo(bsp);
  53939. };
  53940. // Return a list of all polygons in this BSP tree.
  53941. Node.prototype.allPolygons = function () {
  53942. var polygons = this.polygons.slice();
  53943. if (this.front)
  53944. polygons = polygons.concat(this.front.allPolygons());
  53945. if (this.back)
  53946. polygons = polygons.concat(this.back.allPolygons());
  53947. return polygons;
  53948. };
  53949. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  53950. // new polygons are filtered down to the bottom of the tree and become new
  53951. // nodes there. Each set of polygons is partitioned using the first polygon
  53952. // (no heuristic is used to pick a good split).
  53953. Node.prototype.build = function (polygons) {
  53954. if (!polygons.length)
  53955. return;
  53956. if (!this.plane)
  53957. this.plane = polygons[0].plane.clone();
  53958. var front = [], back = [];
  53959. for (var i = 0; i < polygons.length; i++) {
  53960. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  53961. }
  53962. if (front.length) {
  53963. if (!this.front)
  53964. this.front = new Node();
  53965. this.front.build(front);
  53966. }
  53967. if (back.length) {
  53968. if (!this.back)
  53969. this.back = new Node();
  53970. this.back.build(back);
  53971. }
  53972. };
  53973. return Node;
  53974. }());
  53975. var CSG = (function () {
  53976. function CSG() {
  53977. this.polygons = new Array();
  53978. }
  53979. // Convert BABYLON.Mesh to BABYLON.CSG
  53980. CSG.FromMesh = function (mesh) {
  53981. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  53982. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  53983. if (mesh instanceof BABYLON.Mesh) {
  53984. mesh.computeWorldMatrix(true);
  53985. matrix = mesh.getWorldMatrix();
  53986. meshPosition = mesh.position.clone();
  53987. meshRotation = mesh.rotation.clone();
  53988. if (mesh.rotationQuaternion) {
  53989. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  53990. }
  53991. meshScaling = mesh.scaling.clone();
  53992. }
  53993. else {
  53994. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  53995. }
  53996. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  53997. var subMeshes = mesh.subMeshes;
  53998. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  53999. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  54000. vertices = [];
  54001. for (var j = 0; j < 3; j++) {
  54002. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  54003. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  54004. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  54005. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  54006. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  54007. vertex = new Vertex(position, normal, uv);
  54008. vertices.push(vertex);
  54009. }
  54010. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  54011. // To handle the case of degenerated triangle
  54012. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  54013. if (polygon.plane)
  54014. polygons.push(polygon);
  54015. }
  54016. }
  54017. var csg = CSG.FromPolygons(polygons);
  54018. csg.matrix = matrix;
  54019. csg.position = meshPosition;
  54020. csg.rotation = meshRotation;
  54021. csg.scaling = meshScaling;
  54022. csg.rotationQuaternion = meshRotationQuaternion;
  54023. currentCSGMeshId++;
  54024. return csg;
  54025. };
  54026. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  54027. CSG.FromPolygons = function (polygons) {
  54028. var csg = new CSG();
  54029. csg.polygons = polygons;
  54030. return csg;
  54031. };
  54032. CSG.prototype.clone = function () {
  54033. var csg = new CSG();
  54034. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  54035. csg.copyTransformAttributes(this);
  54036. return csg;
  54037. };
  54038. CSG.prototype.toPolygons = function () {
  54039. return this.polygons;
  54040. };
  54041. CSG.prototype.union = function (csg) {
  54042. var a = new Node(this.clone().polygons);
  54043. var b = new Node(csg.clone().polygons);
  54044. a.clipTo(b);
  54045. b.clipTo(a);
  54046. b.invert();
  54047. b.clipTo(a);
  54048. b.invert();
  54049. a.build(b.allPolygons());
  54050. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  54051. };
  54052. CSG.prototype.unionInPlace = function (csg) {
  54053. var a = new Node(this.polygons);
  54054. var b = new Node(csg.polygons);
  54055. a.clipTo(b);
  54056. b.clipTo(a);
  54057. b.invert();
  54058. b.clipTo(a);
  54059. b.invert();
  54060. a.build(b.allPolygons());
  54061. this.polygons = a.allPolygons();
  54062. };
  54063. CSG.prototype.subtract = function (csg) {
  54064. var a = new Node(this.clone().polygons);
  54065. var b = new Node(csg.clone().polygons);
  54066. a.invert();
  54067. a.clipTo(b);
  54068. b.clipTo(a);
  54069. b.invert();
  54070. b.clipTo(a);
  54071. b.invert();
  54072. a.build(b.allPolygons());
  54073. a.invert();
  54074. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  54075. };
  54076. CSG.prototype.subtractInPlace = function (csg) {
  54077. var a = new Node(this.polygons);
  54078. var b = new Node(csg.polygons);
  54079. a.invert();
  54080. a.clipTo(b);
  54081. b.clipTo(a);
  54082. b.invert();
  54083. b.clipTo(a);
  54084. b.invert();
  54085. a.build(b.allPolygons());
  54086. a.invert();
  54087. this.polygons = a.allPolygons();
  54088. };
  54089. CSG.prototype.intersect = function (csg) {
  54090. var a = new Node(this.clone().polygons);
  54091. var b = new Node(csg.clone().polygons);
  54092. a.invert();
  54093. b.clipTo(a);
  54094. b.invert();
  54095. a.clipTo(b);
  54096. b.clipTo(a);
  54097. a.build(b.allPolygons());
  54098. a.invert();
  54099. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  54100. };
  54101. CSG.prototype.intersectInPlace = function (csg) {
  54102. var a = new Node(this.polygons);
  54103. var b = new Node(csg.polygons);
  54104. a.invert();
  54105. b.clipTo(a);
  54106. b.invert();
  54107. a.clipTo(b);
  54108. b.clipTo(a);
  54109. a.build(b.allPolygons());
  54110. a.invert();
  54111. this.polygons = a.allPolygons();
  54112. };
  54113. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  54114. // not modified.
  54115. CSG.prototype.inverse = function () {
  54116. var csg = this.clone();
  54117. csg.inverseInPlace();
  54118. return csg;
  54119. };
  54120. CSG.prototype.inverseInPlace = function () {
  54121. this.polygons.map(function (p) { p.flip(); });
  54122. };
  54123. // This is used to keep meshes transformations so they can be restored
  54124. // when we build back a Babylon Mesh
  54125. // NB : All CSG operations are performed in world coordinates
  54126. CSG.prototype.copyTransformAttributes = function (csg) {
  54127. this.matrix = csg.matrix;
  54128. this.position = csg.position;
  54129. this.rotation = csg.rotation;
  54130. this.scaling = csg.scaling;
  54131. this.rotationQuaternion = csg.rotationQuaternion;
  54132. return this;
  54133. };
  54134. // Build Raw mesh from CSG
  54135. // Coordinates here are in world space
  54136. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  54137. var matrix = this.matrix.clone();
  54138. matrix.invert();
  54139. 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;
  54140. if (keepSubMeshes) {
  54141. // Sort Polygons, since subMeshes are indices range
  54142. polygons.sort(function (a, b) {
  54143. if (a.shared.meshId === b.shared.meshId) {
  54144. return a.shared.subMeshId - b.shared.subMeshId;
  54145. }
  54146. else {
  54147. return a.shared.meshId - b.shared.meshId;
  54148. }
  54149. });
  54150. }
  54151. for (var i = 0, il = polygons.length; i < il; i++) {
  54152. polygon = polygons[i];
  54153. // Building SubMeshes
  54154. if (!subMesh_dict[polygon.shared.meshId]) {
  54155. subMesh_dict[polygon.shared.meshId] = {};
  54156. }
  54157. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  54158. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  54159. indexStart: +Infinity,
  54160. indexEnd: -Infinity,
  54161. materialIndex: polygon.shared.materialIndex
  54162. };
  54163. }
  54164. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  54165. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  54166. polygonIndices[0] = 0;
  54167. polygonIndices[1] = j - 1;
  54168. polygonIndices[2] = j;
  54169. for (var k = 0; k < 3; k++) {
  54170. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  54171. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  54172. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  54173. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  54174. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  54175. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  54176. // Check if 2 points can be merged
  54177. if (!(typeof vertex_idx !== 'undefined' &&
  54178. normals[vertex_idx * 3] === localNormal.x &&
  54179. normals[vertex_idx * 3 + 1] === localNormal.y &&
  54180. normals[vertex_idx * 3 + 2] === localNormal.z &&
  54181. uvs[vertex_idx * 2] === uv.x &&
  54182. uvs[vertex_idx * 2 + 1] === uv.y)) {
  54183. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  54184. uvs.push(uv.x, uv.y);
  54185. normals.push(normal.x, normal.y, normal.z);
  54186. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  54187. }
  54188. indices.push(vertex_idx);
  54189. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  54190. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  54191. currentIndex++;
  54192. }
  54193. }
  54194. }
  54195. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  54196. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  54197. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  54198. mesh.setIndices(indices);
  54199. if (keepSubMeshes) {
  54200. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  54201. var materialIndexOffset = 0, materialMaxIndex;
  54202. mesh.subMeshes = new Array();
  54203. for (var m in subMesh_dict) {
  54204. materialMaxIndex = -1;
  54205. for (var sm in subMesh_dict[m]) {
  54206. subMesh_obj = subMesh_dict[m][sm];
  54207. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  54208. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  54209. }
  54210. materialIndexOffset += ++materialMaxIndex;
  54211. }
  54212. }
  54213. return mesh;
  54214. };
  54215. // Build Mesh from CSG taking material and transforms into account
  54216. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  54217. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  54218. mesh.material = material;
  54219. mesh.position.copyFrom(this.position);
  54220. mesh.rotation.copyFrom(this.rotation);
  54221. if (this.rotationQuaternion) {
  54222. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  54223. }
  54224. mesh.scaling.copyFrom(this.scaling);
  54225. mesh.computeWorldMatrix(true);
  54226. return mesh;
  54227. };
  54228. return CSG;
  54229. }());
  54230. BABYLON.CSG = CSG;
  54231. })(BABYLON || (BABYLON = {}));
  54232. //# sourceMappingURL=babylon.csg.js.map
  54233. var BABYLON;
  54234. (function (BABYLON) {
  54235. var LensFlare = (function () {
  54236. function LensFlare(size, position, color, imgUrl, system) {
  54237. this.size = size;
  54238. this.position = position;
  54239. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  54240. this.dispose = function () {
  54241. if (this.texture) {
  54242. this.texture.dispose();
  54243. }
  54244. // Remove from scene
  54245. var index = this._system.lensFlares.indexOf(this);
  54246. this._system.lensFlares.splice(index, 1);
  54247. };
  54248. this.color = color || new BABYLON.Color3(1, 1, 1);
  54249. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  54250. this._system = system;
  54251. system.lensFlares.push(this);
  54252. }
  54253. return LensFlare;
  54254. }());
  54255. BABYLON.LensFlare = LensFlare;
  54256. })(BABYLON || (BABYLON = {}));
  54257. //# sourceMappingURL=babylon.lensFlare.js.map
  54258. var BABYLON;
  54259. (function (BABYLON) {
  54260. var LensFlareSystem = (function () {
  54261. function LensFlareSystem(name, emitter, scene) {
  54262. this.name = name;
  54263. this.lensFlares = new Array();
  54264. this.borderLimit = 300;
  54265. this.viewportBorder = 0;
  54266. this.layerMask = 0x0FFFFFFF;
  54267. this._vertexBuffers = {};
  54268. this._isEnabled = true;
  54269. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  54270. this._emitter = emitter;
  54271. this.id = name;
  54272. scene.lensFlareSystems.push(this);
  54273. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  54274. var engine = scene.getEngine();
  54275. // VBO
  54276. var vertices = [];
  54277. vertices.push(1, 1);
  54278. vertices.push(-1, 1);
  54279. vertices.push(-1, -1);
  54280. vertices.push(1, -1);
  54281. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  54282. // Indices
  54283. var indices = [];
  54284. indices.push(0);
  54285. indices.push(1);
  54286. indices.push(2);
  54287. indices.push(0);
  54288. indices.push(2);
  54289. indices.push(3);
  54290. this._indexBuffer = engine.createIndexBuffer(indices);
  54291. // Effects
  54292. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  54293. }
  54294. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  54295. get: function () {
  54296. return this._isEnabled;
  54297. },
  54298. set: function (value) {
  54299. this._isEnabled = value;
  54300. },
  54301. enumerable: true,
  54302. configurable: true
  54303. });
  54304. LensFlareSystem.prototype.getScene = function () {
  54305. return this._scene;
  54306. };
  54307. LensFlareSystem.prototype.getEmitter = function () {
  54308. return this._emitter;
  54309. };
  54310. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  54311. this._emitter = newEmitter;
  54312. };
  54313. LensFlareSystem.prototype.getEmitterPosition = function () {
  54314. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  54315. };
  54316. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  54317. var position = this.getEmitterPosition();
  54318. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  54319. this._positionX = position.x;
  54320. this._positionY = position.y;
  54321. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  54322. if (this.viewportBorder > 0) {
  54323. globalViewport.x -= this.viewportBorder;
  54324. globalViewport.y -= this.viewportBorder;
  54325. globalViewport.width += this.viewportBorder * 2;
  54326. globalViewport.height += this.viewportBorder * 2;
  54327. position.x += this.viewportBorder;
  54328. position.y += this.viewportBorder;
  54329. this._positionX += this.viewportBorder;
  54330. this._positionY += this.viewportBorder;
  54331. }
  54332. if (position.z > 0) {
  54333. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  54334. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  54335. return true;
  54336. }
  54337. return true;
  54338. }
  54339. return false;
  54340. };
  54341. LensFlareSystem.prototype._isVisible = function () {
  54342. if (!this._isEnabled) {
  54343. return false;
  54344. }
  54345. var emitterPosition = this.getEmitterPosition();
  54346. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  54347. var distance = direction.length();
  54348. direction.normalize();
  54349. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  54350. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  54351. return !pickInfo.hit || pickInfo.distance > distance;
  54352. };
  54353. LensFlareSystem.prototype.render = function () {
  54354. if (!this._effect.isReady())
  54355. return false;
  54356. var engine = this._scene.getEngine();
  54357. var viewport = this._scene.activeCamera.viewport;
  54358. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  54359. // Position
  54360. if (!this.computeEffectivePosition(globalViewport)) {
  54361. return false;
  54362. }
  54363. // Visibility
  54364. if (!this._isVisible()) {
  54365. return false;
  54366. }
  54367. // Intensity
  54368. var awayX;
  54369. var awayY;
  54370. if (this._positionX < this.borderLimit + globalViewport.x) {
  54371. awayX = this.borderLimit + globalViewport.x - this._positionX;
  54372. }
  54373. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  54374. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  54375. }
  54376. else {
  54377. awayX = 0;
  54378. }
  54379. if (this._positionY < this.borderLimit + globalViewport.y) {
  54380. awayY = this.borderLimit + globalViewport.y - this._positionY;
  54381. }
  54382. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  54383. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  54384. }
  54385. else {
  54386. awayY = 0;
  54387. }
  54388. var away = (awayX > awayY) ? awayX : awayY;
  54389. away -= this.viewportBorder;
  54390. if (away > this.borderLimit) {
  54391. away = this.borderLimit;
  54392. }
  54393. var intensity = 1.0 - (away / this.borderLimit);
  54394. if (intensity < 0) {
  54395. return false;
  54396. }
  54397. if (intensity > 1.0) {
  54398. intensity = 1.0;
  54399. }
  54400. if (this.viewportBorder > 0) {
  54401. globalViewport.x += this.viewportBorder;
  54402. globalViewport.y += this.viewportBorder;
  54403. globalViewport.width -= this.viewportBorder * 2;
  54404. globalViewport.height -= this.viewportBorder * 2;
  54405. this._positionX -= this.viewportBorder;
  54406. this._positionY -= this.viewportBorder;
  54407. }
  54408. // Position
  54409. var centerX = globalViewport.x + globalViewport.width / 2;
  54410. var centerY = globalViewport.y + globalViewport.height / 2;
  54411. var distX = centerX - this._positionX;
  54412. var distY = centerY - this._positionY;
  54413. // Effects
  54414. engine.enableEffect(this._effect);
  54415. engine.setState(false);
  54416. engine.setDepthBuffer(false);
  54417. // VBOs
  54418. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  54419. // Flares
  54420. for (var index = 0; index < this.lensFlares.length; index++) {
  54421. var flare = this.lensFlares[index];
  54422. engine.setAlphaMode(flare.alphaMode);
  54423. var x = centerX - (distX * flare.position);
  54424. var y = centerY - (distY * flare.position);
  54425. var cw = flare.size;
  54426. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  54427. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  54428. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  54429. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  54430. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  54431. // Texture
  54432. this._effect.setTexture("textureSampler", flare.texture);
  54433. // Color
  54434. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  54435. // Draw order
  54436. engine.draw(true, 0, 6);
  54437. }
  54438. engine.setDepthBuffer(true);
  54439. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  54440. return true;
  54441. };
  54442. LensFlareSystem.prototype.dispose = function () {
  54443. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  54444. if (vertexBuffer) {
  54445. vertexBuffer.dispose();
  54446. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  54447. }
  54448. if (this._indexBuffer) {
  54449. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  54450. this._indexBuffer = null;
  54451. }
  54452. while (this.lensFlares.length) {
  54453. this.lensFlares[0].dispose();
  54454. }
  54455. // Remove from scene
  54456. var index = this._scene.lensFlareSystems.indexOf(this);
  54457. this._scene.lensFlareSystems.splice(index, 1);
  54458. };
  54459. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  54460. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  54461. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  54462. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  54463. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  54464. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  54465. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  54466. var parsedFlare = parsedLensFlareSystem.flares[index];
  54467. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  54468. }
  54469. return lensFlareSystem;
  54470. };
  54471. LensFlareSystem.prototype.serialize = function () {
  54472. var serializationObject = {};
  54473. serializationObject.id = this.id;
  54474. serializationObject.name = this.name;
  54475. serializationObject.emitterId = this.getEmitter().id;
  54476. serializationObject.borderLimit = this.borderLimit;
  54477. serializationObject.flares = [];
  54478. for (var index = 0; index < this.lensFlares.length; index++) {
  54479. var flare = this.lensFlares[index];
  54480. serializationObject.flares.push({
  54481. size: flare.size,
  54482. position: flare.position,
  54483. color: flare.color.asArray(),
  54484. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  54485. });
  54486. }
  54487. return serializationObject;
  54488. };
  54489. return LensFlareSystem;
  54490. }());
  54491. BABYLON.LensFlareSystem = LensFlareSystem;
  54492. })(BABYLON || (BABYLON = {}));
  54493. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  54494. var BABYLON;
  54495. (function (BABYLON) {
  54496. /**
  54497. * This is a holder class for the physics joint created by the physics plugin.
  54498. * It holds a set of functions to control the underlying joint.
  54499. */
  54500. var PhysicsJoint = (function () {
  54501. function PhysicsJoint(type, jointData) {
  54502. this.type = type;
  54503. this.jointData = jointData;
  54504. jointData.nativeParams = jointData.nativeParams || {};
  54505. }
  54506. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  54507. get: function () {
  54508. return this._physicsJoint;
  54509. },
  54510. set: function (newJoint) {
  54511. if (this._physicsJoint) {
  54512. //remove from the wolrd
  54513. }
  54514. this._physicsJoint = newJoint;
  54515. },
  54516. enumerable: true,
  54517. configurable: true
  54518. });
  54519. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  54520. set: function (physicsPlugin) {
  54521. this._physicsPlugin = physicsPlugin;
  54522. },
  54523. enumerable: true,
  54524. configurable: true
  54525. });
  54526. /**
  54527. * Execute a function that is physics-plugin specific.
  54528. * @param {Function} func the function that will be executed.
  54529. * It accepts two parameters: the physics world and the physics joint.
  54530. */
  54531. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  54532. func(this._physicsPlugin.world, this._physicsJoint);
  54533. };
  54534. return PhysicsJoint;
  54535. }());
  54536. //TODO check if the native joints are the same
  54537. //Joint Types
  54538. PhysicsJoint.DistanceJoint = 0;
  54539. PhysicsJoint.HingeJoint = 1;
  54540. PhysicsJoint.BallAndSocketJoint = 2;
  54541. PhysicsJoint.WheelJoint = 3;
  54542. PhysicsJoint.SliderJoint = 4;
  54543. //OIMO
  54544. PhysicsJoint.PrismaticJoint = 5;
  54545. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  54546. PhysicsJoint.UniversalJoint = 6;
  54547. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  54548. //Cannon
  54549. //Similar to a Ball-Joint. Different in params
  54550. PhysicsJoint.PointToPointJoint = 8;
  54551. //Cannon only at the moment
  54552. PhysicsJoint.SpringJoint = 9;
  54553. PhysicsJoint.LockJoint = 10;
  54554. BABYLON.PhysicsJoint = PhysicsJoint;
  54555. /**
  54556. * A class representing a physics distance joint.
  54557. */
  54558. var DistanceJoint = (function (_super) {
  54559. __extends(DistanceJoint, _super);
  54560. function DistanceJoint(jointData) {
  54561. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  54562. }
  54563. /**
  54564. * Update the predefined distance.
  54565. */
  54566. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  54567. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  54568. };
  54569. return DistanceJoint;
  54570. }(PhysicsJoint));
  54571. BABYLON.DistanceJoint = DistanceJoint;
  54572. var MotorEnabledJoint = (function (_super) {
  54573. __extends(MotorEnabledJoint, _super);
  54574. function MotorEnabledJoint(type, jointData) {
  54575. return _super.call(this, type, jointData) || this;
  54576. }
  54577. /**
  54578. * Set the motor values.
  54579. * Attention, this function is plugin specific. Engines won't react 100% the same.
  54580. * @param {number} force the force to apply
  54581. * @param {number} maxForce max force for this motor.
  54582. */
  54583. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  54584. this._physicsPlugin.setMotor(this, force, maxForce);
  54585. };
  54586. /**
  54587. * Set the motor's limits.
  54588. * Attention, this function is plugin specific. Engines won't react 100% the same.
  54589. */
  54590. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  54591. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  54592. };
  54593. return MotorEnabledJoint;
  54594. }(PhysicsJoint));
  54595. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  54596. /**
  54597. * This class represents a single hinge physics joint
  54598. */
  54599. var HingeJoint = (function (_super) {
  54600. __extends(HingeJoint, _super);
  54601. function HingeJoint(jointData) {
  54602. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  54603. }
  54604. /**
  54605. * Set the motor values.
  54606. * Attention, this function is plugin specific. Engines won't react 100% the same.
  54607. * @param {number} force the force to apply
  54608. * @param {number} maxForce max force for this motor.
  54609. */
  54610. HingeJoint.prototype.setMotor = function (force, maxForce) {
  54611. this._physicsPlugin.setMotor(this, force, maxForce);
  54612. };
  54613. /**
  54614. * Set the motor's limits.
  54615. * Attention, this function is plugin specific. Engines won't react 100% the same.
  54616. */
  54617. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  54618. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  54619. };
  54620. return HingeJoint;
  54621. }(MotorEnabledJoint));
  54622. BABYLON.HingeJoint = HingeJoint;
  54623. /**
  54624. * This class represents a dual hinge physics joint (same as wheel joint)
  54625. */
  54626. var Hinge2Joint = (function (_super) {
  54627. __extends(Hinge2Joint, _super);
  54628. function Hinge2Joint(jointData) {
  54629. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  54630. }
  54631. /**
  54632. * Set the motor values.
  54633. * Attention, this function is plugin specific. Engines won't react 100% the same.
  54634. * @param {number} force the force to apply
  54635. * @param {number} maxForce max force for this motor.
  54636. * @param {motorIndex} the motor's index, 0 or 1.
  54637. */
  54638. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  54639. if (motorIndex === void 0) { motorIndex = 0; }
  54640. this._physicsPlugin.setMotor(this, force, maxForce, motorIndex);
  54641. };
  54642. /**
  54643. * Set the motor limits.
  54644. * Attention, this function is plugin specific. Engines won't react 100% the same.
  54645. * @param {number} upperLimit the upper limit
  54646. * @param {number} lowerLimit lower limit
  54647. * @param {motorIndex} the motor's index, 0 or 1.
  54648. */
  54649. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  54650. if (motorIndex === void 0) { motorIndex = 0; }
  54651. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  54652. };
  54653. return Hinge2Joint;
  54654. }(MotorEnabledJoint));
  54655. BABYLON.Hinge2Joint = Hinge2Joint;
  54656. })(BABYLON || (BABYLON = {}));
  54657. //# sourceMappingURL=babylon.physicsJoint.js.map
  54658. var BABYLON;
  54659. (function (BABYLON) {
  54660. var PhysicsImpostor = (function () {
  54661. function PhysicsImpostor(object, type, _options, _scene) {
  54662. if (_options === void 0) { _options = { mass: 0 }; }
  54663. var _this = this;
  54664. this.object = object;
  54665. this.type = type;
  54666. this._options = _options;
  54667. this._scene = _scene;
  54668. this._bodyUpdateRequired = false;
  54669. this._onBeforePhysicsStepCallbacks = new Array();
  54670. this._onAfterPhysicsStepCallbacks = new Array();
  54671. this._onPhysicsCollideCallbacks = [];
  54672. this._deltaPosition = BABYLON.Vector3.Zero();
  54673. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  54674. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  54675. /**
  54676. * this function is executed by the physics engine.
  54677. */
  54678. this.beforeStep = function () {
  54679. _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  54680. //conjugate deltaRotation
  54681. if (_this._deltaRotationConjugated) {
  54682. _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  54683. }
  54684. else {
  54685. _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
  54686. }
  54687. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  54688. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  54689. func(_this);
  54690. });
  54691. };
  54692. /**
  54693. * this function is executed by the physics engine.
  54694. */
  54695. this.afterStep = function () {
  54696. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  54697. func(_this);
  54698. });
  54699. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  54700. _this.object.position.addInPlace(_this._deltaPosition);
  54701. if (_this._deltaRotation) {
  54702. _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  54703. }
  54704. };
  54705. /**
  54706. * Legacy collision detection event support
  54707. */
  54708. this.onCollideEvent = null;
  54709. //event and body object due to cannon's event-based architecture.
  54710. this.onCollide = function (e) {
  54711. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent)
  54712. return;
  54713. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  54714. if (otherImpostor) {
  54715. // Legacy collision detection event support
  54716. if (_this.onCollideEvent) {
  54717. _this.onCollideEvent(_this, otherImpostor);
  54718. }
  54719. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  54720. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  54721. }).forEach(function (obj) {
  54722. obj.callback(_this, otherImpostor);
  54723. });
  54724. }
  54725. };
  54726. //sanity check!
  54727. if (!this.object) {
  54728. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  54729. return;
  54730. }
  54731. //legacy support for old syntax.
  54732. if (!this._scene && object.getScene) {
  54733. this._scene = object.getScene();
  54734. }
  54735. this._physicsEngine = this._scene.getPhysicsEngine();
  54736. if (!this._physicsEngine) {
  54737. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  54738. }
  54739. else {
  54740. //set the object's quaternion, if not set
  54741. if (!this.object.rotationQuaternion) {
  54742. if (this.object.rotation) {
  54743. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  54744. }
  54745. else {
  54746. this.object.rotationQuaternion = new BABYLON.Quaternion();
  54747. }
  54748. }
  54749. //default options params
  54750. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  54751. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  54752. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  54753. this._joints = [];
  54754. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  54755. if (!this.object.parent) {
  54756. this._init();
  54757. }
  54758. }
  54759. }
  54760. /**
  54761. * This function will completly initialize this impostor.
  54762. * It will create a new body - but only if this mesh has no parent.
  54763. * If it has, this impostor will not be used other than to define the impostor
  54764. * of the child mesh.
  54765. */
  54766. PhysicsImpostor.prototype._init = function () {
  54767. this._physicsEngine.removeImpostor(this);
  54768. this.physicsBody = null;
  54769. this._parent = this._parent || this._getPhysicsParent();
  54770. if (!this.parent) {
  54771. this._physicsEngine.addImpostor(this);
  54772. }
  54773. };
  54774. PhysicsImpostor.prototype._getPhysicsParent = function () {
  54775. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  54776. var parentMesh = this.object.parent;
  54777. return parentMesh.physicsImpostor;
  54778. }
  54779. return;
  54780. };
  54781. /**
  54782. * Should a new body be generated.
  54783. */
  54784. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  54785. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  54786. };
  54787. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  54788. this.forceUpdate();
  54789. };
  54790. /**
  54791. * Force a regeneration of this or the parent's impostor's body.
  54792. * Use under cautious - This will remove all joints already implemented.
  54793. */
  54794. PhysicsImpostor.prototype.forceUpdate = function () {
  54795. this._init();
  54796. if (this.parent) {
  54797. this.parent.forceUpdate();
  54798. }
  54799. };
  54800. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  54801. /*public get mesh(): AbstractMesh {
  54802. return this._mesh;
  54803. }*/
  54804. /**
  54805. * Gets the body that holds this impostor. Either its own, or its parent.
  54806. */
  54807. get: function () {
  54808. return this._parent ? this._parent.physicsBody : this._physicsBody;
  54809. },
  54810. /**
  54811. * Set the physics body. Used mainly by the physics engine/plugin
  54812. */
  54813. set: function (physicsBody) {
  54814. if (this._physicsBody) {
  54815. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  54816. }
  54817. this._physicsBody = physicsBody;
  54818. this.resetUpdateFlags();
  54819. },
  54820. enumerable: true,
  54821. configurable: true
  54822. });
  54823. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  54824. get: function () {
  54825. return this._parent;
  54826. },
  54827. set: function (value) {
  54828. this._parent = value;
  54829. },
  54830. enumerable: true,
  54831. configurable: true
  54832. });
  54833. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  54834. this._bodyUpdateRequired = false;
  54835. };
  54836. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  54837. if (this.object.getBoundingInfo) {
  54838. var q = this.object.rotationQuaternion;
  54839. //reset rotation
  54840. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  54841. //calculate the world matrix with no rotation
  54842. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  54843. var size = this.object.getBoundingInfo().boundingBox.extendSizeWorld.scale(2);
  54844. //bring back the rotation
  54845. this.object.rotationQuaternion = q;
  54846. //calculate the world matrix with the new rotation
  54847. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  54848. return size;
  54849. }
  54850. else {
  54851. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  54852. }
  54853. };
  54854. PhysicsImpostor.prototype.getObjectCenter = function () {
  54855. if (this.object.getBoundingInfo) {
  54856. return this.object.getBoundingInfo().boundingBox.centerWorld;
  54857. }
  54858. else {
  54859. return this.object.position;
  54860. }
  54861. };
  54862. /**
  54863. * Get a specific parametes from the options parameter.
  54864. */
  54865. PhysicsImpostor.prototype.getParam = function (paramName) {
  54866. return this._options[paramName];
  54867. };
  54868. /**
  54869. * Sets a specific parameter in the options given to the physics plugin
  54870. */
  54871. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  54872. this._options[paramName] = value;
  54873. this._bodyUpdateRequired = true;
  54874. };
  54875. /**
  54876. * Specifically change the body's mass option. Won't recreate the physics body object
  54877. */
  54878. PhysicsImpostor.prototype.setMass = function (mass) {
  54879. if (this.getParam("mass") !== mass) {
  54880. this.setParam("mass", mass);
  54881. }
  54882. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  54883. };
  54884. PhysicsImpostor.prototype.getLinearVelocity = function () {
  54885. return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this);
  54886. };
  54887. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  54888. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  54889. };
  54890. PhysicsImpostor.prototype.getAngularVelocity = function () {
  54891. return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this);
  54892. };
  54893. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  54894. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  54895. };
  54896. /**
  54897. * Execute a function with the physics plugin native code.
  54898. * Provide a function the will have two variables - the world object and the physics body object.
  54899. */
  54900. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  54901. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  54902. };
  54903. /**
  54904. * Register a function that will be executed before the physics world is stepping forward.
  54905. */
  54906. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  54907. this._onBeforePhysicsStepCallbacks.push(func);
  54908. };
  54909. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  54910. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  54911. if (index > -1) {
  54912. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  54913. }
  54914. else {
  54915. BABYLON.Tools.Warn("Function to remove was not found");
  54916. }
  54917. };
  54918. /**
  54919. * Register a function that will be executed after the physics step
  54920. */
  54921. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  54922. this._onAfterPhysicsStepCallbacks.push(func);
  54923. };
  54924. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  54925. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  54926. if (index > -1) {
  54927. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  54928. }
  54929. else {
  54930. BABYLON.Tools.Warn("Function to remove was not found");
  54931. }
  54932. };
  54933. /**
  54934. * register a function that will be executed when this impostor collides against a different body.
  54935. */
  54936. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  54937. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  54938. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  54939. };
  54940. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  54941. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  54942. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  54943. if (index > -1) {
  54944. this._onPhysicsCollideCallbacks.splice(index, 1);
  54945. }
  54946. else {
  54947. BABYLON.Tools.Warn("Function to remove was not found");
  54948. }
  54949. };
  54950. /**
  54951. * Apply a force
  54952. */
  54953. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  54954. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  54955. };
  54956. /**
  54957. * Apply an impulse
  54958. */
  54959. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  54960. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  54961. };
  54962. /**
  54963. * A help function to create a joint.
  54964. */
  54965. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  54966. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  54967. this.addJoint(otherImpostor, joint);
  54968. };
  54969. /**
  54970. * Add a joint to this impostor with a different impostor.
  54971. */
  54972. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  54973. this._joints.push({
  54974. otherImpostor: otherImpostor,
  54975. joint: joint
  54976. });
  54977. this._physicsEngine.addJoint(this, otherImpostor, joint);
  54978. };
  54979. /**
  54980. * Will keep this body still, in a sleep mode.
  54981. */
  54982. PhysicsImpostor.prototype.sleep = function () {
  54983. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  54984. };
  54985. /**
  54986. * Wake the body up.
  54987. */
  54988. PhysicsImpostor.prototype.wakeUp = function () {
  54989. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  54990. };
  54991. PhysicsImpostor.prototype.clone = function (newObject) {
  54992. if (!newObject)
  54993. return null;
  54994. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  54995. };
  54996. PhysicsImpostor.prototype.dispose = function () {
  54997. var _this = this;
  54998. //no dispose if no physics engine is available.
  54999. if (!this._physicsEngine) {
  55000. return;
  55001. }
  55002. this._joints.forEach(function (j) {
  55003. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  55004. });
  55005. //dispose the physics body
  55006. this._physicsEngine.removeImpostor(this);
  55007. if (this.parent) {
  55008. this.parent.forceUpdate();
  55009. }
  55010. else {
  55011. /*this._object.getChildMeshes().forEach(function(mesh) {
  55012. if (mesh.physicsImpostor) {
  55013. if (disposeChildren) {
  55014. mesh.physicsImpostor.dispose();
  55015. mesh.physicsImpostor = null;
  55016. }
  55017. }
  55018. })*/
  55019. }
  55020. };
  55021. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  55022. this._deltaPosition.copyFrom(position);
  55023. };
  55024. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  55025. if (!this._deltaRotation) {
  55026. this._deltaRotation = new BABYLON.Quaternion();
  55027. }
  55028. this._deltaRotation.copyFrom(rotation);
  55029. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  55030. };
  55031. return PhysicsImpostor;
  55032. }());
  55033. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  55034. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  55035. //Impostor types
  55036. PhysicsImpostor.NoImpostor = 0;
  55037. PhysicsImpostor.SphereImpostor = 1;
  55038. PhysicsImpostor.BoxImpostor = 2;
  55039. PhysicsImpostor.PlaneImpostor = 3;
  55040. PhysicsImpostor.MeshImpostor = 4;
  55041. PhysicsImpostor.CylinderImpostor = 7;
  55042. PhysicsImpostor.ParticleImpostor = 8;
  55043. PhysicsImpostor.HeightmapImpostor = 9;
  55044. BABYLON.PhysicsImpostor = PhysicsImpostor;
  55045. })(BABYLON || (BABYLON = {}));
  55046. //# sourceMappingURL=babylon.physicsImpostor.js.map
  55047. var BABYLON;
  55048. (function (BABYLON) {
  55049. var PhysicsEngine = (function () {
  55050. function PhysicsEngine(gravity, _physicsPlugin) {
  55051. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  55052. this._physicsPlugin = _physicsPlugin;
  55053. //new methods and parameters
  55054. this._impostors = [];
  55055. this._joints = [];
  55056. if (!this._physicsPlugin.isSupported()) {
  55057. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  55058. + "Please make sure it is included.");
  55059. }
  55060. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  55061. this.setGravity(gravity);
  55062. this.setTimeStep();
  55063. }
  55064. PhysicsEngine.prototype.setGravity = function (gravity) {
  55065. this.gravity = gravity;
  55066. this._physicsPlugin.setGravity(this.gravity);
  55067. };
  55068. /**
  55069. * Set the time step of the physics engine.
  55070. * default is 1/60.
  55071. * To slow it down, enter 1/600 for example.
  55072. * To speed it up, 1/30
  55073. * @param {number} newTimeStep the new timestep to apply to this world.
  55074. */
  55075. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  55076. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  55077. this._physicsPlugin.setTimeStep(newTimeStep);
  55078. };
  55079. PhysicsEngine.prototype.dispose = function () {
  55080. this._impostors.forEach(function (impostor) {
  55081. impostor.dispose();
  55082. });
  55083. this._physicsPlugin.dispose();
  55084. };
  55085. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  55086. return this._physicsPlugin.name;
  55087. };
  55088. /**
  55089. * Adding a new impostor for the impostor tracking.
  55090. * This will be done by the impostor itself.
  55091. * @param {PhysicsImpostor} impostor the impostor to add
  55092. */
  55093. PhysicsEngine.prototype.addImpostor = function (impostor) {
  55094. impostor.uniqueId = this._impostors.push(impostor);
  55095. //if no parent, generate the body
  55096. if (!impostor.parent) {
  55097. this._physicsPlugin.generatePhysicsBody(impostor);
  55098. }
  55099. };
  55100. /**
  55101. * Remove an impostor from the engine.
  55102. * This impostor and its mesh will not longer be updated by the physics engine.
  55103. * @param {PhysicsImpostor} impostor the impostor to remove
  55104. */
  55105. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  55106. var index = this._impostors.indexOf(impostor);
  55107. if (index > -1) {
  55108. var removed = this._impostors.splice(index, 1);
  55109. //Is it needed?
  55110. if (removed.length) {
  55111. //this will also remove it from the world.
  55112. removed[0].physicsBody = null;
  55113. }
  55114. }
  55115. };
  55116. /**
  55117. * Add a joint to the physics engine
  55118. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  55119. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  55120. * @param {PhysicsJoint} the joint that will connect both impostors.
  55121. */
  55122. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  55123. var impostorJoint = {
  55124. mainImpostor: mainImpostor,
  55125. connectedImpostor: connectedImpostor,
  55126. joint: joint
  55127. };
  55128. joint.physicsPlugin = this._physicsPlugin;
  55129. this._joints.push(impostorJoint);
  55130. this._physicsPlugin.generateJoint(impostorJoint);
  55131. };
  55132. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  55133. var matchingJoints = this._joints.filter(function (impostorJoint) {
  55134. return (impostorJoint.connectedImpostor === connectedImpostor
  55135. && impostorJoint.joint === joint
  55136. && impostorJoint.mainImpostor === mainImpostor);
  55137. });
  55138. if (matchingJoints.length) {
  55139. this._physicsPlugin.removeJoint(matchingJoints[0]);
  55140. //TODO remove it from the list as well
  55141. }
  55142. };
  55143. /**
  55144. * Called by the scene. no need to call it.
  55145. */
  55146. PhysicsEngine.prototype._step = function (delta) {
  55147. var _this = this;
  55148. //check if any mesh has no body / requires an update
  55149. this._impostors.forEach(function (impostor) {
  55150. if (impostor.isBodyInitRequired()) {
  55151. _this._physicsPlugin.generatePhysicsBody(impostor);
  55152. }
  55153. });
  55154. if (delta > 0.1) {
  55155. delta = 0.1;
  55156. }
  55157. else if (delta <= 0) {
  55158. delta = 1.0 / 60.0;
  55159. }
  55160. this._physicsPlugin.executeStep(delta, this._impostors);
  55161. };
  55162. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  55163. return this._physicsPlugin;
  55164. };
  55165. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  55166. for (var i = 0; i < this._impostors.length; ++i) {
  55167. if (this._impostors[i].object === object) {
  55168. return this._impostors[i];
  55169. }
  55170. }
  55171. };
  55172. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  55173. for (var i = 0; i < this._impostors.length; ++i) {
  55174. if (this._impostors[i].physicsBody === body) {
  55175. return this._impostors[i];
  55176. }
  55177. }
  55178. };
  55179. return PhysicsEngine;
  55180. }());
  55181. // Statics
  55182. PhysicsEngine.Epsilon = 0.001;
  55183. BABYLON.PhysicsEngine = PhysicsEngine;
  55184. })(BABYLON || (BABYLON = {}));
  55185. //# sourceMappingURL=babylon.physicsEngine.js.map
  55186. var BABYLON;
  55187. (function (BABYLON) {
  55188. var CannonJSPlugin = (function () {
  55189. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  55190. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  55191. if (iterations === void 0) { iterations = 10; }
  55192. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  55193. this.name = "CannonJSPlugin";
  55194. this._physicsMaterials = [];
  55195. this._fixedTimeStep = 1 / 60;
  55196. //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  55197. this._currentCollisionGroup = 2;
  55198. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  55199. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  55200. this._tmpPosition = BABYLON.Vector3.Zero();
  55201. this._tmpQuaternion = new BABYLON.Quaternion();
  55202. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  55203. this._tmpDeltaRotation = new BABYLON.Quaternion();
  55204. this._tmpUnityRotation = new BABYLON.Quaternion();
  55205. if (!this.isSupported()) {
  55206. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  55207. return;
  55208. }
  55209. this.world = new CANNON.World();
  55210. this.world.broadphase = new CANNON.NaiveBroadphase();
  55211. this.world.solver.iterations = iterations;
  55212. }
  55213. CannonJSPlugin.prototype.setGravity = function (gravity) {
  55214. this.world.gravity.copy(gravity);
  55215. };
  55216. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  55217. this._fixedTimeStep = timeStep;
  55218. };
  55219. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  55220. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  55221. };
  55222. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  55223. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  55224. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  55225. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  55226. };
  55227. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  55228. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  55229. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  55230. impostor.physicsBody.applyForce(impulse, worldPoint);
  55231. };
  55232. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  55233. //parent-child relationship. Does this impostor has a parent impostor?
  55234. if (impostor.parent) {
  55235. if (impostor.physicsBody) {
  55236. this.removePhysicsBody(impostor);
  55237. //TODO is that needed?
  55238. impostor.forceUpdate();
  55239. }
  55240. return;
  55241. }
  55242. //should a new body be created for this impostor?
  55243. if (impostor.isBodyInitRequired()) {
  55244. var shape = this._createShape(impostor);
  55245. //unregister events, if body is being changed
  55246. var oldBody = impostor.physicsBody;
  55247. if (oldBody) {
  55248. this.removePhysicsBody(impostor);
  55249. }
  55250. //create the body and material
  55251. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  55252. var bodyCreationObject = {
  55253. mass: impostor.getParam("mass"),
  55254. material: material
  55255. };
  55256. // A simple extend, in case native options were used.
  55257. var nativeOptions = impostor.getParam("nativeOptions");
  55258. for (var key in nativeOptions) {
  55259. if (nativeOptions.hasOwnProperty(key)) {
  55260. bodyCreationObject[key] = nativeOptions[key];
  55261. }
  55262. }
  55263. impostor.physicsBody = new CANNON.Body(bodyCreationObject);
  55264. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  55265. this.world.addEventListener("preStep", impostor.beforeStep);
  55266. this.world.addEventListener("postStep", impostor.afterStep);
  55267. impostor.physicsBody.addShape(shape);
  55268. this.world.add(impostor.physicsBody);
  55269. //try to keep the body moving in the right direction by taking old properties.
  55270. //Should be tested!
  55271. if (oldBody) {
  55272. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  55273. impostor.physicsBody[param].copy(oldBody[param]);
  55274. });
  55275. }
  55276. this._processChildMeshes(impostor);
  55277. }
  55278. //now update the body's transformation
  55279. this._updatePhysicsBodyTransformation(impostor);
  55280. };
  55281. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  55282. var _this = this;
  55283. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes() : [];
  55284. if (meshChildren.length) {
  55285. var processMesh = function (localPosition, mesh) {
  55286. var childImpostor = mesh.getPhysicsImpostor();
  55287. if (childImpostor) {
  55288. var parent = childImpostor.parent;
  55289. if (parent !== mainImpostor) {
  55290. var localPosition = mesh.position;
  55291. if (childImpostor.physicsBody) {
  55292. _this.removePhysicsBody(childImpostor);
  55293. childImpostor.physicsBody = null;
  55294. }
  55295. childImpostor.parent = mainImpostor;
  55296. childImpostor.resetUpdateFlags();
  55297. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  55298. //Add the mass of the children.
  55299. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  55300. }
  55301. }
  55302. mesh.getChildMeshes().forEach(processMesh.bind(_this, mesh.position));
  55303. };
  55304. meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
  55305. }
  55306. };
  55307. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  55308. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  55309. this.world.removeEventListener("preStep", impostor.beforeStep);
  55310. this.world.removeEventListener("postStep", impostor.afterStep);
  55311. this.world.remove(impostor.physicsBody);
  55312. };
  55313. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  55314. var mainBody = impostorJoint.mainImpostor.physicsBody;
  55315. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  55316. if (!mainBody || !connectedBody) {
  55317. return;
  55318. }
  55319. var constraint;
  55320. var jointData = impostorJoint.joint.jointData;
  55321. //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  55322. var constraintData = {
  55323. pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
  55324. pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
  55325. axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
  55326. axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
  55327. maxForce: jointData.nativeParams.maxForce,
  55328. collideConnected: !!jointData.collision
  55329. };
  55330. switch (impostorJoint.joint.type) {
  55331. case BABYLON.PhysicsJoint.HingeJoint:
  55332. case BABYLON.PhysicsJoint.Hinge2Joint:
  55333. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  55334. break;
  55335. case BABYLON.PhysicsJoint.DistanceJoint:
  55336. constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  55337. break;
  55338. case BABYLON.PhysicsJoint.SpringJoint:
  55339. var springData = jointData;
  55340. constraint = new CANNON.Spring(mainBody, connectedBody, {
  55341. restLength: springData.length,
  55342. stiffness: springData.stiffness,
  55343. damping: springData.damping,
  55344. localAnchorA: constraintData.pivotA,
  55345. localAnchorB: constraintData.pivotB
  55346. });
  55347. break;
  55348. case BABYLON.PhysicsJoint.LockJoint:
  55349. constraint = new CANNON.LockConstraint(mainBody, connectedBody, constraintData);
  55350. break;
  55351. case BABYLON.PhysicsJoint.PointToPointJoint:
  55352. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  55353. default:
  55354. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  55355. break;
  55356. }
  55357. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  55358. constraint.collideConnected = !!jointData.collision;
  55359. impostorJoint.joint.physicsJoint = constraint;
  55360. //don't add spring as constraint, as it is not one.
  55361. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  55362. this.world.addConstraint(constraint);
  55363. }
  55364. else {
  55365. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  55366. constraint.applyForce();
  55367. });
  55368. }
  55369. };
  55370. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  55371. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  55372. };
  55373. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  55374. var index;
  55375. var mat;
  55376. for (index = 0; index < this._physicsMaterials.length; index++) {
  55377. mat = this._physicsMaterials[index];
  55378. if (mat.friction === friction && mat.restitution === restitution) {
  55379. return mat;
  55380. }
  55381. }
  55382. var currentMat = new CANNON.Material(name);
  55383. currentMat.friction = friction;
  55384. currentMat.restitution = restitution;
  55385. this._physicsMaterials.push(currentMat);
  55386. return currentMat;
  55387. };
  55388. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  55389. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  55390. };
  55391. CannonJSPlugin.prototype._createShape = function (impostor) {
  55392. var object = impostor.object;
  55393. var returnValue;
  55394. var extendSize = impostor.getObjectExtendSize();
  55395. switch (impostor.type) {
  55396. case BABYLON.PhysicsImpostor.SphereImpostor:
  55397. var radiusX = extendSize.x;
  55398. var radiusY = extendSize.y;
  55399. var radiusZ = extendSize.z;
  55400. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  55401. break;
  55402. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  55403. case BABYLON.PhysicsImpostor.CylinderImpostor:
  55404. returnValue = new CANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  55405. break;
  55406. case BABYLON.PhysicsImpostor.BoxImpostor:
  55407. var box = extendSize.scale(0.5);
  55408. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  55409. break;
  55410. case BABYLON.PhysicsImpostor.PlaneImpostor:
  55411. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  55412. returnValue = new CANNON.Plane();
  55413. break;
  55414. case BABYLON.PhysicsImpostor.MeshImpostor:
  55415. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  55416. var rawFaces = object.getIndices ? object.getIndices() : [];
  55417. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  55418. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  55419. break;
  55420. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  55421. returnValue = this._createHeightmap(object);
  55422. break;
  55423. case BABYLON.PhysicsImpostor.ParticleImpostor:
  55424. returnValue = new CANNON.Particle();
  55425. break;
  55426. }
  55427. return returnValue;
  55428. };
  55429. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  55430. var pos = object.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55431. var matrix = [];
  55432. //For now pointDepth will not be used and will be automatically calculated.
  55433. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  55434. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  55435. var dim = Math.min(object.getBoundingInfo().boundingBox.extendSize.x, object.getBoundingInfo().boundingBox.extendSize.z);
  55436. var elementSize = dim * 2 / arraySize;
  55437. var minY = object.getBoundingInfo().boundingBox.extendSize.y;
  55438. for (var i = 0; i < pos.length; i = i + 3) {
  55439. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  55440. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  55441. var y = pos[i + 1] + minY;
  55442. if (!matrix[x]) {
  55443. matrix[x] = [];
  55444. }
  55445. if (!matrix[x][z]) {
  55446. matrix[x][z] = y;
  55447. }
  55448. matrix[x][z] = Math.max(y, matrix[x][z]);
  55449. }
  55450. for (var x = 0; x <= arraySize; ++x) {
  55451. if (!matrix[x]) {
  55452. var loc = 1;
  55453. while (!matrix[(x + loc) % arraySize]) {
  55454. loc++;
  55455. }
  55456. matrix[x] = matrix[(x + loc) % arraySize].slice();
  55457. //console.log("missing x", x);
  55458. }
  55459. for (var z = 0; z <= arraySize; ++z) {
  55460. if (!matrix[x][z]) {
  55461. var loc = 1;
  55462. var newValue;
  55463. while (newValue === undefined) {
  55464. newValue = matrix[x][(z + loc++) % arraySize];
  55465. }
  55466. matrix[x][z] = newValue;
  55467. }
  55468. }
  55469. }
  55470. var shape = new CANNON.Heightfield(matrix, {
  55471. elementSize: elementSize
  55472. });
  55473. //For future reference, needed for body transformation
  55474. shape.minY = minY;
  55475. return shape;
  55476. };
  55477. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  55478. var object = impostor.object;
  55479. //make sure it is updated...
  55480. object.computeWorldMatrix && object.computeWorldMatrix(true);
  55481. // The delta between the mesh position and the mesh bounding box center
  55482. var center = impostor.getObjectCenter();
  55483. this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
  55484. this._tmpPosition.copyFrom(center);
  55485. var quaternion = object.rotationQuaternion;
  55486. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  55487. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  55488. //-90 DEG in X, precalculated
  55489. quaternion = quaternion.multiply(this._minus90X);
  55490. //Invert! (Precalculated, 90 deg in X)
  55491. //No need to clone. this will never change.
  55492. impostor.setDeltaRotation(this._plus90X);
  55493. }
  55494. //If it is a heightfield, if should be centered.
  55495. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  55496. var mesh = object;
  55497. //calculate the correct body position:
  55498. var rotationQuaternion = mesh.rotationQuaternion;
  55499. mesh.rotationQuaternion = this._tmpUnityRotation;
  55500. mesh.computeWorldMatrix(true);
  55501. //get original center with no rotation
  55502. var c = center.clone();
  55503. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  55504. //rotation is back
  55505. mesh.rotationQuaternion = rotationQuaternion;
  55506. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  55507. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  55508. mesh.setPivotMatrix(p);
  55509. mesh.computeWorldMatrix(true);
  55510. //calculate the translation
  55511. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  55512. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  55513. //add it inverted to the delta
  55514. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.center.subtract(c));
  55515. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  55516. mesh.setPivotMatrix(oldPivot);
  55517. mesh.computeWorldMatrix(true);
  55518. }
  55519. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  55520. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  55521. this._tmpPosition.copyFrom(object.position);
  55522. }
  55523. impostor.setDeltaPosition(this._tmpDeltaPosition);
  55524. //Now update the impostor object
  55525. impostor.physicsBody.position.copy(this._tmpPosition);
  55526. impostor.physicsBody.quaternion.copy(quaternion);
  55527. };
  55528. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  55529. impostor.object.position.copyFrom(impostor.physicsBody.position);
  55530. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  55531. };
  55532. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  55533. impostor.physicsBody.position.copy(newPosition);
  55534. impostor.physicsBody.quaternion.copy(newRotation);
  55535. };
  55536. CannonJSPlugin.prototype.isSupported = function () {
  55537. return window.CANNON !== undefined;
  55538. };
  55539. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  55540. impostor.physicsBody.velocity.copy(velocity);
  55541. };
  55542. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  55543. impostor.physicsBody.angularVelocity.copy(velocity);
  55544. };
  55545. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  55546. var v = impostor.physicsBody.velocity;
  55547. if (!v)
  55548. return null;
  55549. return new BABYLON.Vector3(v.x, v.y, v.z);
  55550. };
  55551. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  55552. var v = impostor.physicsBody.angularVelocity;
  55553. if (!v)
  55554. return null;
  55555. return new BABYLON.Vector3(v.x, v.y, v.z);
  55556. };
  55557. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  55558. impostor.physicsBody.mass = mass;
  55559. impostor.physicsBody.updateMassProperties();
  55560. };
  55561. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  55562. impostor.physicsBody.sleep();
  55563. };
  55564. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  55565. impostor.physicsBody.wakeUp();
  55566. };
  55567. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  55568. joint.physicsJoint.distance = maxDistance;
  55569. };
  55570. CannonJSPlugin.prototype.enableMotor = function (joint, motorIndex) {
  55571. if (!motorIndex) {
  55572. joint.physicsJoint.enableMotor();
  55573. }
  55574. };
  55575. CannonJSPlugin.prototype.disableMotor = function (joint, motorIndex) {
  55576. if (!motorIndex) {
  55577. joint.physicsJoint.disableMotor();
  55578. }
  55579. };
  55580. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  55581. if (!motorIndex) {
  55582. joint.physicsJoint.enableMotor();
  55583. joint.physicsJoint.setMotorSpeed(speed);
  55584. if (maxForce) {
  55585. this.setLimit(joint, maxForce);
  55586. }
  55587. }
  55588. };
  55589. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  55590. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  55591. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  55592. };
  55593. CannonJSPlugin.prototype.dispose = function () {
  55594. //nothing to do, actually.
  55595. };
  55596. return CannonJSPlugin;
  55597. }());
  55598. BABYLON.CannonJSPlugin = CannonJSPlugin;
  55599. })(BABYLON || (BABYLON = {}));
  55600. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  55601. var BABYLON;
  55602. (function (BABYLON) {
  55603. var OimoJSPlugin = (function () {
  55604. function OimoJSPlugin(iterations) {
  55605. this.name = "OimoJSPlugin";
  55606. this._tmpImpostorsArray = [];
  55607. this._tmpPositionVector = BABYLON.Vector3.Zero();
  55608. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  55609. this.world.worldscale(1);
  55610. this.world.clear();
  55611. //making sure no stats are calculated
  55612. this.world.isNoStat = true;
  55613. }
  55614. OimoJSPlugin.prototype.setGravity = function (gravity) {
  55615. this.world.gravity.copy(gravity);
  55616. };
  55617. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  55618. this.world.timeStep = timeStep;
  55619. };
  55620. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  55621. var _this = this;
  55622. impostors.forEach(function (impostor) {
  55623. impostor.beforeStep();
  55624. });
  55625. this.world.step();
  55626. impostors.forEach(function (impostor) {
  55627. impostor.afterStep();
  55628. //update the ordered impostors array
  55629. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  55630. });
  55631. //check for collisions
  55632. var contact = this.world.contacts;
  55633. while (contact !== null) {
  55634. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  55635. contact = contact.next;
  55636. continue;
  55637. }
  55638. //is this body colliding with any other? get the impostor
  55639. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  55640. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  55641. if (!mainImpostor || !collidingImpostor) {
  55642. contact = contact.next;
  55643. continue;
  55644. }
  55645. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  55646. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  55647. contact = contact.next;
  55648. }
  55649. };
  55650. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  55651. var mass = impostor.physicsBody.massInfo.mass;
  55652. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  55653. };
  55654. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  55655. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  55656. this.applyImpulse(impostor, force, contactPoint);
  55657. };
  55658. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  55659. var _this = this;
  55660. //parent-child relationship. Does this impostor has a parent impostor?
  55661. if (impostor.parent) {
  55662. if (impostor.physicsBody) {
  55663. this.removePhysicsBody(impostor);
  55664. //TODO is that needed?
  55665. impostor.forceUpdate();
  55666. }
  55667. return;
  55668. }
  55669. if (impostor.isBodyInitRequired()) {
  55670. var bodyConfig = {
  55671. name: impostor.uniqueId,
  55672. //Oimo must have mass, also for static objects.
  55673. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  55674. size: [],
  55675. type: [],
  55676. pos: [],
  55677. rot: [],
  55678. move: impostor.getParam("mass") !== 0,
  55679. //Supporting older versions of Oimo
  55680. world: this.world
  55681. };
  55682. var impostors = [impostor];
  55683. var addToArray = function (parent) {
  55684. if (!parent.getChildMeshes)
  55685. return;
  55686. parent.getChildMeshes().forEach(function (m) {
  55687. if (m.physicsImpostor) {
  55688. impostors.push(m.physicsImpostor);
  55689. m.physicsImpostor._init();
  55690. }
  55691. });
  55692. };
  55693. addToArray(impostor.object);
  55694. var checkWithEpsilon_1 = function (value) {
  55695. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  55696. };
  55697. impostors.forEach(function (i) {
  55698. //get the correct bounding box
  55699. var oldQuaternion = i.object.rotationQuaternion;
  55700. var rot = new OIMO.Euler().setFromQuaternion({
  55701. x: impostor.object.rotationQuaternion.x,
  55702. y: impostor.object.rotationQuaternion.y,
  55703. z: impostor.object.rotationQuaternion.z,
  55704. s: impostor.object.rotationQuaternion.w
  55705. });
  55706. var extendSize = i.getObjectExtendSize();
  55707. if (i === impostor) {
  55708. var center = impostor.getObjectCenter();
  55709. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  55710. //Can also use Array.prototype.push.apply
  55711. bodyConfig.pos.push(center.x);
  55712. bodyConfig.pos.push(center.y);
  55713. bodyConfig.pos.push(center.z);
  55714. //tmp solution
  55715. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  55716. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  55717. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  55718. }
  55719. else {
  55720. bodyConfig.pos.push(i.object.position.x);
  55721. bodyConfig.pos.push(i.object.position.y);
  55722. bodyConfig.pos.push(i.object.position.z);
  55723. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  55724. bodyConfig.rot.push(0);
  55725. bodyConfig.rot.push(0);
  55726. bodyConfig.rot.push(0);
  55727. }
  55728. // register mesh
  55729. switch (i.type) {
  55730. case BABYLON.PhysicsImpostor.ParticleImpostor:
  55731. BABYLON.Tools.Warn("No Particle support in Oimo.js. using SphereImpostor instead");
  55732. case BABYLON.PhysicsImpostor.SphereImpostor:
  55733. var radiusX = extendSize.x;
  55734. var radiusY = extendSize.y;
  55735. var radiusZ = extendSize.z;
  55736. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  55737. bodyConfig.type.push('sphere');
  55738. //due to the way oimo works with compounds, add 3 times
  55739. bodyConfig.size.push(size);
  55740. bodyConfig.size.push(size);
  55741. bodyConfig.size.push(size);
  55742. break;
  55743. case BABYLON.PhysicsImpostor.CylinderImpostor:
  55744. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  55745. var sizeY = checkWithEpsilon_1(extendSize.y);
  55746. bodyConfig.type.push('cylinder');
  55747. bodyConfig.size.push(sizeX);
  55748. bodyConfig.size.push(sizeY);
  55749. //due to the way oimo works with compounds, add one more value.
  55750. bodyConfig.size.push(sizeY);
  55751. break;
  55752. case BABYLON.PhysicsImpostor.PlaneImpostor:
  55753. case BABYLON.PhysicsImpostor.BoxImpostor:
  55754. default:
  55755. var sizeX = checkWithEpsilon_1(extendSize.x);
  55756. var sizeY = checkWithEpsilon_1(extendSize.y);
  55757. var sizeZ = checkWithEpsilon_1(extendSize.z);
  55758. bodyConfig.type.push('box');
  55759. bodyConfig.size.push(sizeX);
  55760. bodyConfig.size.push(sizeY);
  55761. bodyConfig.size.push(sizeZ);
  55762. break;
  55763. }
  55764. //actually not needed, but hey...
  55765. i.object.rotationQuaternion = oldQuaternion;
  55766. });
  55767. impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  55768. }
  55769. else {
  55770. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  55771. }
  55772. impostor.setDeltaPosition(this._tmpPositionVector);
  55773. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  55774. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  55775. };
  55776. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  55777. //impostor.physicsBody.dispose();
  55778. //Same as : (older oimo versions)
  55779. this.world.removeRigidBody(impostor.physicsBody);
  55780. };
  55781. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  55782. var mainBody = impostorJoint.mainImpostor.physicsBody;
  55783. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  55784. if (!mainBody || !connectedBody) {
  55785. return;
  55786. }
  55787. var jointData = impostorJoint.joint.jointData;
  55788. var options = jointData.nativeParams || {};
  55789. var type;
  55790. var nativeJointData = {
  55791. body1: mainBody,
  55792. body2: connectedBody,
  55793. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  55794. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  55795. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  55796. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  55797. min: options.min,
  55798. max: options.max,
  55799. collision: options.collision || jointData.collision,
  55800. spring: options.spring,
  55801. //supporting older version of Oimo
  55802. world: this.world
  55803. };
  55804. switch (impostorJoint.joint.type) {
  55805. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  55806. type = "jointBall";
  55807. break;
  55808. case BABYLON.PhysicsJoint.SpringJoint:
  55809. BABYLON.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  55810. var springData = jointData;
  55811. nativeJointData.min = springData.length || nativeJointData.min;
  55812. //Max should also be set, just make sure it is at least min
  55813. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  55814. case BABYLON.PhysicsJoint.DistanceJoint:
  55815. type = "jointDistance";
  55816. nativeJointData.max = jointData.maxDistance;
  55817. break;
  55818. case BABYLON.PhysicsJoint.PrismaticJoint:
  55819. type = "jointPrisme";
  55820. break;
  55821. case BABYLON.PhysicsJoint.SliderJoint:
  55822. type = "jointSlide";
  55823. break;
  55824. case BABYLON.PhysicsJoint.WheelJoint:
  55825. type = "jointWheel";
  55826. break;
  55827. case BABYLON.PhysicsJoint.HingeJoint:
  55828. default:
  55829. type = "jointHinge";
  55830. break;
  55831. }
  55832. nativeJointData.type = type;
  55833. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  55834. };
  55835. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  55836. //Bug in Oimo prevents us from disposing a joint in the playground
  55837. //joint.joint.physicsJoint.dispose();
  55838. //So we will bruteforce it!
  55839. try {
  55840. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  55841. }
  55842. catch (e) {
  55843. BABYLON.Tools.Warn(e);
  55844. }
  55845. };
  55846. OimoJSPlugin.prototype.isSupported = function () {
  55847. return OIMO !== undefined;
  55848. };
  55849. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  55850. if (!impostor.physicsBody.sleeping) {
  55851. //TODO check that
  55852. if (impostor.physicsBody.shapes.next) {
  55853. var parentShape = this._getLastShape(impostor.physicsBody);
  55854. impostor.object.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  55855. impostor.object.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  55856. impostor.object.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  55857. }
  55858. else {
  55859. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  55860. }
  55861. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  55862. impostor.object.rotationQuaternion.normalize();
  55863. }
  55864. };
  55865. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  55866. var body = impostor.physicsBody;
  55867. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  55868. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  55869. body.syncShapes();
  55870. body.awake();
  55871. };
  55872. OimoJSPlugin.prototype._getLastShape = function (body) {
  55873. var lastShape = body.shapes;
  55874. while (lastShape.next) {
  55875. lastShape = lastShape.next;
  55876. }
  55877. return lastShape;
  55878. };
  55879. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  55880. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  55881. };
  55882. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  55883. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  55884. };
  55885. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  55886. var v = impostor.physicsBody.linearVelocity;
  55887. if (!v)
  55888. return null;
  55889. return new BABYLON.Vector3(v.x, v.y, v.z);
  55890. };
  55891. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  55892. var v = impostor.physicsBody.angularVelocity;
  55893. if (!v)
  55894. return null;
  55895. return new BABYLON.Vector3(v.x, v.y, v.z);
  55896. };
  55897. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  55898. var staticBody = mass === 0;
  55899. //this will actually set the body's density and not its mass.
  55900. //But this is how oimo treats the mass variable.
  55901. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  55902. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  55903. };
  55904. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  55905. impostor.physicsBody.sleep();
  55906. };
  55907. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  55908. impostor.physicsBody.awake();
  55909. };
  55910. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  55911. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  55912. if (minDistance !== void 0) {
  55913. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  55914. }
  55915. };
  55916. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  55917. //TODO separate rotational and transational motors.
  55918. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  55919. if (motor) {
  55920. motor.setMotor(speed, maxForce);
  55921. }
  55922. };
  55923. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  55924. //TODO separate rotational and transational motors.
  55925. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  55926. if (motor) {
  55927. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  55928. }
  55929. };
  55930. OimoJSPlugin.prototype.dispose = function () {
  55931. this.world.clear();
  55932. };
  55933. return OimoJSPlugin;
  55934. }());
  55935. BABYLON.OimoJSPlugin = OimoJSPlugin;
  55936. })(BABYLON || (BABYLON = {}));
  55937. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  55938. var BABYLON;
  55939. (function (BABYLON) {
  55940. var Internals;
  55941. (function (Internals) {
  55942. /*
  55943. * Based on jsTGALoader - Javascript loader for TGA file
  55944. * By Vincent Thibault
  55945. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  55946. */
  55947. var TGATools = (function () {
  55948. function TGATools() {
  55949. }
  55950. TGATools.GetTGAHeader = function (data) {
  55951. var offset = 0;
  55952. var header = {
  55953. id_length: data[offset++],
  55954. colormap_type: data[offset++],
  55955. image_type: data[offset++],
  55956. colormap_index: data[offset++] | data[offset++] << 8,
  55957. colormap_length: data[offset++] | data[offset++] << 8,
  55958. colormap_size: data[offset++],
  55959. origin: [
  55960. data[offset++] | data[offset++] << 8,
  55961. data[offset++] | data[offset++] << 8
  55962. ],
  55963. width: data[offset++] | data[offset++] << 8,
  55964. height: data[offset++] | data[offset++] << 8,
  55965. pixel_size: data[offset++],
  55966. flags: data[offset++]
  55967. };
  55968. return header;
  55969. };
  55970. TGATools.UploadContent = function (gl, data) {
  55971. // Not enough data to contain header ?
  55972. if (data.length < 19) {
  55973. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  55974. return;
  55975. }
  55976. // Read Header
  55977. var offset = 18;
  55978. var header = TGATools.GetTGAHeader(data);
  55979. // Assume it's a valid Targa file.
  55980. if (header.id_length + offset > data.length) {
  55981. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  55982. return;
  55983. }
  55984. // Skip not needed data
  55985. offset += header.id_length;
  55986. var use_rle = false;
  55987. var use_pal = false;
  55988. var use_rgb = false;
  55989. var use_grey = false;
  55990. // Get some informations.
  55991. switch (header.image_type) {
  55992. case TGATools._TYPE_RLE_INDEXED:
  55993. use_rle = true;
  55994. case TGATools._TYPE_INDEXED:
  55995. use_pal = true;
  55996. break;
  55997. case TGATools._TYPE_RLE_RGB:
  55998. use_rle = true;
  55999. case TGATools._TYPE_RGB:
  56000. use_rgb = true;
  56001. break;
  56002. case TGATools._TYPE_RLE_GREY:
  56003. use_rle = true;
  56004. case TGATools._TYPE_GREY:
  56005. use_grey = true;
  56006. break;
  56007. }
  56008. var pixel_data;
  56009. var numAlphaBits = header.flags & 0xf;
  56010. var pixel_size = header.pixel_size >> 3;
  56011. var pixel_total = header.width * header.height * pixel_size;
  56012. // Read palettes
  56013. var palettes;
  56014. if (use_pal) {
  56015. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  56016. }
  56017. // Read LRE
  56018. if (use_rle) {
  56019. pixel_data = new Uint8Array(pixel_total);
  56020. var c, count, i;
  56021. var localOffset = 0;
  56022. var pixels = new Uint8Array(pixel_size);
  56023. while (offset < pixel_total && localOffset < pixel_total) {
  56024. c = data[offset++];
  56025. count = (c & 0x7f) + 1;
  56026. // RLE pixels
  56027. if (c & 0x80) {
  56028. // Bind pixel tmp array
  56029. for (i = 0; i < pixel_size; ++i) {
  56030. pixels[i] = data[offset++];
  56031. }
  56032. // Copy pixel array
  56033. for (i = 0; i < count; ++i) {
  56034. pixel_data.set(pixels, localOffset + i * pixel_size);
  56035. }
  56036. localOffset += pixel_size * count;
  56037. }
  56038. else {
  56039. count *= pixel_size;
  56040. for (i = 0; i < count; ++i) {
  56041. pixel_data[localOffset + i] = data[offset++];
  56042. }
  56043. localOffset += count;
  56044. }
  56045. }
  56046. }
  56047. else {
  56048. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  56049. }
  56050. // Load to texture
  56051. var x_start, y_start, x_step, y_step, y_end, x_end;
  56052. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  56053. default:
  56054. case TGATools._ORIGIN_UL:
  56055. x_start = 0;
  56056. x_step = 1;
  56057. x_end = header.width;
  56058. y_start = 0;
  56059. y_step = 1;
  56060. y_end = header.height;
  56061. break;
  56062. case TGATools._ORIGIN_BL:
  56063. x_start = 0;
  56064. x_step = 1;
  56065. x_end = header.width;
  56066. y_start = header.height - 1;
  56067. y_step = -1;
  56068. y_end = -1;
  56069. break;
  56070. case TGATools._ORIGIN_UR:
  56071. x_start = header.width - 1;
  56072. x_step = -1;
  56073. x_end = -1;
  56074. y_start = 0;
  56075. y_step = 1;
  56076. y_end = header.height;
  56077. break;
  56078. case TGATools._ORIGIN_BR:
  56079. x_start = header.width - 1;
  56080. x_step = -1;
  56081. x_end = -1;
  56082. y_start = header.height - 1;
  56083. y_step = -1;
  56084. y_end = -1;
  56085. break;
  56086. }
  56087. // Load the specify method
  56088. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  56089. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  56090. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  56091. };
  56092. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  56093. var image = pixel_data, colormap = palettes;
  56094. var width = header.width, height = header.height;
  56095. var color, i = 0, x, y;
  56096. var imageData = new Uint8Array(width * height * 4);
  56097. for (y = y_start; y !== y_end; y += y_step) {
  56098. for (x = x_start; x !== x_end; x += x_step, i++) {
  56099. color = image[i];
  56100. imageData[(x + width * y) * 4 + 3] = 255;
  56101. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  56102. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  56103. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  56104. }
  56105. }
  56106. return imageData;
  56107. };
  56108. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  56109. var image = pixel_data;
  56110. var width = header.width, height = header.height;
  56111. var color, i = 0, x, y;
  56112. var imageData = new Uint8Array(width * height * 4);
  56113. for (y = y_start; y !== y_end; y += y_step) {
  56114. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  56115. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  56116. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  56117. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  56118. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  56119. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  56120. }
  56121. }
  56122. return imageData;
  56123. };
  56124. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  56125. var image = pixel_data;
  56126. var width = header.width, height = header.height;
  56127. var i = 0, x, y;
  56128. var imageData = new Uint8Array(width * height * 4);
  56129. for (y = y_start; y !== y_end; y += y_step) {
  56130. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  56131. imageData[(x + width * y) * 4 + 3] = 255;
  56132. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  56133. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  56134. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  56135. }
  56136. }
  56137. return imageData;
  56138. };
  56139. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  56140. var image = pixel_data;
  56141. var width = header.width, height = header.height;
  56142. var i = 0, x, y;
  56143. var imageData = new Uint8Array(width * height * 4);
  56144. for (y = y_start; y !== y_end; y += y_step) {
  56145. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  56146. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  56147. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  56148. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  56149. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  56150. }
  56151. }
  56152. return imageData;
  56153. };
  56154. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  56155. var image = pixel_data;
  56156. var width = header.width, height = header.height;
  56157. var color, i = 0, x, y;
  56158. var imageData = new Uint8Array(width * height * 4);
  56159. for (y = y_start; y !== y_end; y += y_step) {
  56160. for (x = x_start; x !== x_end; x += x_step, i++) {
  56161. color = image[i];
  56162. imageData[(x + width * y) * 4 + 0] = color;
  56163. imageData[(x + width * y) * 4 + 1] = color;
  56164. imageData[(x + width * y) * 4 + 2] = color;
  56165. imageData[(x + width * y) * 4 + 3] = 255;
  56166. }
  56167. }
  56168. return imageData;
  56169. };
  56170. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  56171. var image = pixel_data;
  56172. var width = header.width, height = header.height;
  56173. var i = 0, x, y;
  56174. var imageData = new Uint8Array(width * height * 4);
  56175. for (y = y_start; y !== y_end; y += y_step) {
  56176. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  56177. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  56178. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  56179. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  56180. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  56181. }
  56182. }
  56183. return imageData;
  56184. };
  56185. return TGATools;
  56186. }());
  56187. TGATools._TYPE_NO_DATA = 0;
  56188. TGATools._TYPE_INDEXED = 1;
  56189. TGATools._TYPE_RGB = 2;
  56190. TGATools._TYPE_GREY = 3;
  56191. TGATools._TYPE_RLE_INDEXED = 9;
  56192. TGATools._TYPE_RLE_RGB = 10;
  56193. TGATools._TYPE_RLE_GREY = 11;
  56194. TGATools._ORIGIN_MASK = 0x30;
  56195. TGATools._ORIGIN_SHIFT = 0x04;
  56196. TGATools._ORIGIN_BL = 0x00;
  56197. TGATools._ORIGIN_BR = 0x01;
  56198. TGATools._ORIGIN_UL = 0x02;
  56199. TGATools._ORIGIN_UR = 0x03;
  56200. Internals.TGATools = TGATools;
  56201. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  56202. })(BABYLON || (BABYLON = {}));
  56203. //# sourceMappingURL=babylon.tga.js.map
  56204. var BABYLON;
  56205. (function (BABYLON) {
  56206. var Internals;
  56207. (function (Internals) {
  56208. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  56209. // All values and structures referenced from:
  56210. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  56211. var DDS_MAGIC = 0x20534444;
  56212. 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;
  56213. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  56214. 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;
  56215. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  56216. function FourCCToInt32(value) {
  56217. return value.charCodeAt(0) +
  56218. (value.charCodeAt(1) << 8) +
  56219. (value.charCodeAt(2) << 16) +
  56220. (value.charCodeAt(3) << 24);
  56221. }
  56222. function Int32ToFourCC(value) {
  56223. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  56224. }
  56225. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  56226. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  56227. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  56228. var headerLengthInt = 31; // The header length in 32 bit ints
  56229. // Offsets into the header array
  56230. var off_magic = 0;
  56231. var off_size = 1;
  56232. var off_flags = 2;
  56233. var off_height = 3;
  56234. var off_width = 4;
  56235. var off_mipmapCount = 7;
  56236. var off_pfFlags = 20;
  56237. var off_pfFourCC = 21;
  56238. var off_RGBbpp = 22;
  56239. var off_RMask = 23;
  56240. var off_GMask = 24;
  56241. var off_BMask = 25;
  56242. var off_AMask = 26;
  56243. var off_caps1 = 27;
  56244. var off_caps2 = 28;
  56245. ;
  56246. var DDSTools = (function () {
  56247. function DDSTools() {
  56248. }
  56249. DDSTools.GetDDSInfo = function (arrayBuffer) {
  56250. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  56251. var mipmapCount = 1;
  56252. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  56253. mipmapCount = Math.max(1, header[off_mipmapCount]);
  56254. }
  56255. return {
  56256. width: header[off_width],
  56257. height: header[off_height],
  56258. mipmapCount: mipmapCount,
  56259. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  56260. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  56261. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  56262. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  56263. };
  56264. };
  56265. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  56266. var byteArray = new Uint8Array(dataLength);
  56267. var srcData = new Uint8Array(arrayBuffer);
  56268. var index = 0;
  56269. for (var y = height - 1; y >= 0; y--) {
  56270. for (var x = 0; x < width; x++) {
  56271. var srcPos = dataOffset + (x + y * width) * 4;
  56272. byteArray[index + 2] = srcData[srcPos];
  56273. byteArray[index + 1] = srcData[srcPos + 1];
  56274. byteArray[index] = srcData[srcPos + 2];
  56275. byteArray[index + 3] = srcData[srcPos + 3];
  56276. index += 4;
  56277. }
  56278. }
  56279. return byteArray;
  56280. };
  56281. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  56282. var byteArray = new Uint8Array(dataLength);
  56283. var srcData = new Uint8Array(arrayBuffer);
  56284. var index = 0;
  56285. for (var y = height - 1; y >= 0; y--) {
  56286. for (var x = 0; x < width; x++) {
  56287. var srcPos = dataOffset + (x + y * width) * 3;
  56288. byteArray[index + 2] = srcData[srcPos];
  56289. byteArray[index + 1] = srcData[srcPos + 1];
  56290. byteArray[index] = srcData[srcPos + 2];
  56291. index += 3;
  56292. }
  56293. }
  56294. return byteArray;
  56295. };
  56296. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  56297. var byteArray = new Uint8Array(dataLength);
  56298. var srcData = new Uint8Array(arrayBuffer);
  56299. var index = 0;
  56300. for (var y = height - 1; y >= 0; y--) {
  56301. for (var x = 0; x < width; x++) {
  56302. var srcPos = dataOffset + (x + y * width);
  56303. byteArray[index] = srcData[srcPos];
  56304. index++;
  56305. }
  56306. }
  56307. return byteArray;
  56308. };
  56309. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  56310. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  56311. if (header[off_magic] != DDS_MAGIC) {
  56312. BABYLON.Tools.Error("Invalid magic number in DDS header");
  56313. return;
  56314. }
  56315. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  56316. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  56317. return;
  56318. }
  56319. if (info.isFourCC) {
  56320. fourCC = header[off_pfFourCC];
  56321. switch (fourCC) {
  56322. case FOURCC_DXT1:
  56323. blockBytes = 8;
  56324. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  56325. break;
  56326. case FOURCC_DXT3:
  56327. blockBytes = 16;
  56328. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  56329. break;
  56330. case FOURCC_DXT5:
  56331. blockBytes = 16;
  56332. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  56333. break;
  56334. default:
  56335. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  56336. return;
  56337. }
  56338. }
  56339. mipmapCount = 1;
  56340. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  56341. mipmapCount = Math.max(1, header[off_mipmapCount]);
  56342. }
  56343. var bpp = header[off_RGBbpp];
  56344. for (var face = 0; face < faces; face++) {
  56345. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  56346. width = header[off_width];
  56347. height = header[off_height];
  56348. dataOffset = header[off_size] + 4;
  56349. for (i = 0; i < mipmapCount; ++i) {
  56350. if (info.isRGB) {
  56351. if (bpp === 24) {
  56352. dataLength = width * height * 3;
  56353. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  56354. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  56355. }
  56356. else {
  56357. dataLength = width * height * 4;
  56358. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  56359. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  56360. }
  56361. }
  56362. else if (info.isLuminance) {
  56363. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  56364. var unpaddedRowSize = width;
  56365. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  56366. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  56367. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  56368. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  56369. }
  56370. else {
  56371. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  56372. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  56373. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  56374. }
  56375. dataOffset += dataLength;
  56376. width *= 0.5;
  56377. height *= 0.5;
  56378. width = Math.max(1.0, width);
  56379. height = Math.max(1.0, height);
  56380. }
  56381. }
  56382. };
  56383. return DDSTools;
  56384. }());
  56385. Internals.DDSTools = DDSTools;
  56386. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  56387. })(BABYLON || (BABYLON = {}));
  56388. //# sourceMappingURL=babylon.dds.js.map
  56389. var BABYLON;
  56390. (function (BABYLON) {
  56391. var Internals;
  56392. (function (Internals) {
  56393. /**
  56394. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  56395. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  56396. */
  56397. var KhronosTextureContainer = (function () {
  56398. /**
  56399. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  56400. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  56401. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  56402. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  56403. */
  56404. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  56405. this.arrayBuffer = arrayBuffer;
  56406. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  56407. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  56408. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  56409. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  56410. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  56411. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  56412. BABYLON.Tools.Error("texture missing KTX identifier");
  56413. return;
  56414. }
  56415. // load the reset of the header in native 32 bit int
  56416. var header = new Int32Array(this.arrayBuffer, 12, 13);
  56417. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  56418. var oppositeEndianess = header[0] === 0x01020304;
  56419. // read all the header elements in order they exist in the file, without modification (sans endainness)
  56420. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  56421. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  56422. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  56423. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  56424. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  56425. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  56426. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  56427. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  56428. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  56429. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  56430. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  56431. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  56432. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  56433. if (this.glType !== 0) {
  56434. BABYLON.Tools.Error("only compressed formats currently supported");
  56435. return;
  56436. }
  56437. else {
  56438. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  56439. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  56440. }
  56441. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  56442. BABYLON.Tools.Error("only 2D textures currently supported");
  56443. return;
  56444. }
  56445. if (this.numberOfArrayElements !== 0) {
  56446. BABYLON.Tools.Error("texture arrays not currently supported");
  56447. return;
  56448. }
  56449. if (this.numberOfFaces !== facesExpected) {
  56450. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  56451. return;
  56452. }
  56453. // we now have a completely validated file, so could use existence of loadType as success
  56454. // would need to make this more elaborate & adjust checks above to support more than one load type
  56455. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  56456. }
  56457. // not as fast hardware based, but will probably never need to use
  56458. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  56459. return ((val & 0xFF) << 24)
  56460. | ((val & 0xFF00) << 8)
  56461. | ((val >> 8) & 0xFF00)
  56462. | ((val >> 24) & 0xFF);
  56463. };
  56464. /**
  56465. * It is assumed that the texture has already been created & is currently bound
  56466. */
  56467. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  56468. switch (this.loadType) {
  56469. case KhronosTextureContainer.COMPRESSED_2D:
  56470. this._upload2DCompressedLevels(gl, loadMipmaps);
  56471. break;
  56472. case KhronosTextureContainer.TEX_2D:
  56473. case KhronosTextureContainer.COMPRESSED_3D:
  56474. case KhronosTextureContainer.TEX_3D:
  56475. }
  56476. };
  56477. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  56478. // initialize width & height for level 1
  56479. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  56480. var width = this.pixelWidth;
  56481. var height = this.pixelHeight;
  56482. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  56483. for (var level = 0; level < mipmapCount; level++) {
  56484. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  56485. for (var face = 0; face < this.numberOfFaces; face++) {
  56486. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  56487. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  56488. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  56489. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  56490. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  56491. }
  56492. width = Math.max(1.0, width * 0.5);
  56493. height = Math.max(1.0, height * 0.5);
  56494. }
  56495. };
  56496. return KhronosTextureContainer;
  56497. }());
  56498. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  56499. // load types
  56500. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  56501. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  56502. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  56503. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  56504. Internals.KhronosTextureContainer = KhronosTextureContainer;
  56505. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  56506. })(BABYLON || (BABYLON = {}));
  56507. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  56508. var BABYLON;
  56509. (function (BABYLON) {
  56510. var DynamicFloatArrayElementInfo = (function () {
  56511. function DynamicFloatArrayElementInfo() {
  56512. }
  56513. return DynamicFloatArrayElementInfo;
  56514. }());
  56515. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  56516. /**
  56517. * 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.
  56518. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  56519. * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
  56520. * 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.
  56521. * 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.
  56522. * 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".
  56523. */
  56524. var DynamicFloatArray = (function () {
  56525. /**
  56526. * Construct an instance of the dynamic float array
  56527. * @param stride size of one element in float (i.e. not bytes!)
  56528. * @param initialElementCount the number of available entries at construction
  56529. */
  56530. function DynamicFloatArray(stride, initialElementCount) {
  56531. this.compareValueOffset = null;
  56532. this.sortingAscending = true;
  56533. this._stride = stride;
  56534. this.buffer = new Float32Array(stride * initialElementCount);
  56535. this._lastUsed = 0;
  56536. this._firstFree = 0;
  56537. this._allEntries = new Array(initialElementCount);
  56538. this._freeEntries = new Array(initialElementCount);
  56539. for (var i = 0; i < initialElementCount; i++) {
  56540. var element = new DynamicFloatArrayElementInfo();
  56541. element.offset = i * stride;
  56542. this._allEntries[i] = element;
  56543. this._freeEntries[initialElementCount - i - 1] = element;
  56544. }
  56545. }
  56546. /**
  56547. * Allocate an element in the array.
  56548. * @return the element info instance that contains the offset into the main buffer of the element's location.
  56549. * Beware, this offset may change when you call pack()
  56550. */
  56551. DynamicFloatArray.prototype.allocElement = function () {
  56552. if (this._freeEntries.length === 0) {
  56553. this._growBuffer();
  56554. }
  56555. var el = this._freeEntries.pop();
  56556. this._lastUsed = Math.max(el.offset, this._lastUsed);
  56557. if (el.offset === this._firstFree) {
  56558. if (this._freeEntries.length > 0) {
  56559. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  56560. }
  56561. else {
  56562. this._firstFree += this._stride;
  56563. }
  56564. }
  56565. return el;
  56566. };
  56567. /**
  56568. * Free the element corresponding to the given element info
  56569. * @param elInfo the element that describe the allocated element
  56570. */
  56571. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  56572. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  56573. this._freeEntries.push(elInfo);
  56574. };
  56575. /**
  56576. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  56577. * 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().
  56578. * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  56579. */
  56580. DynamicFloatArray.prototype.pack = function () {
  56581. // no free slot? no need to pack
  56582. if (this._freeEntries.length === 0) {
  56583. return this.buffer;
  56584. }
  56585. // If the buffer is already packed the last used will always be lower than the first free
  56586. // 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.
  56587. if (this._lastUsed < this._firstFree) {
  56588. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  56589. return elementsBuffer_1;
  56590. }
  56591. var s = this._stride;
  56592. // 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
  56593. var lastFree = new DynamicFloatArrayElementInfo();
  56594. lastFree.offset = this.totalElementCount * s;
  56595. this._freeEntries.push(lastFree);
  56596. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  56597. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  56598. var firstFreeSlotOffset = sortedFree[0].offset;
  56599. var freeZoneSize = 1;
  56600. var occupiedZoneSize = (this.usedElementCount + 1) * s;
  56601. var prevOffset = sortedFree[0].offset;
  56602. for (var i = 1; i < sortedFree.length; i++) {
  56603. // 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
  56604. if (firstFreeSlotOffset >= occupiedZoneSize) {
  56605. break;
  56606. }
  56607. var curFree = sortedFree[i];
  56608. var curOffset = curFree.offset;
  56609. // Compute the distance between this offset and the previous
  56610. var distance = curOffset - prevOffset;
  56611. // If the distance is the stride size, they are adjacent, it good, move to the next
  56612. if (distance === s) {
  56613. // Free zone is one element bigger
  56614. ++freeZoneSize;
  56615. // as we're about to iterate to the next, the cur becomes the previous...
  56616. prevOffset = curOffset;
  56617. continue;
  56618. }
  56619. // Distance is bigger, which means there's x element between the previous free and this one
  56620. var usedRange = (distance / s) - 1;
  56621. // Two cases the free zone is smaller than the data to move or bigger
  56622. // Copy what can fit in the free zone
  56623. var curMoveOffset = curOffset - s;
  56624. var copyCount = Math.min(freeZoneSize, usedRange);
  56625. for (var j = 0; j < copyCount; j++) {
  56626. var freeI = firstFreeSlotOffset / s;
  56627. var curI = curMoveOffset / s;
  56628. var moveEl = sortedAll[curI];
  56629. this._moveElement(moveEl, firstFreeSlotOffset);
  56630. var replacedEl = sortedAll[freeI];
  56631. // set the offset of the element we replaced with a value that will make it discard at the end of the method
  56632. replacedEl.offset = curMoveOffset;
  56633. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  56634. sortedAll[freeI] = moveEl;
  56635. sortedAll[curI] = replacedEl;
  56636. curMoveOffset -= s;
  56637. firstFreeSlotOffset += s;
  56638. }
  56639. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  56640. if (freeZoneSize <= usedRange) {
  56641. firstFreeSlotOffset = curMoveOffset + s;
  56642. freeZoneSize = 1 + copyCount;
  56643. }
  56644. else {
  56645. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  56646. }
  56647. // as we're about to iterate to the next, the cur becomes the previous...
  56648. prevOffset = curOffset;
  56649. }
  56650. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  56651. this._lastUsed = firstFreeSlotOffset - s;
  56652. this._firstFree = firstFreeSlotOffset;
  56653. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  56654. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  56655. this._allEntries = sortedAll;
  56656. return elementsBuffer;
  56657. };
  56658. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  56659. for (var i = 0; i < this._stride; i++) {
  56660. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  56661. }
  56662. element.offset = destOffset;
  56663. };
  56664. DynamicFloatArray.prototype._growBuffer = function () {
  56665. // Allocate the new buffer with 50% more entries, copy the content of the current one
  56666. var newElCount = Math.floor(this.totalElementCount * 1.5);
  56667. var newBuffer = new Float32Array(newElCount * this._stride);
  56668. newBuffer.set(this.buffer);
  56669. var curCount = this.totalElementCount;
  56670. var addedCount = newElCount - this.totalElementCount;
  56671. for (var i = 0; i < addedCount; i++) {
  56672. var element = new DynamicFloatArrayElementInfo();
  56673. element.offset = (curCount + i) * this.stride;
  56674. this._allEntries.push(element);
  56675. this._freeEntries[addedCount - i - 1] = element;
  56676. }
  56677. this._firstFree = curCount * this.stride;
  56678. this.buffer = newBuffer;
  56679. };
  56680. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  56681. /**
  56682. * Get the total count of entries that can fit in the current buffer
  56683. * @returns the elements count
  56684. */
  56685. get: function () {
  56686. return this._allEntries.length;
  56687. },
  56688. enumerable: true,
  56689. configurable: true
  56690. });
  56691. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  56692. /**
  56693. * Get the count of free entries that can still be allocated without resizing the buffer
  56694. * @returns the free elements count
  56695. */
  56696. get: function () {
  56697. return this._freeEntries.length;
  56698. },
  56699. enumerable: true,
  56700. configurable: true
  56701. });
  56702. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  56703. /**
  56704. * Get the count of allocated elements
  56705. * @returns the allocated elements count
  56706. */
  56707. get: function () {
  56708. return this._allEntries.length - this._freeEntries.length;
  56709. },
  56710. enumerable: true,
  56711. configurable: true
  56712. });
  56713. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  56714. /**
  56715. * Return the size of one element in float
  56716. * @returns the size in float
  56717. */
  56718. get: function () {
  56719. return this._stride;
  56720. },
  56721. enumerable: true,
  56722. configurable: true
  56723. });
  56724. DynamicFloatArray.prototype.sort = function () {
  56725. var _this = this;
  56726. if (!this.compareValueOffset) {
  56727. throw new Error("The DynamicFloatArray.sort() method needs a valid 'compareValueOffset' property");
  56728. }
  56729. var count = this.usedElementCount;
  56730. // Do we have to (re)create the sort table?
  56731. if (!this._sortTable || this._sortTable.length < count) {
  56732. // 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...
  56733. var newCount = Math.min(this.totalElementCount, count * 2);
  56734. this._sortTable = new Array(newCount);
  56735. }
  56736. if (!this._sortedTable || this._sortedTable.length !== count) {
  56737. this._sortedTable = new Array(count);
  56738. }
  56739. // Because, you know...
  56740. this.pack();
  56741. //let stride = this.stride;
  56742. //for (let i = 0; i < count; i++) {
  56743. // let si = this._sortTable[i];
  56744. // if (!si) {
  56745. // si = new SortInfo();
  56746. // this._sortTable[i] = si;
  56747. // }
  56748. // si.entry = this._allEntries[i];
  56749. // si.compareData = this.buffer[si.entry.offset + this.compareValueOffset];
  56750. // si.swapedOffset = null;
  56751. // this._sortedTable[i] = si;
  56752. //}
  56753. var curOffset = 0;
  56754. var stride = this.stride;
  56755. for (var i = 0; i < count; i++, curOffset += stride) {
  56756. var si = this._sortTable[i];
  56757. if (!si) {
  56758. si = new SortInfo();
  56759. this._sortTable[i] = si;
  56760. }
  56761. si.compareData = this.buffer[curOffset + this.compareValueOffset];
  56762. si.offset = curOffset;
  56763. si.swapedOffset = null;
  56764. this._sortedTable[i] = si;
  56765. }
  56766. // Let's sort the sorted table, we want to keep a track of the original one (that's why we have two buffers)
  56767. if (this.sortingAscending) {
  56768. this._sortedTable.sort(function (a, b) { return a.compareData - b.compareData; });
  56769. }
  56770. else {
  56771. this._sortedTable.sort(function (a, b) { return b.compareData - a.compareData; });
  56772. }
  56773. var swapElements = function (src, dst) {
  56774. for (var i = 0; i < stride; i++) {
  56775. var tps = _this.buffer[dst + i];
  56776. _this.buffer[dst + i] = _this.buffer[src + i];
  56777. _this.buffer[src + i] = tps;
  56778. }
  56779. };
  56780. // 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:
  56781. // 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),
  56782. // and I still want something with a good algorithm complexity.
  56783. // 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,
  56784. // we need sortTable for that, it contains the original layout of SortInfo object, not the sorted one.
  56785. // The best way is to use an extra field in SortInfo, because potentially every element can be replaced.
  56786. // 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
  56787. // until we find a SortInfo object without a swapedOffset which means we got the right location
  56788. // 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
  56789. // than a double allocation of the whole float32Array or a O(n²/2) typical algorithm.
  56790. for (var i = 0; i < count; i++) {
  56791. // Get the element to move
  56792. var sourceSI = this._sortedTable[i];
  56793. var destSI = this._sortTable[i];
  56794. var sourceOff = sourceSI.offset;
  56795. // If the source changed location, find the new one
  56796. if (sourceSI.swapedOffset) {
  56797. // Follow the swapedOffset until there's none, it will mean that curSI contains the new location in its offset member
  56798. var curSI = sourceSI;
  56799. while (curSI.swapedOffset) {
  56800. curSI = this._sortTable[curSI.swapedOffset / stride];
  56801. }
  56802. // Finally get the right location
  56803. sourceOff = curSI.offset;
  56804. }
  56805. // Tag the element being replaced with its new location
  56806. destSI.swapedOffset = sourceOff;
  56807. // Swap elements (only if needed)
  56808. if (sourceOff !== destSI.offset) {
  56809. swapElements(sourceOff, destSI.offset);
  56810. }
  56811. // Update the offset in the corresponding DFAE
  56812. //sourceSI.entry.offset = destSI.entry.offset;
  56813. this._allEntries[sourceSI.offset / stride].offset = destSI.offset;
  56814. }
  56815. this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  56816. return true;
  56817. };
  56818. return DynamicFloatArray;
  56819. }());
  56820. BABYLON.DynamicFloatArray = DynamicFloatArray;
  56821. var SortInfo = (function () {
  56822. function SortInfo() {
  56823. this.compareData = this.offset = this.swapedOffset = null;
  56824. }
  56825. return SortInfo;
  56826. }());
  56827. })(BABYLON || (BABYLON = {}));
  56828. //# sourceMappingURL=babylon.dynamicFloatArray.js.map
  56829. var BABYLON;
  56830. (function (BABYLON) {
  56831. var Debug;
  56832. (function (Debug) {
  56833. /**
  56834. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  56835. */
  56836. var SkeletonViewer = (function () {
  56837. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  56838. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  56839. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  56840. this.skeleton = skeleton;
  56841. this.mesh = mesh;
  56842. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  56843. this.renderingGroupId = renderingGroupId;
  56844. this.color = BABYLON.Color3.White();
  56845. this._debugLines = [];
  56846. this._isEnabled = false;
  56847. this._scene = scene;
  56848. this.update();
  56849. this._renderFunction = this.update.bind(this);
  56850. }
  56851. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  56852. get: function () {
  56853. return this._isEnabled;
  56854. },
  56855. set: function (value) {
  56856. if (this._isEnabled === value) {
  56857. return;
  56858. }
  56859. this._isEnabled = value;
  56860. if (value) {
  56861. this._scene.registerBeforeRender(this._renderFunction);
  56862. }
  56863. else {
  56864. this._scene.unregisterBeforeRender(this._renderFunction);
  56865. }
  56866. },
  56867. enumerable: true,
  56868. configurable: true
  56869. });
  56870. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  56871. if (x === void 0) { x = 0; }
  56872. if (y === void 0) { y = 0; }
  56873. if (z === void 0) { z = 0; }
  56874. var tmat = BABYLON.Tmp.Matrix[0];
  56875. var parentBone = bone.getParent();
  56876. tmat.copyFrom(bone.getLocalMatrix());
  56877. if (x !== 0 || y !== 0 || z !== 0) {
  56878. var tmat2 = BABYLON.Tmp.Matrix[1];
  56879. BABYLON.Matrix.IdentityToRef(tmat2);
  56880. tmat2.m[12] = x;
  56881. tmat2.m[13] = y;
  56882. tmat2.m[14] = z;
  56883. tmat2.multiplyToRef(tmat, tmat);
  56884. }
  56885. if (parentBone) {
  56886. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  56887. }
  56888. tmat.multiplyToRef(meshMat, tmat);
  56889. position.x = tmat.m[12];
  56890. position.y = tmat.m[13];
  56891. position.z = tmat.m[14];
  56892. };
  56893. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  56894. var len = bones.length;
  56895. var meshPos = this.mesh.position;
  56896. for (var i = 0; i < len; i++) {
  56897. var bone = bones[i];
  56898. var points = this._debugLines[i];
  56899. if (!points) {
  56900. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  56901. this._debugLines[i] = points;
  56902. }
  56903. this._getBonePosition(points[0], bone, meshMat);
  56904. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  56905. points[0].subtractInPlace(meshPos);
  56906. points[1].subtractInPlace(meshPos);
  56907. }
  56908. };
  56909. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  56910. var len = bones.length;
  56911. var boneNum = 0;
  56912. var meshPos = this.mesh.position;
  56913. for (var i = len - 1; i >= 0; i--) {
  56914. var childBone = bones[i];
  56915. var parentBone = childBone.getParent();
  56916. if (!parentBone) {
  56917. continue;
  56918. }
  56919. var points = this._debugLines[boneNum];
  56920. if (!points) {
  56921. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  56922. this._debugLines[boneNum] = points;
  56923. }
  56924. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  56925. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  56926. points[0].subtractInPlace(meshPos);
  56927. points[1].subtractInPlace(meshPos);
  56928. boneNum++;
  56929. }
  56930. };
  56931. SkeletonViewer.prototype.update = function () {
  56932. if (this.autoUpdateBonesMatrices) {
  56933. this.skeleton.computeAbsoluteTransforms();
  56934. }
  56935. if (this.skeleton.bones[0].length === undefined) {
  56936. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  56937. }
  56938. else {
  56939. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  56940. }
  56941. if (!this._debugMesh) {
  56942. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  56943. this._debugMesh.renderingGroupId = this.renderingGroupId;
  56944. }
  56945. else {
  56946. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  56947. }
  56948. this._debugMesh.position.copyFrom(this.mesh.position);
  56949. this._debugMesh.color = this.color;
  56950. };
  56951. SkeletonViewer.prototype.dispose = function () {
  56952. if (this._debugMesh) {
  56953. this.isEnabled = false;
  56954. this._debugMesh.dispose();
  56955. this._debugMesh = null;
  56956. }
  56957. };
  56958. return SkeletonViewer;
  56959. }());
  56960. Debug.SkeletonViewer = SkeletonViewer;
  56961. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  56962. })(BABYLON || (BABYLON = {}));
  56963. //# sourceMappingURL=babylon.skeletonViewer.js.map
  56964. var BABYLON;
  56965. (function (BABYLON) {
  56966. var Debug;
  56967. (function (Debug) {
  56968. var AxesViewer = (function () {
  56969. function AxesViewer(scene, scaleLines) {
  56970. if (scaleLines === void 0) { scaleLines = 1; }
  56971. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  56972. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  56973. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  56974. this.scaleLines = 1;
  56975. this.scaleLines = scaleLines;
  56976. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  56977. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  56978. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  56979. this._xmesh.renderingGroupId = 2;
  56980. this._ymesh.renderingGroupId = 2;
  56981. this._zmesh.renderingGroupId = 2;
  56982. this._xmesh.material.checkReadyOnlyOnce = true;
  56983. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  56984. this._ymesh.material.checkReadyOnlyOnce = true;
  56985. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  56986. this._zmesh.material.checkReadyOnlyOnce = true;
  56987. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  56988. this.scene = scene;
  56989. }
  56990. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  56991. var scaleLines = this.scaleLines;
  56992. this._xmesh.position.copyFrom(position);
  56993. this._ymesh.position.copyFrom(position);
  56994. this._zmesh.position.copyFrom(position);
  56995. var point2 = this._xline[1];
  56996. point2.x = xaxis.x * scaleLines;
  56997. point2.y = xaxis.y * scaleLines;
  56998. point2.z = xaxis.z * scaleLines;
  56999. BABYLON.Mesh.CreateLines(null, this._xline, null, null, this._xmesh);
  57000. point2 = this._yline[1];
  57001. point2.x = yaxis.x * scaleLines;
  57002. point2.y = yaxis.y * scaleLines;
  57003. point2.z = yaxis.z * scaleLines;
  57004. BABYLON.Mesh.CreateLines(null, this._yline, null, null, this._ymesh);
  57005. point2 = this._zline[1];
  57006. point2.x = zaxis.x * scaleLines;
  57007. point2.y = zaxis.y * scaleLines;
  57008. point2.z = zaxis.z * scaleLines;
  57009. BABYLON.Mesh.CreateLines(null, this._zline, null, null, this._zmesh);
  57010. };
  57011. AxesViewer.prototype.dispose = function () {
  57012. if (this._xmesh) {
  57013. this._xmesh.dispose();
  57014. this._ymesh.dispose();
  57015. this._zmesh.dispose();
  57016. this._xmesh = null;
  57017. this._ymesh = null;
  57018. this._zmesh = null;
  57019. this._xline = null;
  57020. this._yline = null;
  57021. this._zline = null;
  57022. this.scene = null;
  57023. }
  57024. };
  57025. return AxesViewer;
  57026. }());
  57027. Debug.AxesViewer = AxesViewer;
  57028. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  57029. })(BABYLON || (BABYLON = {}));
  57030. //# sourceMappingURL=babylon.axesViewer.js.map
  57031. var BABYLON;
  57032. (function (BABYLON) {
  57033. var Debug;
  57034. (function (Debug) {
  57035. var BoneAxesViewer = (function (_super) {
  57036. __extends(BoneAxesViewer, _super);
  57037. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  57038. if (scaleLines === void 0) { scaleLines = 1; }
  57039. var _this = _super.call(this, scene, scaleLines) || this;
  57040. _this.pos = BABYLON.Vector3.Zero();
  57041. _this.xaxis = BABYLON.Vector3.Zero();
  57042. _this.yaxis = BABYLON.Vector3.Zero();
  57043. _this.zaxis = BABYLON.Vector3.Zero();
  57044. _this.mesh = mesh;
  57045. _this.bone = bone;
  57046. return _this;
  57047. }
  57048. BoneAxesViewer.prototype.update = function () {
  57049. var bone = this.bone;
  57050. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  57051. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  57052. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  57053. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  57054. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  57055. };
  57056. BoneAxesViewer.prototype.dispose = function () {
  57057. if (this.pos) {
  57058. this.pos = null;
  57059. this.xaxis = null;
  57060. this.yaxis = null;
  57061. this.zaxis = null;
  57062. this.mesh = null;
  57063. this.bone = null;
  57064. _super.prototype.dispose.call(this);
  57065. }
  57066. };
  57067. return BoneAxesViewer;
  57068. }(Debug.AxesViewer));
  57069. Debug.BoneAxesViewer = BoneAxesViewer;
  57070. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  57071. })(BABYLON || (BABYLON = {}));
  57072. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  57073. var BABYLON;
  57074. (function (BABYLON) {
  57075. var RayHelper = (function () {
  57076. function RayHelper(ray) {
  57077. this.ray = ray;
  57078. }
  57079. RayHelper.CreateAndShow = function (ray, scene, color) {
  57080. var helper = new RayHelper(ray);
  57081. helper.show(scene, color);
  57082. return helper;
  57083. };
  57084. RayHelper.prototype.show = function (scene, color) {
  57085. if (!this._renderFunction) {
  57086. var ray = this.ray;
  57087. this._renderFunction = this._render.bind(this);
  57088. this._scene = scene;
  57089. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  57090. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  57091. this._scene.registerBeforeRender(this._renderFunction);
  57092. }
  57093. if (color) {
  57094. this._renderLine.color.copyFrom(color);
  57095. }
  57096. };
  57097. RayHelper.prototype.hide = function () {
  57098. if (this._renderFunction) {
  57099. this._scene.unregisterBeforeRender(this._renderFunction);
  57100. this._scene = null;
  57101. this._renderFunction = null;
  57102. this._renderLine.dispose();
  57103. this._renderLine = null;
  57104. this._renderPoints = null;
  57105. }
  57106. };
  57107. RayHelper.prototype._render = function () {
  57108. var ray = this.ray;
  57109. var point = this._renderPoints[1];
  57110. var len = Math.min(ray.length, 1000000);
  57111. point.copyFrom(ray.direction);
  57112. point.scaleInPlace(len);
  57113. point.addInPlace(ray.origin);
  57114. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  57115. };
  57116. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  57117. this._attachedToMesh = mesh;
  57118. var ray = this.ray;
  57119. if (!ray.direction) {
  57120. ray.direction = BABYLON.Vector3.Zero();
  57121. }
  57122. if (!ray.origin) {
  57123. ray.origin = BABYLON.Vector3.Zero();
  57124. }
  57125. if (length) {
  57126. ray.length = length;
  57127. }
  57128. if (!meshSpaceOrigin) {
  57129. meshSpaceOrigin = BABYLON.Vector3.Zero();
  57130. }
  57131. if (!meshSpaceDirection) {
  57132. // -1 so that this will work with Mesh.lookAt
  57133. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  57134. }
  57135. if (!this._meshSpaceDirection) {
  57136. this._meshSpaceDirection = meshSpaceDirection.clone();
  57137. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  57138. }
  57139. else {
  57140. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  57141. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  57142. }
  57143. if (!this._updateToMeshFunction) {
  57144. this._updateToMeshFunction = this._updateToMesh.bind(this);
  57145. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  57146. }
  57147. this._updateToMesh();
  57148. };
  57149. RayHelper.prototype.detachFromMesh = function () {
  57150. if (this._attachedToMesh) {
  57151. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  57152. this._attachedToMesh = null;
  57153. this._updateToMeshFunction = null;
  57154. }
  57155. };
  57156. RayHelper.prototype._updateToMesh = function () {
  57157. var ray = this.ray;
  57158. if (this._attachedToMesh._isDisposed) {
  57159. this.detachFromMesh();
  57160. return;
  57161. }
  57162. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  57163. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  57164. };
  57165. RayHelper.prototype.dispose = function () {
  57166. this.hide();
  57167. this.detachFromMesh();
  57168. this.ray = null;
  57169. };
  57170. return RayHelper;
  57171. }());
  57172. BABYLON.RayHelper = RayHelper;
  57173. })(BABYLON || (BABYLON = {}));
  57174. //# sourceMappingURL=babylon.rayHelper.js.map
  57175. var BABYLON;
  57176. (function (BABYLON) {
  57177. var DebugLayer = (function () {
  57178. function DebugLayer(scene) {
  57179. this._scene = scene;
  57180. }
  57181. /** Creates the inspector window. */
  57182. DebugLayer.prototype._createInspector = function (config) {
  57183. if (config === void 0) { config = {}; }
  57184. var popup = config.popup || false;
  57185. var initialTab = config.initialTab || 0;
  57186. var parentElement = config.parentElement || null;
  57187. if (!this._inspector) {
  57188. this._inspector = new INSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  57189. } // else nothing to do,; instance is already existing
  57190. };
  57191. DebugLayer.prototype.isVisible = function () {
  57192. if (!this._inspector) {
  57193. return false;
  57194. }
  57195. return true;
  57196. };
  57197. DebugLayer.prototype.hide = function () {
  57198. if (this._inspector) {
  57199. try {
  57200. this._inspector.dispose();
  57201. }
  57202. catch (e) {
  57203. // If the inspector has been removed directly from the inspector tool
  57204. }
  57205. this._inspector = null;
  57206. }
  57207. };
  57208. DebugLayer.prototype.show = function (config) {
  57209. if (config === void 0) { config = {}; }
  57210. if (typeof INSPECTOR == 'undefined') {
  57211. // Load inspector and add it to the DOM
  57212. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  57213. }
  57214. else {
  57215. // Otherwise creates the inspector
  57216. this._createInspector(config);
  57217. }
  57218. };
  57219. return DebugLayer;
  57220. }());
  57221. // Get protocol used - http or https
  57222. DebugLayer.InspectorURL = window.location.href.split('/')[0] + '//www.babylonjs.com/babylon.inspector.bundle.js';
  57223. BABYLON.DebugLayer = DebugLayer;
  57224. })(BABYLON || (BABYLON = {}));
  57225. //# sourceMappingURL=babylon.debugLayer.js.map
  57226. var BABYLON;
  57227. (function (BABYLON) {
  57228. var BoundingBoxRenderer = (function () {
  57229. function BoundingBoxRenderer(scene) {
  57230. this.frontColor = new BABYLON.Color3(1, 1, 1);
  57231. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  57232. this.showBackLines = true;
  57233. this.renderList = new BABYLON.SmartArray(32);
  57234. this._vertexBuffers = {};
  57235. this._scene = scene;
  57236. }
  57237. BoundingBoxRenderer.prototype._prepareRessources = function () {
  57238. if (this._colorShader) {
  57239. return;
  57240. }
  57241. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  57242. attributes: [BABYLON.VertexBuffer.PositionKind],
  57243. uniforms: ["world", "viewProjection", "color"]
  57244. });
  57245. var engine = this._scene.getEngine();
  57246. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  57247. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  57248. 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]);
  57249. };
  57250. BoundingBoxRenderer.prototype.reset = function () {
  57251. this.renderList.reset();
  57252. };
  57253. BoundingBoxRenderer.prototype.render = function () {
  57254. if (this.renderList.length === 0) {
  57255. return;
  57256. }
  57257. this._prepareRessources();
  57258. if (!this._colorShader.isReady()) {
  57259. return;
  57260. }
  57261. var engine = this._scene.getEngine();
  57262. engine.setDepthWrite(false);
  57263. this._colorShader._preBind();
  57264. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  57265. var boundingBox = this.renderList.data[boundingBoxIndex];
  57266. var min = boundingBox.minimum;
  57267. var max = boundingBox.maximum;
  57268. var diff = max.subtract(min);
  57269. var median = min.add(diff.scale(0.5));
  57270. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  57271. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  57272. .multiply(boundingBox.getWorldMatrix());
  57273. // VBOs
  57274. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  57275. if (this.showBackLines) {
  57276. // Back
  57277. engine.setDepthFunctionToGreaterOrEqual();
  57278. this._scene.resetCachedMaterial();
  57279. this._colorShader.setColor4("color", this.backColor.toColor4());
  57280. this._colorShader.bind(worldMatrix);
  57281. // Draw order
  57282. engine.draw(false, 0, 24);
  57283. }
  57284. // Front
  57285. engine.setDepthFunctionToLess();
  57286. this._scene.resetCachedMaterial();
  57287. this._colorShader.setColor4("color", this.frontColor.toColor4());
  57288. this._colorShader.bind(worldMatrix);
  57289. // Draw order
  57290. engine.draw(false, 0, 24);
  57291. }
  57292. this._colorShader.unbind();
  57293. engine.setDepthFunctionToLessOrEqual();
  57294. engine.setDepthWrite(true);
  57295. };
  57296. BoundingBoxRenderer.prototype.dispose = function () {
  57297. if (!this._colorShader) {
  57298. return;
  57299. }
  57300. this.renderList.dispose();
  57301. this._colorShader.dispose();
  57302. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  57303. if (buffer) {
  57304. buffer.dispose();
  57305. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  57306. }
  57307. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  57308. };
  57309. return BoundingBoxRenderer;
  57310. }());
  57311. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  57312. })(BABYLON || (BABYLON = {}));
  57313. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  57314. var BABYLON;
  57315. (function (BABYLON) {
  57316. var MorphTarget = (function () {
  57317. function MorphTarget(name, influence) {
  57318. if (influence === void 0) { influence = 0; }
  57319. this.name = name;
  57320. this.animations = new Array();
  57321. this.onInfluenceChanged = new BABYLON.Observable();
  57322. this.influence = influence;
  57323. }
  57324. Object.defineProperty(MorphTarget.prototype, "influence", {
  57325. get: function () {
  57326. return this._influence;
  57327. },
  57328. set: function (influence) {
  57329. if (this._influence === influence) {
  57330. return;
  57331. }
  57332. var previous = this._influence;
  57333. this._influence = influence;
  57334. if (this.onInfluenceChanged.hasObservers) {
  57335. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  57336. }
  57337. },
  57338. enumerable: true,
  57339. configurable: true
  57340. });
  57341. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  57342. get: function () {
  57343. return this._normals !== undefined;
  57344. },
  57345. enumerable: true,
  57346. configurable: true
  57347. });
  57348. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  57349. get: function () {
  57350. return this._tangents !== undefined;
  57351. },
  57352. enumerable: true,
  57353. configurable: true
  57354. });
  57355. MorphTarget.prototype.setPositions = function (data) {
  57356. this._positions = new Float32Array(data);
  57357. };
  57358. MorphTarget.prototype.getPositions = function () {
  57359. return this._positions;
  57360. };
  57361. MorphTarget.prototype.setNormals = function (data) {
  57362. this._normals = new Float32Array(data);
  57363. };
  57364. MorphTarget.prototype.getNormals = function () {
  57365. return this._normals;
  57366. };
  57367. MorphTarget.prototype.setTangents = function (data) {
  57368. this._tangents = new Float32Array(data);
  57369. };
  57370. MorphTarget.prototype.getTangents = function () {
  57371. return this._tangents;
  57372. };
  57373. /**
  57374. * Serializes the current target into a Serialization object.
  57375. * Returns the serialized object.
  57376. */
  57377. MorphTarget.prototype.serialize = function () {
  57378. var serializationObject = {};
  57379. serializationObject.name = this.name;
  57380. serializationObject.influence = this.influence;
  57381. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  57382. if (this.hasNormals) {
  57383. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  57384. }
  57385. if (this.hasTangents) {
  57386. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  57387. }
  57388. return serializationObject;
  57389. };
  57390. // Statics
  57391. MorphTarget.Parse = function (serializationObject) {
  57392. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  57393. result.setPositions(serializationObject.positions);
  57394. if (serializationObject.normals) {
  57395. result.setNormals(serializationObject.normals);
  57396. }
  57397. if (serializationObject.tangents) {
  57398. result.setTangents(serializationObject.tangents);
  57399. }
  57400. return result;
  57401. };
  57402. MorphTarget.FromMesh = function (mesh, name, influence) {
  57403. if (!name) {
  57404. name = mesh.name;
  57405. }
  57406. var result = new MorphTarget(name, influence);
  57407. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  57408. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  57409. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  57410. }
  57411. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  57412. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  57413. }
  57414. return result;
  57415. };
  57416. return MorphTarget;
  57417. }());
  57418. BABYLON.MorphTarget = MorphTarget;
  57419. })(BABYLON || (BABYLON = {}));
  57420. //# sourceMappingURL=babylon.morphTarget.js.map
  57421. var BABYLON;
  57422. (function (BABYLON) {
  57423. var MorphTargetManager = (function () {
  57424. function MorphTargetManager(scene) {
  57425. this._targets = new Array();
  57426. this._targetObservable = new Array();
  57427. this._activeTargets = new BABYLON.SmartArray(16);
  57428. this._supportsNormals = false;
  57429. this._supportsTangents = false;
  57430. this._vertexCount = 0;
  57431. this._uniqueId = 0;
  57432. if (!scene) {
  57433. scene = BABYLON.Engine.LastCreatedScene;
  57434. }
  57435. this._scene = scene;
  57436. this._scene.morphTargetManagers.push(this);
  57437. this._uniqueId = scene.getUniqueId();
  57438. }
  57439. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  57440. get: function () {
  57441. return this._uniqueId;
  57442. },
  57443. enumerable: true,
  57444. configurable: true
  57445. });
  57446. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  57447. get: function () {
  57448. return this._vertexCount;
  57449. },
  57450. enumerable: true,
  57451. configurable: true
  57452. });
  57453. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  57454. get: function () {
  57455. return this._supportsNormals;
  57456. },
  57457. enumerable: true,
  57458. configurable: true
  57459. });
  57460. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  57461. get: function () {
  57462. return this._supportsTangents;
  57463. },
  57464. enumerable: true,
  57465. configurable: true
  57466. });
  57467. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  57468. get: function () {
  57469. return this._targets.length;
  57470. },
  57471. enumerable: true,
  57472. configurable: true
  57473. });
  57474. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  57475. get: function () {
  57476. return this._activeTargets.length;
  57477. },
  57478. enumerable: true,
  57479. configurable: true
  57480. });
  57481. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  57482. get: function () {
  57483. return this._influences;
  57484. },
  57485. enumerable: true,
  57486. configurable: true
  57487. });
  57488. MorphTargetManager.prototype.getActiveTarget = function (index) {
  57489. return this._activeTargets.data[index];
  57490. };
  57491. MorphTargetManager.prototype.getTarget = function (index) {
  57492. return this._targets[index];
  57493. };
  57494. MorphTargetManager.prototype.addTarget = function (target) {
  57495. var _this = this;
  57496. if (this._vertexCount) {
  57497. if (this._vertexCount !== target.getPositions().length / 3) {
  57498. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  57499. return;
  57500. }
  57501. }
  57502. this._targets.push(target);
  57503. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  57504. _this._syncActiveTargets(needUpdate);
  57505. }));
  57506. this._syncActiveTargets(true);
  57507. };
  57508. MorphTargetManager.prototype.removeTarget = function (target) {
  57509. var index = this._targets.indexOf(target);
  57510. if (index >= 0) {
  57511. this._targets.splice(index, 1);
  57512. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  57513. this._vertexCount = 0;
  57514. this._syncActiveTargets(true);
  57515. }
  57516. };
  57517. /**
  57518. * Serializes the current manager into a Serialization object.
  57519. * Returns the serialized object.
  57520. */
  57521. MorphTargetManager.prototype.serialize = function () {
  57522. var serializationObject = {};
  57523. serializationObject.id = this.uniqueId;
  57524. serializationObject.targets = [];
  57525. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  57526. var target = _a[_i];
  57527. serializationObject.targets.push(target.serialize());
  57528. }
  57529. return serializationObject;
  57530. };
  57531. MorphTargetManager.prototype._onInfluenceChanged = function (needUpdate) {
  57532. this._syncActiveTargets(needUpdate);
  57533. };
  57534. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  57535. this._activeTargets.reset();
  57536. var tempInfluences = [];
  57537. this._supportsNormals = true;
  57538. this._supportsTangents = true;
  57539. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  57540. var target = _a[_i];
  57541. if (target.influence > 0) {
  57542. this._activeTargets.push(target);
  57543. tempInfluences.push(target.influence);
  57544. this._supportsNormals = this._supportsNormals && target.hasNormals;
  57545. this._supportsTangents = this._supportsTangents && target.hasTangents;
  57546. if (this._vertexCount === 0) {
  57547. this._vertexCount = target.getPositions().length / 3;
  57548. }
  57549. }
  57550. }
  57551. this._influences = new Float32Array(tempInfluences);
  57552. if (needUpdate) {
  57553. // Flag meshes as dirty to resync with the active targets
  57554. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  57555. var mesh = _c[_b];
  57556. if (mesh.morphTargetManager === this) {
  57557. mesh._syncGeometryWithMorphTargetManager();
  57558. }
  57559. }
  57560. }
  57561. };
  57562. // Statics
  57563. MorphTargetManager.Parse = function (serializationObject, scene) {
  57564. var result = new MorphTargetManager(scene);
  57565. result._uniqueId = serializationObject.id;
  57566. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  57567. var targetData = _a[_i];
  57568. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  57569. }
  57570. return result;
  57571. };
  57572. return MorphTargetManager;
  57573. }());
  57574. BABYLON.MorphTargetManager = MorphTargetManager;
  57575. })(BABYLON || (BABYLON = {}));
  57576. //# sourceMappingURL=babylon.morphTargetManager.js.map
  57577. var BABYLON;
  57578. (function (BABYLON) {
  57579. /**
  57580. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  57581. * It can help converting any input color in a desired output one. This can then be used to create effects
  57582. * from sepia, black and white to sixties or futuristic rendering...
  57583. *
  57584. * The only supported format is currently 3dl.
  57585. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  57586. */
  57587. var ColorGradingTexture = (function (_super) {
  57588. __extends(ColorGradingTexture, _super);
  57589. /**
  57590. * Instantiates a ColorGradingTexture from the following parameters.
  57591. *
  57592. * @param url The location of the color gradind data (currently only supporting 3dl)
  57593. * @param scene The scene the texture will be used in
  57594. */
  57595. function ColorGradingTexture(url, scene) {
  57596. var _this = _super.call(this, scene) || this;
  57597. if (!url) {
  57598. return _this;
  57599. }
  57600. _this._textureMatrix = BABYLON.Matrix.Identity();
  57601. _this.name = url;
  57602. _this.url = url;
  57603. _this.hasAlpha = false;
  57604. _this.isCube = false;
  57605. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57606. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57607. _this.anisotropicFilteringLevel = 1;
  57608. _this._texture = _this._getFromCache(url, true);
  57609. if (!_this._texture) {
  57610. if (!scene.useDelayedTextureLoading) {
  57611. _this.loadTexture();
  57612. }
  57613. else {
  57614. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  57615. }
  57616. }
  57617. return _this;
  57618. }
  57619. /**
  57620. * Returns the texture matrix used in most of the material.
  57621. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  57622. */
  57623. ColorGradingTexture.prototype.getTextureMatrix = function () {
  57624. return this._textureMatrix;
  57625. };
  57626. /**
  57627. * Occurs when the file being loaded is a .3dl LUT file.
  57628. */
  57629. ColorGradingTexture.prototype.load3dlTexture = function () {
  57630. var _this = this;
  57631. var mipLevels = 0;
  57632. var floatArrayView = null;
  57633. var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  57634. this._texture = texture;
  57635. var callback = function (text) {
  57636. var data;
  57637. var tempData;
  57638. var line;
  57639. var lines = text.split('\n');
  57640. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  57641. var maxColor = 0;
  57642. for (var i = 0; i < lines.length; i++) {
  57643. line = lines[i];
  57644. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  57645. continue;
  57646. if (line.indexOf('#') === 0)
  57647. continue;
  57648. var words = line.split(" ");
  57649. if (size === 0) {
  57650. // Number of space + one
  57651. size = words.length;
  57652. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  57653. tempData = new Float32Array(size * size * size * 4);
  57654. continue;
  57655. }
  57656. if (size != 0) {
  57657. var r = Math.max(parseInt(words[0]), 0);
  57658. var g = Math.max(parseInt(words[1]), 0);
  57659. var b = Math.max(parseInt(words[2]), 0);
  57660. maxColor = Math.max(r, maxColor);
  57661. maxColor = Math.max(g, maxColor);
  57662. maxColor = Math.max(b, maxColor);
  57663. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  57664. tempData[pixelStorageIndex + 0] = r;
  57665. tempData[pixelStorageIndex + 1] = g;
  57666. tempData[pixelStorageIndex + 2] = b;
  57667. tempData[pixelStorageIndex + 3] = 0;
  57668. pixelIndexSlice++;
  57669. if (pixelIndexSlice % size == 0) {
  57670. pixelIndexH++;
  57671. pixelIndexSlice = 0;
  57672. if (pixelIndexH % size == 0) {
  57673. pixelIndexW++;
  57674. pixelIndexH = 0;
  57675. }
  57676. }
  57677. }
  57678. }
  57679. for (var i = 0; i < tempData.length; i++) {
  57680. var value = tempData[i];
  57681. data[i] = (value / maxColor * 255);
  57682. }
  57683. _this.getScene().getEngine().updateTextureSize(texture, size * size, size);
  57684. _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  57685. };
  57686. BABYLON.Tools.LoadFile(this.url, callback);
  57687. return this._texture;
  57688. };
  57689. /**
  57690. * Starts the loading process of the texture.
  57691. */
  57692. ColorGradingTexture.prototype.loadTexture = function () {
  57693. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  57694. this.load3dlTexture();
  57695. }
  57696. };
  57697. /**
  57698. * Clones the color gradind texture.
  57699. */
  57700. ColorGradingTexture.prototype.clone = function () {
  57701. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  57702. // Base texture
  57703. newTexture.level = this.level;
  57704. return newTexture;
  57705. };
  57706. /**
  57707. * Called during delayed load for textures.
  57708. */
  57709. ColorGradingTexture.prototype.delayLoad = function () {
  57710. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  57711. return;
  57712. }
  57713. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  57714. this._texture = this._getFromCache(this.url, true);
  57715. if (!this._texture) {
  57716. this.loadTexture();
  57717. }
  57718. };
  57719. /**
  57720. * Binds the color grading to the shader.
  57721. * @param colorGrading The texture to bind
  57722. * @param effect The effect to bind to
  57723. */
  57724. ColorGradingTexture.Bind = function (colorGrading, effect) {
  57725. effect.setTexture("cameraColorGrading2DSampler", colorGrading);
  57726. var x = colorGrading.level; // Texture Level
  57727. var y = colorGrading.getSize().height; // Texture Size example with 8
  57728. var z = y - 1.0; // SizeMinusOne 8 - 1
  57729. var w = 1 / y; // Space of 1 slice 1 / 8
  57730. effect.setFloat4("vCameraColorGradingInfos", x, y, z, w);
  57731. var slicePixelSizeU = w / y; // Space of 1 pixel in U direction, e.g. 1/64
  57732. 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
  57733. 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
  57734. 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
  57735. var z2 = 0.5 * slicePixelSizeU; // Offset of lookup range in U to align sample position with texel centre, for example 0.5/64
  57736. var w2 = 0.5 * slicePixelSizeV; // Offset of lookup range in V to align sample position with texel centre, for example 0.5/8
  57737. effect.setFloat4("vCameraColorGradingScaleOffset", x2, y2, z2, w2);
  57738. };
  57739. /**
  57740. * Prepare the list of uniforms associated with the ColorGrading effects.
  57741. * @param uniformsList The list of uniforms used in the effect
  57742. * @param samplersList The list of samplers used in the effect
  57743. */
  57744. ColorGradingTexture.PrepareUniformsAndSamplers = function (uniformsList, samplersList) {
  57745. uniformsList.push("vCameraColorGradingInfos", "vCameraColorGradingScaleOffset");
  57746. samplersList.push("cameraColorGrading2DSampler");
  57747. };
  57748. /**
  57749. * Parses a color grading texture serialized by Babylon.
  57750. * @param parsedTexture The texture information being parsedTexture
  57751. * @param scene The scene to load the texture in
  57752. * @param rootUrl The root url of the data assets to load
  57753. * @return A color gradind texture
  57754. */
  57755. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  57756. var texture = null;
  57757. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  57758. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  57759. texture.name = parsedTexture.name;
  57760. texture.level = parsedTexture.level;
  57761. }
  57762. return texture;
  57763. };
  57764. /**
  57765. * Serializes the LUT texture to json format.
  57766. */
  57767. ColorGradingTexture.prototype.serialize = function () {
  57768. if (!this.name) {
  57769. return null;
  57770. }
  57771. var serializationObject = {};
  57772. serializationObject.name = this.name;
  57773. serializationObject.level = this.level;
  57774. serializationObject.customType = "BABYLON.ColorGradingTexture";
  57775. return serializationObject;
  57776. };
  57777. return ColorGradingTexture;
  57778. }(BABYLON.BaseTexture));
  57779. /**
  57780. * Empty line regex stored for GC.
  57781. */
  57782. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  57783. BABYLON.ColorGradingTexture = ColorGradingTexture;
  57784. })(BABYLON || (BABYLON = {}));
  57785. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  57786. var BABYLON;
  57787. (function (BABYLON) {
  57788. /**
  57789. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  57790. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  57791. * 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;
  57792. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  57793. */
  57794. var ColorCurves = (function () {
  57795. function ColorCurves() {
  57796. this._dirty = true;
  57797. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  57798. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  57799. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  57800. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  57801. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  57802. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  57803. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  57804. this._globalHue = 30;
  57805. this._globalDensity = 0;
  57806. this._globalSaturation = 0;
  57807. this._globalExposure = 0;
  57808. this._highlightsHue = 30;
  57809. this._highlightsDensity = 0;
  57810. this._highlightsSaturation = 0;
  57811. this._highlightsExposure = 0;
  57812. this._midtonesHue = 30;
  57813. this._midtonesDensity = 0;
  57814. this._midtonesSaturation = 0;
  57815. this._midtonesExposure = 0;
  57816. this._shadowsHue = 30;
  57817. this._shadowsDensity = 0;
  57818. this._shadowsSaturation = 0;
  57819. this._shadowsExposure = 0;
  57820. }
  57821. Object.defineProperty(ColorCurves.prototype, "GlobalHue", {
  57822. /**
  57823. * Gets the global Hue value.
  57824. * 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).
  57825. */
  57826. get: function () {
  57827. return this._globalHue;
  57828. },
  57829. /**
  57830. * Sets the global Hue value.
  57831. * 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).
  57832. */
  57833. set: function (value) {
  57834. this._globalHue = value;
  57835. this._dirty = true;
  57836. },
  57837. enumerable: true,
  57838. configurable: true
  57839. });
  57840. Object.defineProperty(ColorCurves.prototype, "GlobalDensity", {
  57841. /**
  57842. * Gets the global Density value.
  57843. * 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.
  57844. * Values less than zero provide a filter of opposite hue.
  57845. */
  57846. get: function () {
  57847. return this._globalDensity;
  57848. },
  57849. /**
  57850. * Sets the global Density value.
  57851. * 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.
  57852. * Values less than zero provide a filter of opposite hue.
  57853. */
  57854. set: function (value) {
  57855. this._globalDensity = value;
  57856. this._dirty = true;
  57857. },
  57858. enumerable: true,
  57859. configurable: true
  57860. });
  57861. Object.defineProperty(ColorCurves.prototype, "GlobalSaturation", {
  57862. /**
  57863. * Gets the global Saturation value.
  57864. * 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.
  57865. */
  57866. get: function () {
  57867. return this._globalSaturation;
  57868. },
  57869. /**
  57870. * Sets the global Saturation value.
  57871. * 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.
  57872. */
  57873. set: function (value) {
  57874. this._globalSaturation = value;
  57875. this._dirty = true;
  57876. },
  57877. enumerable: true,
  57878. configurable: true
  57879. });
  57880. Object.defineProperty(ColorCurves.prototype, "HighlightsHue", {
  57881. /**
  57882. * Gets the highlights Hue value.
  57883. * 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).
  57884. */
  57885. get: function () {
  57886. return this._highlightsHue;
  57887. },
  57888. /**
  57889. * Sets the highlights Hue value.
  57890. * 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).
  57891. */
  57892. set: function (value) {
  57893. this._highlightsHue = value;
  57894. this._dirty = true;
  57895. },
  57896. enumerable: true,
  57897. configurable: true
  57898. });
  57899. Object.defineProperty(ColorCurves.prototype, "HighlightsDensity", {
  57900. /**
  57901. * Gets the highlights Density value.
  57902. * 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.
  57903. * Values less than zero provide a filter of opposite hue.
  57904. */
  57905. get: function () {
  57906. return this._highlightsDensity;
  57907. },
  57908. /**
  57909. * Sets the highlights Density value.
  57910. * 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.
  57911. * Values less than zero provide a filter of opposite hue.
  57912. */
  57913. set: function (value) {
  57914. this._highlightsDensity = value;
  57915. this._dirty = true;
  57916. },
  57917. enumerable: true,
  57918. configurable: true
  57919. });
  57920. Object.defineProperty(ColorCurves.prototype, "HighlightsSaturation", {
  57921. /**
  57922. * Gets the highlights Saturation value.
  57923. * 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.
  57924. */
  57925. get: function () {
  57926. return this._highlightsSaturation;
  57927. },
  57928. /**
  57929. * Sets the highlights Saturation value.
  57930. * 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.
  57931. */
  57932. set: function (value) {
  57933. this._highlightsSaturation = value;
  57934. this._dirty = true;
  57935. },
  57936. enumerable: true,
  57937. configurable: true
  57938. });
  57939. Object.defineProperty(ColorCurves.prototype, "HighlightsExposure", {
  57940. /**
  57941. * Gets the highlights Exposure value.
  57942. * 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.
  57943. */
  57944. get: function () {
  57945. return this._highlightsExposure;
  57946. },
  57947. /**
  57948. * Sets the highlights Exposure value.
  57949. * 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.
  57950. */
  57951. set: function (value) {
  57952. this._highlightsExposure = value;
  57953. this._dirty = true;
  57954. },
  57955. enumerable: true,
  57956. configurable: true
  57957. });
  57958. Object.defineProperty(ColorCurves.prototype, "MidtonesHue", {
  57959. /**
  57960. * Gets the midtones Hue value.
  57961. * 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).
  57962. */
  57963. get: function () {
  57964. return this._midtonesHue;
  57965. },
  57966. /**
  57967. * Sets the midtones Hue value.
  57968. * 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).
  57969. */
  57970. set: function (value) {
  57971. this._midtonesHue = value;
  57972. this._dirty = true;
  57973. },
  57974. enumerable: true,
  57975. configurable: true
  57976. });
  57977. Object.defineProperty(ColorCurves.prototype, "MidtonesDensity", {
  57978. /**
  57979. * Gets the midtones Density value.
  57980. * 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.
  57981. * Values less than zero provide a filter of opposite hue.
  57982. */
  57983. get: function () {
  57984. return this._midtonesDensity;
  57985. },
  57986. /**
  57987. * Sets the midtones Density value.
  57988. * 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.
  57989. * Values less than zero provide a filter of opposite hue.
  57990. */
  57991. set: function (value) {
  57992. this._midtonesDensity = value;
  57993. this._dirty = true;
  57994. },
  57995. enumerable: true,
  57996. configurable: true
  57997. });
  57998. Object.defineProperty(ColorCurves.prototype, "MidtonesSaturation", {
  57999. /**
  58000. * Gets the midtones Saturation value.
  58001. * 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.
  58002. */
  58003. get: function () {
  58004. return this._midtonesSaturation;
  58005. },
  58006. /**
  58007. * Sets the midtones Saturation value.
  58008. * 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.
  58009. */
  58010. set: function (value) {
  58011. this._midtonesSaturation = value;
  58012. this._dirty = true;
  58013. },
  58014. enumerable: true,
  58015. configurable: true
  58016. });
  58017. Object.defineProperty(ColorCurves.prototype, "MidtonesExposure", {
  58018. /**
  58019. * Gets the midtones Exposure value.
  58020. * 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.
  58021. */
  58022. get: function () {
  58023. return this._midtonesExposure;
  58024. },
  58025. /**
  58026. * Sets the midtones Exposure value.
  58027. * 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.
  58028. */
  58029. set: function (value) {
  58030. this._midtonesExposure = value;
  58031. this._dirty = true;
  58032. },
  58033. enumerable: true,
  58034. configurable: true
  58035. });
  58036. Object.defineProperty(ColorCurves.prototype, "ShadowsHue", {
  58037. /**
  58038. * Gets the shadows Hue value.
  58039. * 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).
  58040. */
  58041. get: function () {
  58042. return this._shadowsHue;
  58043. },
  58044. /**
  58045. * Sets the shadows Hue value.
  58046. * 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).
  58047. */
  58048. set: function (value) {
  58049. this._shadowsHue = value;
  58050. this._dirty = true;
  58051. },
  58052. enumerable: true,
  58053. configurable: true
  58054. });
  58055. Object.defineProperty(ColorCurves.prototype, "ShadowsDensity", {
  58056. /**
  58057. * Gets the shadows Density value.
  58058. * 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.
  58059. * Values less than zero provide a filter of opposite hue.
  58060. */
  58061. get: function () {
  58062. return this._shadowsDensity;
  58063. },
  58064. /**
  58065. * Sets the shadows Density value.
  58066. * 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.
  58067. * Values less than zero provide a filter of opposite hue.
  58068. */
  58069. set: function (value) {
  58070. this._shadowsDensity = value;
  58071. this._dirty = true;
  58072. },
  58073. enumerable: true,
  58074. configurable: true
  58075. });
  58076. Object.defineProperty(ColorCurves.prototype, "ShadowsSaturation", {
  58077. /**
  58078. * Gets the shadows Saturation value.
  58079. * 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.
  58080. */
  58081. get: function () {
  58082. return this._shadowsSaturation;
  58083. },
  58084. /**
  58085. * Sets the shadows Saturation value.
  58086. * 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.
  58087. */
  58088. set: function (value) {
  58089. this._shadowsSaturation = value;
  58090. this._dirty = true;
  58091. },
  58092. enumerable: true,
  58093. configurable: true
  58094. });
  58095. Object.defineProperty(ColorCurves.prototype, "ShadowsExposure", {
  58096. /**
  58097. * Gets the shadows Exposure value.
  58098. * 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.
  58099. */
  58100. get: function () {
  58101. return this._shadowsExposure;
  58102. },
  58103. /**
  58104. * Sets the shadows Exposure value.
  58105. * 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.
  58106. */
  58107. set: function (value) {
  58108. this._shadowsExposure = value;
  58109. this._dirty = true;
  58110. },
  58111. enumerable: true,
  58112. configurable: true
  58113. });
  58114. /**
  58115. * Binds the color curves to the shader.
  58116. * @param colorCurves The color curve to bind
  58117. * @param effect The effect to bind to
  58118. */
  58119. ColorCurves.Bind = function (colorCurves, effect) {
  58120. if (colorCurves._dirty) {
  58121. colorCurves._dirty = false;
  58122. // Fill in global info.
  58123. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  58124. // Compute highlights info.
  58125. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  58126. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  58127. // Compute midtones info.
  58128. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  58129. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  58130. // Compute shadows info.
  58131. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  58132. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  58133. // Compute deltas (neutral is midtones).
  58134. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  58135. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  58136. }
  58137. effect.setFloat4("vCameraColorCurvePositive", colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  58138. effect.setFloat4("vCameraColorCurveNeutral", colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  58139. effect.setFloat4("vCameraColorCurveNegative", colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  58140. };
  58141. /**
  58142. * Prepare the list of uniforms associated with the ColorCurves effects.
  58143. * @param uniformsList The list of uniforms used in the effect
  58144. */
  58145. ColorCurves.PrepareUniforms = function (uniformsList) {
  58146. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  58147. };
  58148. /**
  58149. * Returns color grading data based on a hue, density, saturation and exposure value.
  58150. * @param filterHue The hue of the color filter.
  58151. * @param filterDensity The density of the color filter.
  58152. * @param saturation The saturation.
  58153. * @param exposure The exposure.
  58154. * @param result The result data container.
  58155. */
  58156. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  58157. if (hue == null) {
  58158. return;
  58159. }
  58160. hue = ColorCurves.clamp(hue, 0, 360);
  58161. density = ColorCurves.clamp(density, -100, 100);
  58162. saturation = ColorCurves.clamp(saturation, -100, 100);
  58163. exposure = ColorCurves.clamp(exposure, -100, 100);
  58164. // Remap the slider/config filter density with non-linear mapping and also scale by half
  58165. // so that the maximum filter density is only 50% control. This provides fine control
  58166. // for small values and reasonable range.
  58167. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  58168. density *= 0.5;
  58169. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  58170. if (density < 0) {
  58171. density *= -1;
  58172. hue = (hue + 180) % 360;
  58173. }
  58174. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  58175. result.scaleToRef(2, result);
  58176. result.a = 1 + 0.01 * saturation;
  58177. };
  58178. /**
  58179. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  58180. * @param value The input slider value in range [-100,100].
  58181. * @returns Adjusted value.
  58182. */
  58183. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  58184. value /= 100;
  58185. var x = Math.abs(value);
  58186. x = Math.pow(x, 2);
  58187. if (value < 0) {
  58188. x *= -1;
  58189. }
  58190. x *= 100;
  58191. return x;
  58192. };
  58193. /**
  58194. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  58195. * @param hue The hue (H) input.
  58196. * @param saturation The saturation (S) input.
  58197. * @param brightness The brightness (B) input.
  58198. * @result An RGBA color represented as Vector4.
  58199. */
  58200. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  58201. var h = ColorCurves.clamp(hue, 0, 360);
  58202. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  58203. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  58204. if (s === 0) {
  58205. result.r = v;
  58206. result.g = v;
  58207. result.b = v;
  58208. }
  58209. else {
  58210. // sector 0 to 5
  58211. h /= 60;
  58212. var i = Math.floor(h);
  58213. // fractional part of h
  58214. var f = h - i;
  58215. var p = v * (1 - s);
  58216. var q = v * (1 - s * f);
  58217. var t = v * (1 - s * (1 - f));
  58218. switch (i) {
  58219. case 0:
  58220. result.r = v;
  58221. result.g = t;
  58222. result.b = p;
  58223. break;
  58224. case 1:
  58225. result.r = q;
  58226. result.g = v;
  58227. result.b = p;
  58228. break;
  58229. case 2:
  58230. result.r = p;
  58231. result.g = v;
  58232. result.b = t;
  58233. break;
  58234. case 3:
  58235. result.r = p;
  58236. result.g = q;
  58237. result.b = v;
  58238. break;
  58239. case 4:
  58240. result.r = t;
  58241. result.g = p;
  58242. result.b = v;
  58243. break;
  58244. default:
  58245. result.r = v;
  58246. result.g = p;
  58247. result.b = q;
  58248. break;
  58249. }
  58250. }
  58251. result.a = 1;
  58252. };
  58253. /**
  58254. * Returns a value clamped between min and max
  58255. * @param value The value to clamp
  58256. * @param min The minimum of value
  58257. * @param max The maximum of value
  58258. * @returns The clamped value.
  58259. */
  58260. ColorCurves.clamp = function (value, min, max) {
  58261. return Math.min(Math.max(value, min), max);
  58262. };
  58263. /**
  58264. * Clones the current color curve instance.
  58265. * @return The cloned curves
  58266. */
  58267. ColorCurves.prototype.clone = function () {
  58268. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  58269. };
  58270. /**
  58271. * Serializes the current color curve instance to a json representation.
  58272. * @return a JSON representation
  58273. */
  58274. ColorCurves.prototype.serialize = function () {
  58275. return BABYLON.SerializationHelper.Serialize(this);
  58276. };
  58277. /**
  58278. * Parses the color curve from a json representation.
  58279. * @param source the JSON source to parse
  58280. * @return The parsed curves
  58281. */
  58282. ColorCurves.Parse = function (source) {
  58283. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  58284. };
  58285. return ColorCurves;
  58286. }());
  58287. __decorate([
  58288. BABYLON.serialize()
  58289. ], ColorCurves.prototype, "_globalHue", void 0);
  58290. __decorate([
  58291. BABYLON.serialize()
  58292. ], ColorCurves.prototype, "_globalDensity", void 0);
  58293. __decorate([
  58294. BABYLON.serialize()
  58295. ], ColorCurves.prototype, "_globalSaturation", void 0);
  58296. __decorate([
  58297. BABYLON.serialize()
  58298. ], ColorCurves.prototype, "_globalExposure", void 0);
  58299. __decorate([
  58300. BABYLON.serialize()
  58301. ], ColorCurves.prototype, "_highlightsHue", void 0);
  58302. __decorate([
  58303. BABYLON.serialize()
  58304. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  58305. __decorate([
  58306. BABYLON.serialize()
  58307. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  58308. __decorate([
  58309. BABYLON.serialize()
  58310. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  58311. __decorate([
  58312. BABYLON.serialize()
  58313. ], ColorCurves.prototype, "_midtonesHue", void 0);
  58314. __decorate([
  58315. BABYLON.serialize()
  58316. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  58317. __decorate([
  58318. BABYLON.serialize()
  58319. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  58320. __decorate([
  58321. BABYLON.serialize()
  58322. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  58323. BABYLON.ColorCurves = ColorCurves;
  58324. })(BABYLON || (BABYLON = {}));
  58325. //# sourceMappingURL=babylon.colorCurves.js.map
  58326. var BABYLON;
  58327. (function (BABYLON) {
  58328. var Octree = (function () {
  58329. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  58330. if (maxDepth === void 0) { maxDepth = 2; }
  58331. this.maxDepth = maxDepth;
  58332. this.dynamicContent = new Array();
  58333. this._maxBlockCapacity = maxBlockCapacity || 64;
  58334. this._selectionContent = new BABYLON.SmartArray(1024);
  58335. this._creationFunc = creationFunc;
  58336. }
  58337. // Methods
  58338. Octree.prototype.update = function (worldMin, worldMax, entries) {
  58339. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  58340. };
  58341. Octree.prototype.addMesh = function (entry) {
  58342. for (var index = 0; index < this.blocks.length; index++) {
  58343. var block = this.blocks[index];
  58344. block.addEntry(entry);
  58345. }
  58346. };
  58347. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  58348. this._selectionContent.reset();
  58349. for (var index = 0; index < this.blocks.length; index++) {
  58350. var block = this.blocks[index];
  58351. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  58352. }
  58353. if (allowDuplicate) {
  58354. this._selectionContent.concat(this.dynamicContent);
  58355. }
  58356. else {
  58357. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  58358. }
  58359. return this._selectionContent;
  58360. };
  58361. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  58362. this._selectionContent.reset();
  58363. for (var index = 0; index < this.blocks.length; index++) {
  58364. var block = this.blocks[index];
  58365. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  58366. }
  58367. if (allowDuplicate) {
  58368. this._selectionContent.concat(this.dynamicContent);
  58369. }
  58370. else {
  58371. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  58372. }
  58373. return this._selectionContent;
  58374. };
  58375. Octree.prototype.intersectsRay = function (ray) {
  58376. this._selectionContent.reset();
  58377. for (var index = 0; index < this.blocks.length; index++) {
  58378. var block = this.blocks[index];
  58379. block.intersectsRay(ray, this._selectionContent);
  58380. }
  58381. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  58382. return this._selectionContent;
  58383. };
  58384. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  58385. target.blocks = new Array();
  58386. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  58387. // Segmenting space
  58388. for (var x = 0; x < 2; x++) {
  58389. for (var y = 0; y < 2; y++) {
  58390. for (var z = 0; z < 2; z++) {
  58391. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  58392. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  58393. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  58394. block.addEntries(entries);
  58395. target.blocks.push(block);
  58396. }
  58397. }
  58398. }
  58399. };
  58400. return Octree;
  58401. }());
  58402. Octree.CreationFuncForMeshes = function (entry, block) {
  58403. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  58404. block.entries.push(entry);
  58405. }
  58406. };
  58407. Octree.CreationFuncForSubMeshes = function (entry, block) {
  58408. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  58409. block.entries.push(entry);
  58410. }
  58411. };
  58412. BABYLON.Octree = Octree;
  58413. })(BABYLON || (BABYLON = {}));
  58414. //# sourceMappingURL=babylon.octree.js.map
  58415. var BABYLON;
  58416. (function (BABYLON) {
  58417. var OctreeBlock = (function () {
  58418. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  58419. this.entries = new Array();
  58420. this._boundingVectors = new Array();
  58421. this._capacity = capacity;
  58422. this._depth = depth;
  58423. this._maxDepth = maxDepth;
  58424. this._creationFunc = creationFunc;
  58425. this._minPoint = minPoint;
  58426. this._maxPoint = maxPoint;
  58427. this._boundingVectors.push(minPoint.clone());
  58428. this._boundingVectors.push(maxPoint.clone());
  58429. this._boundingVectors.push(minPoint.clone());
  58430. this._boundingVectors[2].x = maxPoint.x;
  58431. this._boundingVectors.push(minPoint.clone());
  58432. this._boundingVectors[3].y = maxPoint.y;
  58433. this._boundingVectors.push(minPoint.clone());
  58434. this._boundingVectors[4].z = maxPoint.z;
  58435. this._boundingVectors.push(maxPoint.clone());
  58436. this._boundingVectors[5].z = minPoint.z;
  58437. this._boundingVectors.push(maxPoint.clone());
  58438. this._boundingVectors[6].x = minPoint.x;
  58439. this._boundingVectors.push(maxPoint.clone());
  58440. this._boundingVectors[7].y = minPoint.y;
  58441. }
  58442. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  58443. // Property
  58444. get: function () {
  58445. return this._capacity;
  58446. },
  58447. enumerable: true,
  58448. configurable: true
  58449. });
  58450. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  58451. get: function () {
  58452. return this._minPoint;
  58453. },
  58454. enumerable: true,
  58455. configurable: true
  58456. });
  58457. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  58458. get: function () {
  58459. return this._maxPoint;
  58460. },
  58461. enumerable: true,
  58462. configurable: true
  58463. });
  58464. // Methods
  58465. OctreeBlock.prototype.addEntry = function (entry) {
  58466. if (this.blocks) {
  58467. for (var index = 0; index < this.blocks.length; index++) {
  58468. var block = this.blocks[index];
  58469. block.addEntry(entry);
  58470. }
  58471. return;
  58472. }
  58473. this._creationFunc(entry, this);
  58474. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  58475. this.createInnerBlocks();
  58476. }
  58477. };
  58478. OctreeBlock.prototype.addEntries = function (entries) {
  58479. for (var index = 0; index < entries.length; index++) {
  58480. var mesh = entries[index];
  58481. this.addEntry(mesh);
  58482. }
  58483. };
  58484. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  58485. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  58486. if (this.blocks) {
  58487. for (var index = 0; index < this.blocks.length; index++) {
  58488. var block = this.blocks[index];
  58489. block.select(frustumPlanes, selection, allowDuplicate);
  58490. }
  58491. return;
  58492. }
  58493. if (allowDuplicate) {
  58494. selection.concat(this.entries);
  58495. }
  58496. else {
  58497. selection.concatWithNoDuplicate(this.entries);
  58498. }
  58499. }
  58500. };
  58501. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  58502. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  58503. if (this.blocks) {
  58504. for (var index = 0; index < this.blocks.length; index++) {
  58505. var block = this.blocks[index];
  58506. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  58507. }
  58508. return;
  58509. }
  58510. if (allowDuplicate) {
  58511. selection.concat(this.entries);
  58512. }
  58513. else {
  58514. selection.concatWithNoDuplicate(this.entries);
  58515. }
  58516. }
  58517. };
  58518. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  58519. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  58520. if (this.blocks) {
  58521. for (var index = 0; index < this.blocks.length; index++) {
  58522. var block = this.blocks[index];
  58523. block.intersectsRay(ray, selection);
  58524. }
  58525. return;
  58526. }
  58527. selection.concatWithNoDuplicate(this.entries);
  58528. }
  58529. };
  58530. OctreeBlock.prototype.createInnerBlocks = function () {
  58531. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  58532. };
  58533. return OctreeBlock;
  58534. }());
  58535. BABYLON.OctreeBlock = OctreeBlock;
  58536. })(BABYLON || (BABYLON = {}));
  58537. //# sourceMappingURL=babylon.octreeBlock.js.map
  58538. var BABYLON;
  58539. (function (BABYLON) {
  58540. var SIMDVector3 = (function () {
  58541. function SIMDVector3() {
  58542. }
  58543. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  58544. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD(vector.x, vector.y, vector.z, transformation, result);
  58545. };
  58546. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  58547. var m = transformation.m;
  58548. var m0 = SIMD.Float32x4.load(m, 0);
  58549. var m1 = SIMD.Float32x4.load(m, 4);
  58550. var m2 = SIMD.Float32x4.load(m, 8);
  58551. var m3 = SIMD.Float32x4.load(m, 12);
  58552. 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));
  58553. r = SIMD.Float32x4.div(r, SIMD.Float32x4.swizzle(r, 3, 3, 3, 3));
  58554. result.x = SIMD.Float32x4.extractLane(r, 0);
  58555. result.y = SIMD.Float32x4.extractLane(r, 1);
  58556. result.z = SIMD.Float32x4.extractLane(r, 2);
  58557. };
  58558. return SIMDVector3;
  58559. }());
  58560. var SIMDMatrix = (function () {
  58561. function SIMDMatrix() {
  58562. }
  58563. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  58564. var tm = this.m;
  58565. var om = other.m;
  58566. var m0 = SIMD.Float32x4.load(om, 0);
  58567. var m1 = SIMD.Float32x4.load(om, 4);
  58568. var m2 = SIMD.Float32x4.load(om, 8);
  58569. var m3 = SIMD.Float32x4.load(om, 12);
  58570. for (var i = 0; i < 16; i += 4) {
  58571. 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)))));
  58572. }
  58573. return this;
  58574. };
  58575. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  58576. var src = this.m;
  58577. var dest = other.m;
  58578. // Load the 4 rows
  58579. var src0 = SIMD.Float32x4.load(src, 0);
  58580. var src1 = SIMD.Float32x4.load(src, 4);
  58581. var src2 = SIMD.Float32x4.load(src, 8);
  58582. var src3 = SIMD.Float32x4.load(src, 12);
  58583. // Transpose the source matrix. Sort of. Not a true transpose operation
  58584. var tmp1 = SIMD.Float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  58585. var row1 = SIMD.Float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  58586. var row0 = SIMD.Float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  58587. row1 = SIMD.Float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  58588. tmp1 = SIMD.Float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  58589. var row3 = SIMD.Float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  58590. var row2 = SIMD.Float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  58591. row3 = SIMD.Float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  58592. // This is a true transposition, but it will lead to an incorrect result
  58593. //tmp1 = shuffle(src0, src1, 0, 1, 4, 5);
  58594. //tmp2 = shuffle(src2, src3, 0, 1, 4, 5);
  58595. //row0 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  58596. //row1 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  58597. //tmp1 = shuffle(src0, src1, 2, 3, 6, 7);
  58598. //tmp2 = shuffle(src2, src3, 2, 3, 6, 7);
  58599. //row2 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  58600. //row3 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  58601. // ----
  58602. tmp1 = SIMD.Float32x4.mul(row2, row3);
  58603. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  58604. var minor0 = SIMD.Float32x4.mul(row1, tmp1);
  58605. var minor1 = SIMD.Float32x4.mul(row0, tmp1);
  58606. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  58607. minor0 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row1, tmp1), minor0);
  58608. minor1 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor1);
  58609. minor1 = SIMD.Float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  58610. // ----
  58611. tmp1 = SIMD.Float32x4.mul(row1, row2);
  58612. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  58613. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor0);
  58614. var minor3 = SIMD.Float32x4.mul(row0, tmp1);
  58615. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  58616. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row3, tmp1));
  58617. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor3);
  58618. minor3 = SIMD.Float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  58619. // ----
  58620. tmp1 = SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  58621. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  58622. row2 = SIMD.Float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  58623. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor0);
  58624. var minor2 = SIMD.Float32x4.mul(row0, tmp1);
  58625. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  58626. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row2, tmp1));
  58627. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor2);
  58628. minor2 = SIMD.Float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  58629. // ----
  58630. tmp1 = SIMD.Float32x4.mul(row0, row1);
  58631. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  58632. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor2);
  58633. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row2, tmp1), minor3);
  58634. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  58635. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row3, tmp1), minor2);
  58636. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row2, tmp1));
  58637. // ----
  58638. tmp1 = SIMD.Float32x4.mul(row0, row3);
  58639. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  58640. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row2, tmp1));
  58641. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor2);
  58642. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  58643. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor1);
  58644. minor2 = SIMD.Float32x4.sub(minor2, SIMD.Float32x4.mul(row1, tmp1));
  58645. // ----
  58646. tmp1 = SIMD.Float32x4.mul(row0, row2);
  58647. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  58648. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor1);
  58649. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row1, tmp1));
  58650. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  58651. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row3, tmp1));
  58652. minor3 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor3);
  58653. // Compute determinant
  58654. var det = SIMD.Float32x4.mul(row0, minor0);
  58655. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  58656. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  58657. tmp1 = SIMD.Float32x4.reciprocalApproximation(det);
  58658. det = SIMD.Float32x4.sub(SIMD.Float32x4.add(tmp1, tmp1), SIMD.Float32x4.mul(det, SIMD.Float32x4.mul(tmp1, tmp1)));
  58659. det = SIMD.Float32x4.swizzle(det, 0, 0, 0, 0);
  58660. // These shuffles aren't necessary if the faulty transposition is done
  58661. // up at the top of this function.
  58662. //minor0 =SIMD.Float32x4.swizzle(minor0, 2, 1, 0, 3);
  58663. //minor1 =SIMD.Float32x4.swizzle(minor1, 2, 1, 0, 3);
  58664. //minor2 =SIMD.Float32x4.swizzle(minor2, 2, 1, 0, 3);
  58665. //minor3 =SIMD.Float32x4.swizzle(minor3, 2, 1, 0, 3);
  58666. // Compute final values by multiplying with 1/det
  58667. SIMD.Float32x4.store(dest, 0, SIMD.Float32x4.mul(det, minor0));
  58668. SIMD.Float32x4.store(dest, 4, SIMD.Float32x4.mul(det, minor1));
  58669. SIMD.Float32x4.store(dest, 8, minor2 = SIMD.Float32x4.mul(det, minor2));
  58670. SIMD.Float32x4.store(dest, 12, SIMD.Float32x4.mul(det, minor3));
  58671. return this;
  58672. };
  58673. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  58674. var out = result.m;
  58675. var center = SIMD.Float32x4(targetRef.x, targetRef.y, targetRef.z, 0.0);
  58676. var eye = SIMD.Float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0.0);
  58677. var up = SIMD.Float32x4(upRef.x, upRef.y, upRef.z, 0.0);
  58678. // cc.kmVec3Subtract(f, pCenter, pEye);
  58679. var f = SIMD.Float32x4.sub(center, eye);
  58680. // cc.kmVec3Normalize(f, f);
  58681. var tmp = SIMD.Float32x4.mul(f, f);
  58682. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  58683. f = SIMD.Float32x4.mul(f, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  58684. // cc.kmVec3Assign(up, pUp);
  58685. // cc.kmVec3Normalize(up, up);
  58686. tmp = SIMD.Float32x4.mul(up, up);
  58687. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  58688. up = SIMD.Float32x4.mul(up, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  58689. // cc.kmVec3Cross(s, f, up);
  58690. 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)));
  58691. // cc.kmVec3Normalize(s, s);
  58692. tmp = SIMD.Float32x4.mul(s, s);
  58693. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  58694. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  58695. // cc.kmVec3Cross(u, s, f);
  58696. 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)));
  58697. // cc.kmVec3Normalize(s, s);
  58698. tmp = SIMD.Float32x4.mul(s, s);
  58699. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  58700. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  58701. var zero = SIMD.Float32x4.splat(0.0);
  58702. s = SIMD.Float32x4.neg(s);
  58703. var tmp01 = SIMD.Float32x4.shuffle(s, u, 0, 1, 4, 5);
  58704. var tmp23 = SIMD.Float32x4.shuffle(f, zero, 0, 1, 4, 5);
  58705. var a0 = SIMD.Float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  58706. var a1 = SIMD.Float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  58707. 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);
  58708. var a3 = SIMD.Float32x4(0.0, 0.0, 0.0, 1.0);
  58709. var b = SIMD.Float32x4(1.0, 0.0, 0.0, 0.0);
  58710. 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)))));
  58711. b = SIMD.Float32x4(0.0, 1.0, 0.0, 0.0);
  58712. 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)))));
  58713. b = SIMD.Float32x4(0.0, 0.0, 1.0, 0.0);
  58714. 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)))));
  58715. b = SIMD.Float32x4.replaceLane(SIMD.Float32x4.neg(eye), 3, 1.0);
  58716. 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)))));
  58717. };
  58718. return SIMDMatrix;
  58719. }());
  58720. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  58721. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  58722. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  58723. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  58724. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  58725. var SIMDHelper = (function () {
  58726. function SIMDHelper() {
  58727. }
  58728. Object.defineProperty(SIMDHelper, "IsEnabled", {
  58729. get: function () {
  58730. return SIMDHelper._isEnabled;
  58731. },
  58732. enumerable: true,
  58733. configurable: true
  58734. });
  58735. SIMDHelper.DisableSIMD = function () {
  58736. // Replace functions
  58737. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  58738. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  58739. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  58740. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  58741. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  58742. SIMDHelper._isEnabled = false;
  58743. };
  58744. SIMDHelper.EnableSIMD = function () {
  58745. if (self.SIMD === undefined) {
  58746. return;
  58747. }
  58748. // check if polyfills needed
  58749. if (!self.Math.fround) {
  58750. self.Math.fround = (function (array) { return function (x) {
  58751. return array[0] = x, array[0];
  58752. }; })(new Float32Array(1));
  58753. }
  58754. if (!self.Math.imul) {
  58755. self.Math.imul = function (a, b) {
  58756. var ah = (a >>> 16) & 0xffff;
  58757. var al = a & 0xffff;
  58758. var bh = (b >>> 16) & 0xffff;
  58759. var bl = b & 0xffff;
  58760. // the shift by 0 fixes the sign on the high part
  58761. // the final |0 converts the unsigned value into a signed value
  58762. return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);
  58763. };
  58764. }
  58765. // Replace functions
  58766. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  58767. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  58768. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  58769. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  58770. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  58771. SIMDHelper._isEnabled = true;
  58772. };
  58773. return SIMDHelper;
  58774. }());
  58775. SIMDHelper._isEnabled = false;
  58776. BABYLON.SIMDHelper = SIMDHelper;
  58777. })(BABYLON || (BABYLON = {}));
  58778. //# sourceMappingURL=babylon.math.SIMD.js.map
  58779. var BABYLON;
  58780. (function (BABYLON) {
  58781. var VRDistortionCorrectionPostProcess = (function (_super) {
  58782. __extends(VRDistortionCorrectionPostProcess, _super);
  58783. //ANY
  58784. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  58785. var _this = _super.call(this, name, "vrDistortionCorrection", [
  58786. 'LensCenter',
  58787. 'Scale',
  58788. 'ScaleIn',
  58789. 'HmdWarpParam'
  58790. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null) || this;
  58791. _this._isRightEye = isRightEye;
  58792. _this._distortionFactors = vrMetrics.distortionK;
  58793. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  58794. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  58795. _this.onSizeChangedObservable.add(function () {
  58796. _this.aspectRatio = _this.width * .5 / _this.height;
  58797. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  58798. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  58799. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  58800. });
  58801. _this.onApplyObservable.add(function (effect) {
  58802. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  58803. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  58804. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  58805. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  58806. });
  58807. return _this;
  58808. }
  58809. return VRDistortionCorrectionPostProcess;
  58810. }(BABYLON.PostProcess));
  58811. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  58812. })(BABYLON || (BABYLON = {}));
  58813. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  58814. var BABYLON;
  58815. (function (BABYLON) {
  58816. var AnaglyphPostProcess = (function (_super) {
  58817. __extends(AnaglyphPostProcess, _super);
  58818. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  58819. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  58820. _this._passedProcess = rigCameras[0]._rigPostProcess;
  58821. _this.onApplyObservable.add(function (effect) {
  58822. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  58823. });
  58824. return _this;
  58825. }
  58826. return AnaglyphPostProcess;
  58827. }(BABYLON.PostProcess));
  58828. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  58829. })(BABYLON || (BABYLON = {}));
  58830. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  58831. var BABYLON;
  58832. (function (BABYLON) {
  58833. var StereoscopicInterlacePostProcess = (function (_super) {
  58834. __extends(StereoscopicInterlacePostProcess, _super);
  58835. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  58836. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  58837. _this._passedProcess = rigCameras[0]._rigPostProcess;
  58838. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  58839. _this.onSizeChangedObservable.add(function () {
  58840. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  58841. });
  58842. _this.onApplyObservable.add(function (effect) {
  58843. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  58844. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  58845. });
  58846. return _this;
  58847. }
  58848. return StereoscopicInterlacePostProcess;
  58849. }(BABYLON.PostProcess));
  58850. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  58851. })(BABYLON || (BABYLON = {}));
  58852. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  58853. var BABYLON;
  58854. (function (BABYLON) {
  58855. var FreeCameraDeviceOrientationInput = (function () {
  58856. function FreeCameraDeviceOrientationInput() {
  58857. var _this = this;
  58858. this._screenOrientationAngle = 0;
  58859. this._screenQuaternion = new BABYLON.Quaternion();
  58860. this._alpha = 0;
  58861. this._beta = 0;
  58862. this._gamma = 0;
  58863. this._orientationChanged = function () {
  58864. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  58865. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  58866. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  58867. };
  58868. this._deviceOrientation = function (evt) {
  58869. _this._alpha = evt.alpha;
  58870. _this._beta = evt.beta;
  58871. _this._gamma = evt.gamma;
  58872. };
  58873. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  58874. this._orientationChanged();
  58875. }
  58876. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  58877. get: function () {
  58878. return this._camera;
  58879. },
  58880. set: function (camera) {
  58881. this._camera = camera;
  58882. if (!this._camera.rotationQuaternion)
  58883. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  58884. },
  58885. enumerable: true,
  58886. configurable: true
  58887. });
  58888. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  58889. window.addEventListener("orientationchange", this._orientationChanged);
  58890. window.addEventListener("deviceorientation", this._deviceOrientation);
  58891. //In certain cases, the attach control is called AFTER orientation was changed,
  58892. //So this is needed.
  58893. this._orientationChanged();
  58894. };
  58895. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  58896. window.removeEventListener("orientationchange", this._orientationChanged);
  58897. window.removeEventListener("deviceorientation", this._deviceOrientation);
  58898. };
  58899. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  58900. //if no device orientation provided, don't update the rotation.
  58901. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  58902. if (!this._alpha)
  58903. return;
  58904. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  58905. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  58906. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  58907. //Mirror on XY Plane
  58908. this._camera.rotationQuaternion.z *= -1;
  58909. this._camera.rotationQuaternion.w *= -1;
  58910. };
  58911. FreeCameraDeviceOrientationInput.prototype.getTypeName = function () {
  58912. return "FreeCameraDeviceOrientationInput";
  58913. };
  58914. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  58915. return "deviceOrientation";
  58916. };
  58917. return FreeCameraDeviceOrientationInput;
  58918. }());
  58919. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  58920. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  58921. })(BABYLON || (BABYLON = {}));
  58922. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  58923. var BABYLON;
  58924. (function (BABYLON) {
  58925. var ArcRotateCameraVRDeviceOrientationInput = (function () {
  58926. function ArcRotateCameraVRDeviceOrientationInput() {
  58927. this.alphaCorrection = 1;
  58928. this.betaCorrection = 1;
  58929. this.gammaCorrection = 1;
  58930. this._alpha = 0;
  58931. this._beta = 0;
  58932. this._gamma = 0;
  58933. this._dirty = false;
  58934. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  58935. }
  58936. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  58937. this.camera.attachControl(element, noPreventDefault);
  58938. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  58939. };
  58940. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  58941. var camera = this.camera;
  58942. this._alpha = +evt.alpha | 0;
  58943. this._beta = +evt.beta | 0;
  58944. this._gamma = +evt.gamma | 0;
  58945. this._dirty = true;
  58946. };
  58947. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  58948. if (this._dirty) {
  58949. this._dirty = false;
  58950. if (this._gamma < 0) {
  58951. this._gamma = 180 + this._gamma;
  58952. }
  58953. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  58954. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  58955. }
  58956. };
  58957. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  58958. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  58959. };
  58960. ArcRotateCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
  58961. return "ArcRotateCameraVRDeviceOrientationInput";
  58962. };
  58963. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  58964. return "VRDeviceOrientation";
  58965. };
  58966. return ArcRotateCameraVRDeviceOrientationInput;
  58967. }());
  58968. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  58969. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  58970. })(BABYLON || (BABYLON = {}));
  58971. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  58972. var BABYLON;
  58973. (function (BABYLON) {
  58974. var VRCameraMetrics = (function () {
  58975. function VRCameraMetrics() {
  58976. this.compensateDistortion = true;
  58977. }
  58978. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  58979. get: function () {
  58980. return this.hResolution / (2 * this.vResolution);
  58981. },
  58982. enumerable: true,
  58983. configurable: true
  58984. });
  58985. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  58986. get: function () {
  58987. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  58988. },
  58989. enumerable: true,
  58990. configurable: true
  58991. });
  58992. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  58993. get: function () {
  58994. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  58995. var h = (4 * meters) / this.hScreenSize;
  58996. return BABYLON.Matrix.Translation(h, 0, 0);
  58997. },
  58998. enumerable: true,
  58999. configurable: true
  59000. });
  59001. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  59002. get: function () {
  59003. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  59004. var h = (4 * meters) / this.hScreenSize;
  59005. return BABYLON.Matrix.Translation(-h, 0, 0);
  59006. },
  59007. enumerable: true,
  59008. configurable: true
  59009. });
  59010. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  59011. get: function () {
  59012. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  59013. },
  59014. enumerable: true,
  59015. configurable: true
  59016. });
  59017. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  59018. get: function () {
  59019. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  59020. },
  59021. enumerable: true,
  59022. configurable: true
  59023. });
  59024. VRCameraMetrics.GetDefault = function () {
  59025. var result = new VRCameraMetrics();
  59026. result.hResolution = 1280;
  59027. result.vResolution = 800;
  59028. result.hScreenSize = 0.149759993;
  59029. result.vScreenSize = 0.0935999975;
  59030. result.vScreenCenter = 0.0467999987;
  59031. result.eyeToScreenDistance = 0.0410000011;
  59032. result.lensSeparationDistance = 0.0635000020;
  59033. result.interpupillaryDistance = 0.0640000030;
  59034. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  59035. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  59036. result.postProcessScaleFactor = 1.714605507808412;
  59037. result.lensCenterOffset = 0.151976421;
  59038. return result;
  59039. };
  59040. return VRCameraMetrics;
  59041. }());
  59042. BABYLON.VRCameraMetrics = VRCameraMetrics;
  59043. })(BABYLON || (BABYLON = {}));
  59044. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  59045. var BABYLON;
  59046. (function (BABYLON) {
  59047. var WebVRFreeCamera = (function (_super) {
  59048. __extends(WebVRFreeCamera, _super);
  59049. function WebVRFreeCamera(name, position, scene, webVROptions) {
  59050. if (webVROptions === void 0) { webVROptions = {}; }
  59051. var _this = _super.call(this, name, position, scene) || this;
  59052. _this.webVROptions = webVROptions;
  59053. _this._vrDevice = null;
  59054. _this.rawPose = null;
  59055. _this._vrEnabled = false;
  59056. _this._specsVersion = 1.1;
  59057. _this._attached = false;
  59058. _this._positionOffset = BABYLON.Vector3.Zero();
  59059. _this._descendants = [];
  59060. _this.devicePosition = BABYLON.Vector3.Zero();
  59061. _this.deviceScaleFactor = 1;
  59062. _this.controllers = [];
  59063. _this.rigParenting = true; // should the rig cameras be used as parent instead of this camera.
  59064. //legacy support - the compensation boolean was removed.
  59065. if (arguments.length === 5) {
  59066. _this.webVROptions = arguments[4];
  59067. }
  59068. // default webVR options
  59069. if (_this.webVROptions.trackPosition == undefined) {
  59070. _this.webVROptions.trackPosition = true;
  59071. }
  59072. if (_this.webVROptions.controllerMeshes == undefined) {
  59073. _this.webVROptions.controllerMeshes = true;
  59074. }
  59075. if (_this.webVROptions.defaultLightningOnControllers == undefined) {
  59076. _this.webVROptions.defaultLightningOnControllers = true;
  59077. }
  59078. _this.rotationQuaternion = new BABYLON.Quaternion();
  59079. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  59080. if (_this.webVROptions && _this.webVROptions.positionScale) {
  59081. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  59082. }
  59083. //enable VR
  59084. _this.getEngine().initWebVR();
  59085. //check specs version
  59086. if (!window.VRFrameData) {
  59087. _this._specsVersion = 1.0;
  59088. _this._frameData = {};
  59089. }
  59090. else {
  59091. _this._frameData = new VRFrameData();
  59092. }
  59093. _this.getEngine().getVRDevice(_this.webVROptions.displayName, function (device) {
  59094. if (!device) {
  59095. return;
  59096. }
  59097. _this._vrEnabled = true;
  59098. _this._vrDevice = device;
  59099. //reset the rig parameters.
  59100. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  59101. if (_this._attached) {
  59102. _this.getEngine().enableVR(_this._vrDevice);
  59103. }
  59104. });
  59105. // try to attach the controllers, if found.
  59106. _this.initControllers();
  59107. /**
  59108. * The idea behind the following lines:
  59109. * objects that have the camera as parent should actually have the rig cameras as a parent.
  59110. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  59111. * the second will not show it correctly.
  59112. *
  59113. * To solve this - each object that has the camera as parent will be added to a protected array.
  59114. * When the rig camera renders, it will take this array and set all of those to be its children.
  59115. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  59116. * Amazing!
  59117. */
  59118. scene.onBeforeCameraRenderObservable.add(function (camera) {
  59119. if (camera.parent === _this && _this.rigParenting) {
  59120. _this._descendants = _this.getDescendants(true, function (n) {
  59121. // don't take the cameras or the controllers!
  59122. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  59123. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  59124. return !isController && !isRigCamera;
  59125. });
  59126. _this._descendants.forEach(function (node) {
  59127. node.parent = camera;
  59128. });
  59129. }
  59130. });
  59131. scene.onAfterCameraRenderObservable.add(function (camera) {
  59132. if (camera.parent === _this && _this.rigParenting) {
  59133. _this._descendants.forEach(function (node) {
  59134. node.parent = _this;
  59135. });
  59136. }
  59137. });
  59138. return _this;
  59139. }
  59140. Object.defineProperty(WebVRFreeCamera.prototype, "onControllersAttached", {
  59141. set: function (callback) {
  59142. this._onControllersAttached = callback;
  59143. // after setting - if the controllers are already set, execute the callback.
  59144. if (this.controllers.length >= 2) {
  59145. callback(this.controllers);
  59146. }
  59147. },
  59148. enumerable: true,
  59149. configurable: true
  59150. });
  59151. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  59152. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  59153. var gp = _a[_i];
  59154. if (gp.hand === name) {
  59155. return gp;
  59156. }
  59157. }
  59158. return undefined;
  59159. };
  59160. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  59161. get: function () {
  59162. if (!this._leftController) {
  59163. this._leftController = this.getControllerByName("left");
  59164. }
  59165. return this._leftController;
  59166. },
  59167. enumerable: true,
  59168. configurable: true
  59169. });
  59170. ;
  59171. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  59172. get: function () {
  59173. if (!this._rightController) {
  59174. this._rightController = this.getControllerByName("right");
  59175. }
  59176. return this._rightController;
  59177. },
  59178. enumerable: true,
  59179. configurable: true
  59180. });
  59181. ;
  59182. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  59183. if (length === void 0) { length = 100; }
  59184. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.position.add(this.devicePosition)); // Need the actual rendered camera
  59185. };
  59186. WebVRFreeCamera.prototype._checkInputs = function () {
  59187. if (this._vrEnabled) {
  59188. if (this._specsVersion === 1.1) {
  59189. this._vrDevice.getFrameData(this._frameData);
  59190. }
  59191. else {
  59192. //backwards comp
  59193. var pose = this._vrDevice.getPose();
  59194. this._frameData.pose = pose;
  59195. // calculate view and projection matrix
  59196. }
  59197. this.updateFromDevice(this._frameData.pose);
  59198. }
  59199. _super.prototype._checkInputs.call(this);
  59200. };
  59201. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  59202. if (poseData && poseData.orientation) {
  59203. this.rawPose = poseData;
  59204. this.deviceRotationQuaternion.copyFromFloats(this.rawPose.orientation[0], this.rawPose.orientation[1], -this.rawPose.orientation[2], -this.rawPose.orientation[3]);
  59205. if (this.getScene().useRightHandedSystem) {
  59206. this.deviceRotationQuaternion.z *= -1;
  59207. this.deviceRotationQuaternion.w *= -1;
  59208. }
  59209. if (this.webVROptions.trackPosition && this.rawPose.position) {
  59210. this.devicePosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  59211. if (this.getScene().useRightHandedSystem) {
  59212. this.devicePosition.z *= -1;
  59213. }
  59214. }
  59215. }
  59216. };
  59217. /**
  59218. * WebVR's attach control will start broadcasting frames to the device.
  59219. * Note that in certain browsers (chrome for example) this function must be called
  59220. * within a user-interaction callback. Example:
  59221. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  59222. *
  59223. * @param {HTMLElement} element
  59224. * @param {boolean} [noPreventDefault]
  59225. *
  59226. * @memberOf WebVRFreeCamera
  59227. */
  59228. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  59229. _super.prototype.attachControl.call(this, element, noPreventDefault);
  59230. this._attached = true;
  59231. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  59232. if (this._vrEnabled) {
  59233. this.getEngine().enableVR(this._vrDevice);
  59234. }
  59235. };
  59236. WebVRFreeCamera.prototype.detachControl = function (element) {
  59237. _super.prototype.detachControl.call(this, element);
  59238. this._vrEnabled = false;
  59239. this._attached = false;
  59240. this.getEngine().disableVR();
  59241. };
  59242. WebVRFreeCamera.prototype.getClassName = function () {
  59243. return "WebVRFreeCamera";
  59244. };
  59245. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  59246. //uses the vrDisplay's "resetPose()".
  59247. //pitch and roll won't be affected.
  59248. this._vrDevice.resetPose();
  59249. };
  59250. WebVRFreeCamera.prototype._updateRigCameras = function () {
  59251. var camLeft = this._rigCameras[0];
  59252. var camRight = this._rigCameras[1];
  59253. camLeft.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  59254. camRight.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  59255. camLeft.position.copyFrom(this.devicePosition);
  59256. camRight.position.copyFrom(this.devicePosition);
  59257. };
  59258. /**
  59259. * This function is called by the two RIG cameras.
  59260. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  59261. */
  59262. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  59263. var _this = this;
  59264. //WebVR 1.0
  59265. if (this._cameraRigParams["specs"] === 1.0) {
  59266. this._updateCameraRotationMatrix();
  59267. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  59268. // Computing target and final matrix
  59269. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  59270. if (this.getScene().useRightHandedSystem) {
  59271. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._webvrViewMatrix);
  59272. }
  59273. else {
  59274. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._webvrViewMatrix);
  59275. }
  59276. //now move the eye in the right direction
  59277. var eyeParams = this._cameraRigParams["eyeParameters"];
  59278. var offset = eyeParams.offset;
  59279. // it will actually always be 0, but just in case
  59280. if (this.getScene().useRightHandedSystem) {
  59281. offset[2] *= -1;
  59282. }
  59283. BABYLON.Matrix.TranslationToRef(-offset[0], offset[1], -offset[2], BABYLON.Tmp.Matrix[0]);
  59284. this._webvrViewMatrix.multiplyToRef(BABYLON.Tmp.Matrix[0], this._webvrViewMatrix);
  59285. }
  59286. else {
  59287. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  59288. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  59289. if (!this.getScene().useRightHandedSystem) {
  59290. [2, 6, 8, 9, 14].forEach(function (num) {
  59291. _this._webvrViewMatrix.m[num] *= -1;
  59292. });
  59293. }
  59294. // update the camera rotation matrix
  59295. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  59296. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  59297. // Computing target and final matrix
  59298. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  59299. }
  59300. var parentCamera = this._cameraRigParams["parentCamera"];
  59301. // should the view matrix be updated with scale and position offset?
  59302. if (parentCamera.deviceScaleFactor !== 1) {
  59303. this._webvrViewMatrix.invert();
  59304. // scale the position, if set
  59305. if (parentCamera.deviceScaleFactor) {
  59306. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  59307. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  59308. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  59309. }
  59310. this._webvrViewMatrix.invert();
  59311. }
  59312. return this._webvrViewMatrix;
  59313. };
  59314. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  59315. var _this = this;
  59316. if (this._cameraRigParams["specs"] === 1.0) {
  59317. var eyeParams = this._cameraRigParams["eyeParameters"];
  59318. // deprecated!!
  59319. BABYLON.Matrix.PerspectiveFovWebVRToRef(eyeParams.fieldOfView, 0.1, 1000, this._projectionMatrix, this.getScene().useRightHandedSystem);
  59320. }
  59321. else {
  59322. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  59323. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  59324. //babylon compatible matrix
  59325. if (!this.getScene().useRightHandedSystem) {
  59326. [8, 9, 10, 11].forEach(function (num) {
  59327. _this._projectionMatrix.m[num] *= -1;
  59328. });
  59329. }
  59330. }
  59331. return this._projectionMatrix;
  59332. };
  59333. WebVRFreeCamera.prototype.initControllers = function () {
  59334. var _this = this;
  59335. this.controllers = [];
  59336. new BABYLON.Gamepads(function (gp) {
  59337. if (gp.type === BABYLON.Gamepad.POSE_ENABLED) {
  59338. var webVrController = gp;
  59339. if (_this.webVROptions.controllerMeshes) {
  59340. webVrController.initControllerMesh(_this.getScene(), function (loadedMesh) {
  59341. if (_this.webVROptions.defaultLightningOnControllers) {
  59342. if (!_this._lightOnControllers) {
  59343. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  59344. }
  59345. loadedMesh.getChildren().forEach(function (mesh) {
  59346. _this._lightOnControllers.includedOnlyMeshes.push(mesh);
  59347. });
  59348. }
  59349. });
  59350. }
  59351. webVrController.attachToPoseControlledCamera(_this);
  59352. // since this is async - sanity check. Is the controller already stored?
  59353. if (_this.controllers.indexOf(webVrController) === -1) {
  59354. //add to the controllers array
  59355. _this.controllers.push(webVrController);
  59356. //did we find enough controllers? Great! let the developer know.
  59357. if (_this._onControllersAttached && _this.controllers.length >= 2) {
  59358. _this._onControllersAttached(_this.controllers);
  59359. }
  59360. }
  59361. }
  59362. });
  59363. };
  59364. return WebVRFreeCamera;
  59365. }(BABYLON.FreeCamera));
  59366. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  59367. })(BABYLON || (BABYLON = {}));
  59368. //# sourceMappingURL=babylon.webVRCamera.js.map
  59369. /// <reference path="babylon.freeCamera.ts" />
  59370. var BABYLON;
  59371. (function (BABYLON) {
  59372. // We're mainly based on the logic defined into the FreeCamera code
  59373. var DeviceOrientationCamera = (function (_super) {
  59374. __extends(DeviceOrientationCamera, _super);
  59375. function DeviceOrientationCamera(name, position, scene) {
  59376. var _this = _super.call(this, name, position, scene) || this;
  59377. _this._quaternionCache = new BABYLON.Quaternion();
  59378. _this.inputs.addDeviceOrientation();
  59379. return _this;
  59380. }
  59381. DeviceOrientationCamera.prototype.getClassName = function () {
  59382. return "DeviceOrientationCamera";
  59383. };
  59384. DeviceOrientationCamera.prototype._checkInputs = function () {
  59385. _super.prototype._checkInputs.call(this);
  59386. this._quaternionCache.copyFrom(this.rotationQuaternion);
  59387. if (this._initialQuaternion) {
  59388. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  59389. }
  59390. };
  59391. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  59392. var _this = this;
  59393. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  59394. //can only work if this camera has a rotation quaternion already.
  59395. if (!this.rotationQuaternion)
  59396. return;
  59397. if (!this._initialQuaternion) {
  59398. this._initialQuaternion = new BABYLON.Quaternion();
  59399. }
  59400. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  59401. ['x', 'y', 'z'].forEach(function (axisName) {
  59402. if (!axis[axisName]) {
  59403. _this._initialQuaternion[axisName] = 0;
  59404. }
  59405. else {
  59406. _this._initialQuaternion[axisName] *= -1;
  59407. }
  59408. });
  59409. this._initialQuaternion.normalize();
  59410. //force rotation update
  59411. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  59412. };
  59413. return DeviceOrientationCamera;
  59414. }(BABYLON.FreeCamera));
  59415. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  59416. })(BABYLON || (BABYLON = {}));
  59417. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  59418. var BABYLON;
  59419. (function (BABYLON) {
  59420. var VRDeviceOrientationFreeCamera = (function (_super) {
  59421. __extends(VRDeviceOrientationFreeCamera, _super);
  59422. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  59423. if (compensateDistortion === void 0) { compensateDistortion = true; }
  59424. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  59425. var _this = _super.call(this, name, position, scene) || this;
  59426. vrCameraMetrics.compensateDistortion = compensateDistortion;
  59427. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  59428. return _this;
  59429. }
  59430. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  59431. return "VRDeviceOrientationFreeCamera";
  59432. };
  59433. return VRDeviceOrientationFreeCamera;
  59434. }(BABYLON.DeviceOrientationCamera));
  59435. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  59436. var VRDeviceOrientationGamepadCamera = (function (_super) {
  59437. __extends(VRDeviceOrientationGamepadCamera, _super);
  59438. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  59439. if (compensateDistortion === void 0) { compensateDistortion = true; }
  59440. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  59441. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  59442. _this.inputs.addGamepad();
  59443. return _this;
  59444. }
  59445. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  59446. return "VRDeviceOrientationGamepadCamera";
  59447. };
  59448. return VRDeviceOrientationGamepadCamera;
  59449. }(VRDeviceOrientationFreeCamera));
  59450. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  59451. var VRDeviceOrientationArcRotateCamera = (function (_super) {
  59452. __extends(VRDeviceOrientationArcRotateCamera, _super);
  59453. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  59454. if (compensateDistortion === void 0) { compensateDistortion = true; }
  59455. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  59456. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  59457. vrCameraMetrics.compensateDistortion = compensateDistortion;
  59458. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  59459. _this.inputs.addVRDeviceOrientation();
  59460. return _this;
  59461. }
  59462. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  59463. return "VRDeviceOrientationArcRotateCamera";
  59464. };
  59465. return VRDeviceOrientationArcRotateCamera;
  59466. }(BABYLON.ArcRotateCamera));
  59467. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  59468. })(BABYLON || (BABYLON = {}));
  59469. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  59470. /// <reference path="babylon.freeCamera.ts" />
  59471. /// <reference path="babylon.arcRotateCamera.ts" />
  59472. /// <reference path="babylon.gamepadCamera.ts" />
  59473. /// <reference path="babylon.universalCamera.ts" />
  59474. var BABYLON;
  59475. (function (BABYLON) {
  59476. var AnaglyphFreeCamera = (function (_super) {
  59477. __extends(AnaglyphFreeCamera, _super);
  59478. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  59479. var _this = _super.call(this, name, position, scene) || this;
  59480. _this.interaxialDistance = interaxialDistance;
  59481. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  59482. return _this;
  59483. }
  59484. AnaglyphFreeCamera.prototype.getClassName = function () {
  59485. return "AnaglyphFreeCamera";
  59486. };
  59487. return AnaglyphFreeCamera;
  59488. }(BABYLON.FreeCamera));
  59489. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  59490. var AnaglyphArcRotateCamera = (function (_super) {
  59491. __extends(AnaglyphArcRotateCamera, _super);
  59492. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  59493. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  59494. _this.interaxialDistance = interaxialDistance;
  59495. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  59496. return _this;
  59497. }
  59498. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  59499. return "AnaglyphArcRotateCamera";
  59500. };
  59501. return AnaglyphArcRotateCamera;
  59502. }(BABYLON.ArcRotateCamera));
  59503. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  59504. var AnaglyphGamepadCamera = (function (_super) {
  59505. __extends(AnaglyphGamepadCamera, _super);
  59506. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  59507. var _this = _super.call(this, name, position, scene) || this;
  59508. _this.interaxialDistance = interaxialDistance;
  59509. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  59510. return _this;
  59511. }
  59512. AnaglyphGamepadCamera.prototype.getClassName = function () {
  59513. return "AnaglyphGamepadCamera";
  59514. };
  59515. return AnaglyphGamepadCamera;
  59516. }(BABYLON.GamepadCamera));
  59517. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  59518. var AnaglyphUniversalCamera = (function (_super) {
  59519. __extends(AnaglyphUniversalCamera, _super);
  59520. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  59521. var _this = _super.call(this, name, position, scene) || this;
  59522. _this.interaxialDistance = interaxialDistance;
  59523. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  59524. return _this;
  59525. }
  59526. AnaglyphUniversalCamera.prototype.getClassName = function () {
  59527. return "AnaglyphUniversalCamera";
  59528. };
  59529. return AnaglyphUniversalCamera;
  59530. }(BABYLON.UniversalCamera));
  59531. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  59532. var StereoscopicFreeCamera = (function (_super) {
  59533. __extends(StereoscopicFreeCamera, _super);
  59534. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  59535. var _this = _super.call(this, name, position, scene) || this;
  59536. _this.interaxialDistance = interaxialDistance;
  59537. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  59538. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  59539. return _this;
  59540. }
  59541. StereoscopicFreeCamera.prototype.getClassName = function () {
  59542. return "StereoscopicFreeCamera";
  59543. };
  59544. return StereoscopicFreeCamera;
  59545. }(BABYLON.FreeCamera));
  59546. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  59547. var StereoscopicArcRotateCamera = (function (_super) {
  59548. __extends(StereoscopicArcRotateCamera, _super);
  59549. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  59550. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  59551. _this.interaxialDistance = interaxialDistance;
  59552. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  59553. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  59554. return _this;
  59555. }
  59556. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  59557. return "StereoscopicArcRotateCamera";
  59558. };
  59559. return StereoscopicArcRotateCamera;
  59560. }(BABYLON.ArcRotateCamera));
  59561. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  59562. var StereoscopicGamepadCamera = (function (_super) {
  59563. __extends(StereoscopicGamepadCamera, _super);
  59564. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  59565. var _this = _super.call(this, name, position, scene) || this;
  59566. _this.interaxialDistance = interaxialDistance;
  59567. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  59568. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  59569. return _this;
  59570. }
  59571. StereoscopicGamepadCamera.prototype.getClassName = function () {
  59572. return "StereoscopicGamepadCamera";
  59573. };
  59574. return StereoscopicGamepadCamera;
  59575. }(BABYLON.GamepadCamera));
  59576. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  59577. var StereoscopicUniversalCamera = (function (_super) {
  59578. __extends(StereoscopicUniversalCamera, _super);
  59579. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  59580. var _this = _super.call(this, name, position, scene) || this;
  59581. _this.interaxialDistance = interaxialDistance;
  59582. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  59583. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  59584. return _this;
  59585. }
  59586. StereoscopicUniversalCamera.prototype.getClassName = function () {
  59587. return "StereoscopicUniversalCamera";
  59588. };
  59589. return StereoscopicUniversalCamera;
  59590. }(BABYLON.UniversalCamera));
  59591. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  59592. })(BABYLON || (BABYLON = {}));
  59593. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  59594. // Mainly based on these 2 articles :
  59595. // 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
  59596. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  59597. var BABYLON;
  59598. (function (BABYLON) {
  59599. var JoystickAxis;
  59600. (function (JoystickAxis) {
  59601. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  59602. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  59603. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  59604. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  59605. var VirtualJoystick = (function () {
  59606. function VirtualJoystick(leftJoystick) {
  59607. var _this = this;
  59608. if (leftJoystick) {
  59609. this._leftJoystick = true;
  59610. }
  59611. else {
  59612. this._leftJoystick = false;
  59613. }
  59614. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  59615. VirtualJoystick._globalJoystickIndex++;
  59616. // By default left & right arrow keys are moving the X
  59617. // and up & down keys are moving the Y
  59618. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  59619. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  59620. this.reverseLeftRight = false;
  59621. this.reverseUpDown = false;
  59622. // collections of pointers
  59623. this._touches = new BABYLON.StringDictionary();
  59624. this.deltaPosition = BABYLON.Vector3.Zero();
  59625. this._joystickSensibility = 25;
  59626. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  59627. this._rotationSpeed = 25;
  59628. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  59629. this._rotateOnAxisRelativeToMesh = false;
  59630. this._onResize = function (evt) {
  59631. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  59632. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  59633. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  59634. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  59635. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  59636. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  59637. };
  59638. // injecting a canvas element on top of the canvas 3D game
  59639. if (!VirtualJoystick.vjCanvas) {
  59640. window.addEventListener("resize", this._onResize, false);
  59641. VirtualJoystick.vjCanvas = document.createElement("canvas");
  59642. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  59643. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  59644. VirtualJoystick.vjCanvas.width = window.innerWidth;
  59645. VirtualJoystick.vjCanvas.height = window.innerHeight;
  59646. VirtualJoystick.vjCanvas.style.width = "100%";
  59647. VirtualJoystick.vjCanvas.style.height = "100%";
  59648. VirtualJoystick.vjCanvas.style.position = "absolute";
  59649. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  59650. VirtualJoystick.vjCanvas.style.top = "0px";
  59651. VirtualJoystick.vjCanvas.style.left = "0px";
  59652. VirtualJoystick.vjCanvas.style.zIndex = "5";
  59653. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  59654. // Support for jQuery PEP polyfill
  59655. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  59656. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  59657. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  59658. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  59659. document.body.appendChild(VirtualJoystick.vjCanvas);
  59660. }
  59661. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  59662. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  59663. this.pressed = false;
  59664. // default joystick color
  59665. this._joystickColor = "cyan";
  59666. this._joystickPointerID = -1;
  59667. // current joystick position
  59668. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  59669. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  59670. // origin joystick position
  59671. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  59672. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  59673. this._onPointerDownHandlerRef = function (evt) {
  59674. _this._onPointerDown(evt);
  59675. };
  59676. this._onPointerMoveHandlerRef = function (evt) {
  59677. _this._onPointerMove(evt);
  59678. };
  59679. this._onPointerOutHandlerRef = function (evt) {
  59680. _this._onPointerUp(evt);
  59681. };
  59682. this._onPointerUpHandlerRef = function (evt) {
  59683. _this._onPointerUp(evt);
  59684. };
  59685. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  59686. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  59687. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  59688. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  59689. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  59690. evt.preventDefault(); // Disables system menu
  59691. }, false);
  59692. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  59693. }
  59694. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  59695. this._joystickSensibility = newJoystickSensibility;
  59696. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  59697. };
  59698. VirtualJoystick.prototype._onPointerDown = function (e) {
  59699. var positionOnScreenCondition;
  59700. e.preventDefault();
  59701. if (this._leftJoystick === true) {
  59702. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  59703. }
  59704. else {
  59705. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  59706. }
  59707. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  59708. // First contact will be dedicated to the virtual joystick
  59709. this._joystickPointerID = e.pointerId;
  59710. this._joystickPointerStartPos.x = e.clientX;
  59711. this._joystickPointerStartPos.y = e.clientY;
  59712. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  59713. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  59714. this._deltaJoystickVector.x = 0;
  59715. this._deltaJoystickVector.y = 0;
  59716. this.pressed = true;
  59717. this._touches.add(e.pointerId.toString(), e);
  59718. }
  59719. else {
  59720. // You can only trigger the action buttons with a joystick declared
  59721. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  59722. this._action();
  59723. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  59724. }
  59725. }
  59726. };
  59727. VirtualJoystick.prototype._onPointerMove = function (e) {
  59728. // If the current pointer is the one associated to the joystick (first touch contact)
  59729. if (this._joystickPointerID == e.pointerId) {
  59730. this._joystickPointerPos.x = e.clientX;
  59731. this._joystickPointerPos.y = e.clientY;
  59732. this._deltaJoystickVector = this._joystickPointerPos.clone();
  59733. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  59734. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  59735. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  59736. switch (this._axisTargetedByLeftAndRight) {
  59737. case JoystickAxis.X:
  59738. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  59739. break;
  59740. case JoystickAxis.Y:
  59741. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  59742. break;
  59743. case JoystickAxis.Z:
  59744. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  59745. break;
  59746. }
  59747. var directionUpDown = this.reverseUpDown ? 1 : -1;
  59748. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  59749. switch (this._axisTargetedByUpAndDown) {
  59750. case JoystickAxis.X:
  59751. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  59752. break;
  59753. case JoystickAxis.Y:
  59754. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  59755. break;
  59756. case JoystickAxis.Z:
  59757. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  59758. break;
  59759. }
  59760. }
  59761. else {
  59762. var data = this._touches.get(e.pointerId.toString());
  59763. if (data) {
  59764. data.x = e.clientX;
  59765. data.y = e.clientY;
  59766. }
  59767. }
  59768. };
  59769. VirtualJoystick.prototype._onPointerUp = function (e) {
  59770. if (this._joystickPointerID == e.pointerId) {
  59771. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  59772. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  59773. this._joystickPointerID = -1;
  59774. this.pressed = false;
  59775. }
  59776. else {
  59777. var touch = this._touches.get(e.pointerId.toString());
  59778. if (touch) {
  59779. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  59780. }
  59781. }
  59782. this._deltaJoystickVector.x = 0;
  59783. this._deltaJoystickVector.y = 0;
  59784. this._touches.remove(e.pointerId.toString());
  59785. };
  59786. /**
  59787. * Change the color of the virtual joystick
  59788. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  59789. */
  59790. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  59791. this._joystickColor = newColor;
  59792. };
  59793. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  59794. this._action = action;
  59795. };
  59796. // Define which axis you'd like to control for left & right
  59797. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  59798. switch (axis) {
  59799. case JoystickAxis.X:
  59800. case JoystickAxis.Y:
  59801. case JoystickAxis.Z:
  59802. this._axisTargetedByLeftAndRight = axis;
  59803. break;
  59804. default:
  59805. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  59806. break;
  59807. }
  59808. };
  59809. // Define which axis you'd like to control for up & down
  59810. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  59811. switch (axis) {
  59812. case JoystickAxis.X:
  59813. case JoystickAxis.Y:
  59814. case JoystickAxis.Z:
  59815. this._axisTargetedByUpAndDown = axis;
  59816. break;
  59817. default:
  59818. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  59819. break;
  59820. }
  59821. };
  59822. VirtualJoystick.prototype._clearCanvas = function () {
  59823. if (this._leftJoystick) {
  59824. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  59825. }
  59826. else {
  59827. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  59828. }
  59829. };
  59830. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  59831. var _this = this;
  59832. if (this.pressed) {
  59833. this._touches.forEach(function (key, touch) {
  59834. if (touch.pointerId === _this._joystickPointerID) {
  59835. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  59836. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  59837. VirtualJoystick.vjCanvasContext.beginPath();
  59838. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  59839. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  59840. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  59841. VirtualJoystick.vjCanvasContext.stroke();
  59842. VirtualJoystick.vjCanvasContext.closePath();
  59843. VirtualJoystick.vjCanvasContext.beginPath();
  59844. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  59845. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  59846. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  59847. VirtualJoystick.vjCanvasContext.stroke();
  59848. VirtualJoystick.vjCanvasContext.closePath();
  59849. VirtualJoystick.vjCanvasContext.beginPath();
  59850. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  59851. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  59852. VirtualJoystick.vjCanvasContext.stroke();
  59853. VirtualJoystick.vjCanvasContext.closePath();
  59854. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  59855. }
  59856. else {
  59857. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  59858. VirtualJoystick.vjCanvasContext.beginPath();
  59859. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  59860. VirtualJoystick.vjCanvasContext.beginPath();
  59861. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  59862. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  59863. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  59864. VirtualJoystick.vjCanvasContext.stroke();
  59865. VirtualJoystick.vjCanvasContext.closePath();
  59866. touch.prevX = touch.x;
  59867. touch.prevY = touch.y;
  59868. }
  59869. ;
  59870. });
  59871. }
  59872. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  59873. };
  59874. VirtualJoystick.prototype.releaseCanvas = function () {
  59875. if (VirtualJoystick.vjCanvas) {
  59876. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  59877. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  59878. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  59879. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  59880. window.removeEventListener("resize", this._onResize);
  59881. document.body.removeChild(VirtualJoystick.vjCanvas);
  59882. VirtualJoystick.vjCanvas = null;
  59883. }
  59884. };
  59885. return VirtualJoystick;
  59886. }());
  59887. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  59888. VirtualJoystick._globalJoystickIndex = 0;
  59889. BABYLON.VirtualJoystick = VirtualJoystick;
  59890. })(BABYLON || (BABYLON = {}));
  59891. //# sourceMappingURL=babylon.virtualJoystick.js.map
  59892. var BABYLON;
  59893. (function (BABYLON) {
  59894. // We're mainly based on the logic defined into the FreeCamera code
  59895. var VirtualJoysticksCamera = (function (_super) {
  59896. __extends(VirtualJoysticksCamera, _super);
  59897. function VirtualJoysticksCamera(name, position, scene) {
  59898. var _this = _super.call(this, name, position, scene) || this;
  59899. _this.inputs.addVirtualJoystick();
  59900. return _this;
  59901. }
  59902. VirtualJoysticksCamera.prototype.getClassName = function () {
  59903. return "VirtualJoysticksCamera";
  59904. };
  59905. return VirtualJoysticksCamera;
  59906. }(BABYLON.FreeCamera));
  59907. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  59908. })(BABYLON || (BABYLON = {}));
  59909. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  59910. var BABYLON;
  59911. (function (BABYLON) {
  59912. var FreeCameraVirtualJoystickInput = (function () {
  59913. function FreeCameraVirtualJoystickInput() {
  59914. }
  59915. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  59916. return this._leftjoystick;
  59917. };
  59918. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  59919. return this._rightjoystick;
  59920. };
  59921. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  59922. if (this._leftjoystick) {
  59923. var camera = this.camera;
  59924. var speed = camera._computeLocalCameraSpeed() * 50;
  59925. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  59926. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  59927. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  59928. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  59929. if (!this._leftjoystick.pressed) {
  59930. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  59931. }
  59932. if (!this._rightjoystick.pressed) {
  59933. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  59934. }
  59935. }
  59936. };
  59937. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  59938. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  59939. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  59940. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  59941. this._leftjoystick.setJoystickSensibility(0.15);
  59942. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  59943. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  59944. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  59945. this._rightjoystick.reverseUpDown = true;
  59946. this._rightjoystick.setJoystickSensibility(0.05);
  59947. this._rightjoystick.setJoystickColor("yellow");
  59948. };
  59949. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  59950. this._leftjoystick.releaseCanvas();
  59951. this._rightjoystick.releaseCanvas();
  59952. };
  59953. FreeCameraVirtualJoystickInput.prototype.getTypeName = function () {
  59954. return "FreeCameraVirtualJoystickInput";
  59955. };
  59956. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  59957. return "virtualJoystick";
  59958. };
  59959. return FreeCameraVirtualJoystickInput;
  59960. }());
  59961. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  59962. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  59963. })(BABYLON || (BABYLON = {}));
  59964. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  59965. var BABYLON;
  59966. (function (BABYLON) {
  59967. var SimplificationSettings = (function () {
  59968. function SimplificationSettings(quality, distance, optimizeMesh) {
  59969. this.quality = quality;
  59970. this.distance = distance;
  59971. this.optimizeMesh = optimizeMesh;
  59972. }
  59973. return SimplificationSettings;
  59974. }());
  59975. BABYLON.SimplificationSettings = SimplificationSettings;
  59976. var SimplificationQueue = (function () {
  59977. function SimplificationQueue() {
  59978. this.running = false;
  59979. this._simplificationArray = [];
  59980. }
  59981. SimplificationQueue.prototype.addTask = function (task) {
  59982. this._simplificationArray.push(task);
  59983. };
  59984. SimplificationQueue.prototype.executeNext = function () {
  59985. var task = this._simplificationArray.pop();
  59986. if (task) {
  59987. this.running = true;
  59988. this.runSimplification(task);
  59989. }
  59990. else {
  59991. this.running = false;
  59992. }
  59993. };
  59994. SimplificationQueue.prototype.runSimplification = function (task) {
  59995. var _this = this;
  59996. if (task.parallelProcessing) {
  59997. //parallel simplifier
  59998. task.settings.forEach(function (setting) {
  59999. var simplifier = _this.getSimplifier(task);
  60000. simplifier.simplify(setting, function (newMesh) {
  60001. task.mesh.addLODLevel(setting.distance, newMesh);
  60002. newMesh.isVisible = true;
  60003. //check if it is the last
  60004. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  60005. //all done, run the success callback.
  60006. task.successCallback();
  60007. }
  60008. _this.executeNext();
  60009. });
  60010. });
  60011. }
  60012. else {
  60013. //single simplifier.
  60014. var simplifier = this.getSimplifier(task);
  60015. var runDecimation = function (setting, callback) {
  60016. simplifier.simplify(setting, function (newMesh) {
  60017. task.mesh.addLODLevel(setting.distance, newMesh);
  60018. newMesh.isVisible = true;
  60019. //run the next quality level
  60020. callback();
  60021. });
  60022. };
  60023. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  60024. runDecimation(task.settings[loop.index], function () {
  60025. loop.executeNext();
  60026. });
  60027. }, function () {
  60028. //execution ended, run the success callback.
  60029. if (task.successCallback) {
  60030. task.successCallback();
  60031. }
  60032. _this.executeNext();
  60033. });
  60034. }
  60035. };
  60036. SimplificationQueue.prototype.getSimplifier = function (task) {
  60037. switch (task.simplificationType) {
  60038. case SimplificationType.QUADRATIC:
  60039. default:
  60040. return new QuadraticErrorSimplification(task.mesh);
  60041. }
  60042. };
  60043. return SimplificationQueue;
  60044. }());
  60045. BABYLON.SimplificationQueue = SimplificationQueue;
  60046. /**
  60047. * The implemented types of simplification.
  60048. * At the moment only Quadratic Error Decimation is implemented.
  60049. */
  60050. var SimplificationType;
  60051. (function (SimplificationType) {
  60052. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  60053. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  60054. var DecimationTriangle = (function () {
  60055. function DecimationTriangle(vertices) {
  60056. this.vertices = vertices;
  60057. this.error = new Array(4);
  60058. this.deleted = false;
  60059. this.isDirty = false;
  60060. this.deletePending = false;
  60061. this.borderFactor = 0;
  60062. }
  60063. return DecimationTriangle;
  60064. }());
  60065. BABYLON.DecimationTriangle = DecimationTriangle;
  60066. var DecimationVertex = (function () {
  60067. function DecimationVertex(position, id) {
  60068. this.position = position;
  60069. this.id = id;
  60070. this.isBorder = true;
  60071. this.q = new QuadraticMatrix();
  60072. this.triangleCount = 0;
  60073. this.triangleStart = 0;
  60074. this.originalOffsets = [];
  60075. }
  60076. DecimationVertex.prototype.updatePosition = function (newPosition) {
  60077. this.position.copyFrom(newPosition);
  60078. };
  60079. return DecimationVertex;
  60080. }());
  60081. BABYLON.DecimationVertex = DecimationVertex;
  60082. var QuadraticMatrix = (function () {
  60083. function QuadraticMatrix(data) {
  60084. this.data = new Array(10);
  60085. for (var i = 0; i < 10; ++i) {
  60086. if (data && data[i]) {
  60087. this.data[i] = data[i];
  60088. }
  60089. else {
  60090. this.data[i] = 0;
  60091. }
  60092. }
  60093. }
  60094. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  60095. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  60096. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  60097. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  60098. return det;
  60099. };
  60100. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  60101. for (var i = 0; i < 10; ++i) {
  60102. this.data[i] += matrix.data[i];
  60103. }
  60104. };
  60105. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  60106. for (var i = 0; i < 10; ++i) {
  60107. this.data[i] += data[i];
  60108. }
  60109. };
  60110. QuadraticMatrix.prototype.add = function (matrix) {
  60111. var m = new QuadraticMatrix();
  60112. for (var i = 0; i < 10; ++i) {
  60113. m.data[i] = this.data[i] + matrix.data[i];
  60114. }
  60115. return m;
  60116. };
  60117. QuadraticMatrix.FromData = function (a, b, c, d) {
  60118. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  60119. };
  60120. //returning an array to avoid garbage collection
  60121. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  60122. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  60123. };
  60124. return QuadraticMatrix;
  60125. }());
  60126. BABYLON.QuadraticMatrix = QuadraticMatrix;
  60127. var Reference = (function () {
  60128. function Reference(vertexId, triangleId) {
  60129. this.vertexId = vertexId;
  60130. this.triangleId = triangleId;
  60131. }
  60132. return Reference;
  60133. }());
  60134. BABYLON.Reference = Reference;
  60135. /**
  60136. * An implementation of the Quadratic Error simplification algorithm.
  60137. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  60138. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  60139. * @author RaananW
  60140. */
  60141. var QuadraticErrorSimplification = (function () {
  60142. function QuadraticErrorSimplification(_mesh) {
  60143. this._mesh = _mesh;
  60144. this.initialized = false;
  60145. this.syncIterations = 5000;
  60146. this.aggressiveness = 7;
  60147. this.decimationIterations = 100;
  60148. this.boundingBoxEpsilon = BABYLON.Epsilon;
  60149. }
  60150. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  60151. var _this = this;
  60152. this.initDecimatedMesh();
  60153. //iterating through the submeshes array, one after the other.
  60154. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  60155. _this.initWithMesh(loop.index, function () {
  60156. _this.runDecimation(settings, loop.index, function () {
  60157. loop.executeNext();
  60158. });
  60159. }, settings.optimizeMesh);
  60160. }, function () {
  60161. setTimeout(function () {
  60162. successCallback(_this._reconstructedMesh);
  60163. }, 0);
  60164. });
  60165. };
  60166. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  60167. var _this = this;
  60168. var gCount = 0;
  60169. triangle.vertices.forEach(function (vertex) {
  60170. var count = 0;
  60171. var vPos = vertex.position;
  60172. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  60173. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  60174. ++count;
  60175. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  60176. ++count;
  60177. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  60178. ++count;
  60179. if (count > 1) {
  60180. ++gCount;
  60181. }
  60182. ;
  60183. });
  60184. if (gCount > 1) {
  60185. console.log(triangle, gCount);
  60186. }
  60187. return gCount > 1;
  60188. };
  60189. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  60190. var _this = this;
  60191. var targetCount = ~~(this.triangles.length * settings.quality);
  60192. var deletedTriangles = 0;
  60193. var triangleCount = this.triangles.length;
  60194. var iterationFunction = function (iteration, callback) {
  60195. setTimeout(function () {
  60196. if (iteration % 5 === 0) {
  60197. _this.updateMesh(iteration === 0);
  60198. }
  60199. for (var i = 0; i < _this.triangles.length; ++i) {
  60200. _this.triangles[i].isDirty = false;
  60201. }
  60202. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  60203. var trianglesIterator = function (i) {
  60204. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  60205. var t = _this.triangles[tIdx];
  60206. if (!t)
  60207. return;
  60208. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  60209. return;
  60210. }
  60211. for (var j = 0; j < 3; ++j) {
  60212. if (t.error[j] < threshold) {
  60213. var deleted0 = [];
  60214. var deleted1 = [];
  60215. var v0 = t.vertices[j];
  60216. var v1 = t.vertices[(j + 1) % 3];
  60217. if (v0.isBorder || v1.isBorder)
  60218. continue;
  60219. var p = BABYLON.Vector3.Zero();
  60220. var n = BABYLON.Vector3.Zero();
  60221. var uv = BABYLON.Vector2.Zero();
  60222. var color = new BABYLON.Color4(0, 0, 0, 1);
  60223. _this.calculateError(v0, v1, p, n, uv, color);
  60224. var delTr = [];
  60225. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  60226. continue;
  60227. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  60228. continue;
  60229. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  60230. continue;
  60231. var uniqueArray = [];
  60232. delTr.forEach(function (deletedT) {
  60233. if (uniqueArray.indexOf(deletedT) === -1) {
  60234. deletedT.deletePending = true;
  60235. uniqueArray.push(deletedT);
  60236. }
  60237. });
  60238. if (uniqueArray.length % 2 !== 0) {
  60239. continue;
  60240. }
  60241. v0.q = v1.q.add(v0.q);
  60242. v0.updatePosition(p);
  60243. var tStart = _this.references.length;
  60244. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  60245. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  60246. var tCount = _this.references.length - tStart;
  60247. if (tCount <= v0.triangleCount) {
  60248. if (tCount) {
  60249. for (var c = 0; c < tCount; c++) {
  60250. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  60251. }
  60252. }
  60253. }
  60254. else {
  60255. v0.triangleStart = tStart;
  60256. }
  60257. v0.triangleCount = tCount;
  60258. break;
  60259. }
  60260. }
  60261. };
  60262. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  60263. }, 0);
  60264. };
  60265. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  60266. if (triangleCount - deletedTriangles <= targetCount)
  60267. loop.breakLoop();
  60268. else {
  60269. iterationFunction(loop.index, function () {
  60270. loop.executeNext();
  60271. });
  60272. }
  60273. }, function () {
  60274. setTimeout(function () {
  60275. //reconstruct this part of the mesh
  60276. _this.reconstructMesh(submeshIndex);
  60277. successCallback();
  60278. }, 0);
  60279. });
  60280. };
  60281. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  60282. var _this = this;
  60283. this.vertices = [];
  60284. this.triangles = [];
  60285. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60286. var indices = this._mesh.getIndices();
  60287. var submesh = this._mesh.subMeshes[submeshIndex];
  60288. var findInVertices = function (positionToSearch) {
  60289. if (optimizeMesh) {
  60290. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  60291. if (_this.vertices[ii].position.equals(positionToSearch)) {
  60292. return _this.vertices[ii];
  60293. }
  60294. }
  60295. }
  60296. return null;
  60297. };
  60298. var vertexReferences = [];
  60299. var vertexInit = function (i) {
  60300. var offset = i + submesh.verticesStart;
  60301. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  60302. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  60303. vertex.originalOffsets.push(offset);
  60304. if (vertex.id === _this.vertices.length) {
  60305. _this.vertices.push(vertex);
  60306. }
  60307. vertexReferences.push(vertex.id);
  60308. };
  60309. //var totalVertices = mesh.getTotalVertices();
  60310. var totalVertices = submesh.verticesCount;
  60311. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  60312. var indicesInit = function (i) {
  60313. var offset = (submesh.indexStart / 3) + i;
  60314. var pos = (offset * 3);
  60315. var i0 = indices[pos + 0];
  60316. var i1 = indices[pos + 1];
  60317. var i2 = indices[pos + 2];
  60318. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  60319. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  60320. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  60321. var triangle = new DecimationTriangle([v0, v1, v2]);
  60322. triangle.originalOffset = pos;
  60323. _this.triangles.push(triangle);
  60324. };
  60325. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  60326. _this.init(callback);
  60327. });
  60328. });
  60329. };
  60330. QuadraticErrorSimplification.prototype.init = function (callback) {
  60331. var _this = this;
  60332. var triangleInit1 = function (i) {
  60333. var t = _this.triangles[i];
  60334. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  60335. for (var j = 0; j < 3; j++) {
  60336. 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))));
  60337. }
  60338. };
  60339. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  60340. var triangleInit2 = function (i) {
  60341. var t = _this.triangles[i];
  60342. for (var j = 0; j < 3; ++j) {
  60343. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  60344. }
  60345. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  60346. };
  60347. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  60348. _this.initialized = true;
  60349. callback();
  60350. });
  60351. });
  60352. };
  60353. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  60354. var newTriangles = [];
  60355. var i;
  60356. for (i = 0; i < this.vertices.length; ++i) {
  60357. this.vertices[i].triangleCount = 0;
  60358. }
  60359. var t;
  60360. var j;
  60361. for (i = 0; i < this.triangles.length; ++i) {
  60362. if (!this.triangles[i].deleted) {
  60363. t = this.triangles[i];
  60364. for (j = 0; j < 3; ++j) {
  60365. t.vertices[j].triangleCount = 1;
  60366. }
  60367. newTriangles.push(t);
  60368. }
  60369. }
  60370. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  60371. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  60372. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  60373. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  60374. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  60375. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  60376. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  60377. var vertexCount = 0;
  60378. for (i = 0; i < this.vertices.length; ++i) {
  60379. var vertex = this.vertices[i];
  60380. vertex.id = vertexCount;
  60381. if (vertex.triangleCount) {
  60382. vertex.originalOffsets.forEach(function (originalOffset) {
  60383. newPositionData.push(vertex.position.x);
  60384. newPositionData.push(vertex.position.y);
  60385. newPositionData.push(vertex.position.z);
  60386. newNormalData.push(normalData[originalOffset * 3]);
  60387. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  60388. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  60389. if (uvs && uvs.length) {
  60390. newUVsData.push(uvs[(originalOffset * 2)]);
  60391. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  60392. }
  60393. else if (colorsData && colorsData.length) {
  60394. newColorsData.push(colorsData[(originalOffset * 4)]);
  60395. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  60396. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  60397. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  60398. }
  60399. ++vertexCount;
  60400. });
  60401. }
  60402. }
  60403. var startingIndex = this._reconstructedMesh.getTotalIndices();
  60404. var startingVertex = this._reconstructedMesh.getTotalVertices();
  60405. var submeshesArray = this._reconstructedMesh.subMeshes;
  60406. this._reconstructedMesh.subMeshes = [];
  60407. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  60408. var originalIndices = this._mesh.getIndices();
  60409. for (i = 0; i < newTriangles.length; ++i) {
  60410. t = newTriangles[i]; //now get the new referencing point for each vertex
  60411. [0, 1, 2].forEach(function (idx) {
  60412. var id = originalIndices[t.originalOffset + idx];
  60413. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  60414. if (offset < 0)
  60415. offset = 0;
  60416. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  60417. });
  60418. }
  60419. //overwriting the old vertex buffers and indices.
  60420. this._reconstructedMesh.setIndices(newIndicesArray);
  60421. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  60422. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  60423. if (newUVsData.length > 0)
  60424. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  60425. if (newColorsData.length > 0)
  60426. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  60427. //create submesh
  60428. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  60429. if (submeshIndex > 0) {
  60430. this._reconstructedMesh.subMeshes = [];
  60431. submeshesArray.forEach(function (submesh) {
  60432. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  60433. });
  60434. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  60435. }
  60436. };
  60437. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  60438. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  60439. this._reconstructedMesh.material = this._mesh.material;
  60440. this._reconstructedMesh.parent = this._mesh.parent;
  60441. this._reconstructedMesh.isVisible = false;
  60442. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  60443. };
  60444. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  60445. for (var i = 0; i < vertex1.triangleCount; ++i) {
  60446. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  60447. if (t.deleted)
  60448. continue;
  60449. var s = this.references[vertex1.triangleStart + i].vertexId;
  60450. var v1 = t.vertices[(s + 1) % 3];
  60451. var v2 = t.vertices[(s + 2) % 3];
  60452. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  60453. deletedArray[i] = true;
  60454. delTr.push(t);
  60455. continue;
  60456. }
  60457. var d1 = v1.position.subtract(point);
  60458. d1 = d1.normalize();
  60459. var d2 = v2.position.subtract(point);
  60460. d2 = d2.normalize();
  60461. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  60462. return true;
  60463. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  60464. deletedArray[i] = false;
  60465. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  60466. return true;
  60467. }
  60468. return false;
  60469. };
  60470. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  60471. var newDeleted = deletedTriangles;
  60472. for (var i = 0; i < vertex.triangleCount; ++i) {
  60473. var ref = this.references[vertex.triangleStart + i];
  60474. var t = this.triangles[ref.triangleId];
  60475. if (t.deleted)
  60476. continue;
  60477. if (deletedArray[i] && t.deletePending) {
  60478. t.deleted = true;
  60479. newDeleted++;
  60480. continue;
  60481. }
  60482. t.vertices[ref.vertexId] = origVertex;
  60483. t.isDirty = true;
  60484. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  60485. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  60486. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  60487. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  60488. this.references.push(ref);
  60489. }
  60490. return newDeleted;
  60491. };
  60492. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  60493. for (var i = 0; i < this.vertices.length; ++i) {
  60494. var vCount = [];
  60495. var vId = [];
  60496. var v = this.vertices[i];
  60497. var j;
  60498. for (j = 0; j < v.triangleCount; ++j) {
  60499. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  60500. for (var ii = 0; ii < 3; ii++) {
  60501. var ofs = 0;
  60502. var vv = triangle.vertices[ii];
  60503. while (ofs < vCount.length) {
  60504. if (vId[ofs] === vv.id)
  60505. break;
  60506. ++ofs;
  60507. }
  60508. if (ofs === vCount.length) {
  60509. vCount.push(1);
  60510. vId.push(vv.id);
  60511. }
  60512. else {
  60513. vCount[ofs]++;
  60514. }
  60515. }
  60516. }
  60517. for (j = 0; j < vCount.length; ++j) {
  60518. if (vCount[j] === 1) {
  60519. this.vertices[vId[j]].isBorder = true;
  60520. }
  60521. else {
  60522. this.vertices[vId[j]].isBorder = false;
  60523. }
  60524. }
  60525. }
  60526. };
  60527. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  60528. if (identifyBorders === void 0) { identifyBorders = false; }
  60529. var i;
  60530. if (!identifyBorders) {
  60531. var newTrianglesVector = [];
  60532. for (i = 0; i < this.triangles.length; ++i) {
  60533. if (!this.triangles[i].deleted) {
  60534. newTrianglesVector.push(this.triangles[i]);
  60535. }
  60536. }
  60537. this.triangles = newTrianglesVector;
  60538. }
  60539. for (i = 0; i < this.vertices.length; ++i) {
  60540. this.vertices[i].triangleCount = 0;
  60541. this.vertices[i].triangleStart = 0;
  60542. }
  60543. var t;
  60544. var j;
  60545. var v;
  60546. for (i = 0; i < this.triangles.length; ++i) {
  60547. t = this.triangles[i];
  60548. for (j = 0; j < 3; ++j) {
  60549. v = t.vertices[j];
  60550. v.triangleCount++;
  60551. }
  60552. }
  60553. var tStart = 0;
  60554. for (i = 0; i < this.vertices.length; ++i) {
  60555. this.vertices[i].triangleStart = tStart;
  60556. tStart += this.vertices[i].triangleCount;
  60557. this.vertices[i].triangleCount = 0;
  60558. }
  60559. var newReferences = new Array(this.triangles.length * 3);
  60560. for (i = 0; i < this.triangles.length; ++i) {
  60561. t = this.triangles[i];
  60562. for (j = 0; j < 3; ++j) {
  60563. v = t.vertices[j];
  60564. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  60565. v.triangleCount++;
  60566. }
  60567. }
  60568. this.references = newReferences;
  60569. if (identifyBorders) {
  60570. this.identifyBorder();
  60571. }
  60572. };
  60573. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  60574. var x = point.x;
  60575. var y = point.y;
  60576. var z = point.z;
  60577. 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
  60578. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  60579. };
  60580. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  60581. var q = vertex1.q.add(vertex2.q);
  60582. var border = vertex1.isBorder && vertex2.isBorder;
  60583. var error = 0;
  60584. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  60585. if (qDet !== 0 && !border) {
  60586. if (!pointResult) {
  60587. pointResult = BABYLON.Vector3.Zero();
  60588. }
  60589. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  60590. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  60591. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  60592. error = this.vertexError(q, pointResult);
  60593. }
  60594. else {
  60595. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  60596. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  60597. var error1 = this.vertexError(q, vertex1.position);
  60598. var error2 = this.vertexError(q, vertex2.position);
  60599. var error3 = this.vertexError(q, p3);
  60600. error = Math.min(error1, error2, error3);
  60601. if (error === error1) {
  60602. if (pointResult) {
  60603. pointResult.copyFrom(vertex1.position);
  60604. }
  60605. }
  60606. else if (error === error2) {
  60607. if (pointResult) {
  60608. pointResult.copyFrom(vertex2.position);
  60609. }
  60610. }
  60611. else {
  60612. if (pointResult) {
  60613. pointResult.copyFrom(p3);
  60614. }
  60615. }
  60616. }
  60617. return error;
  60618. };
  60619. return QuadraticErrorSimplification;
  60620. }());
  60621. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  60622. })(BABYLON || (BABYLON = {}));
  60623. //# sourceMappingURL=babylon.meshSimplification.js.map
  60624. var BABYLON;
  60625. (function (BABYLON) {
  60626. var Internals;
  60627. (function (Internals) {
  60628. var MeshLODLevel = (function () {
  60629. function MeshLODLevel(distance, mesh) {
  60630. this.distance = distance;
  60631. this.mesh = mesh;
  60632. }
  60633. return MeshLODLevel;
  60634. }());
  60635. Internals.MeshLODLevel = MeshLODLevel;
  60636. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  60637. })(BABYLON || (BABYLON = {}));
  60638. //# sourceMappingURL=babylon.meshLODLevel.js.map
  60639. var BABYLON;
  60640. (function (BABYLON) {
  60641. // Standard optimizations
  60642. var SceneOptimization = (function () {
  60643. function SceneOptimization(priority) {
  60644. if (priority === void 0) { priority = 0; }
  60645. this.priority = priority;
  60646. this.apply = function (scene) {
  60647. return true; // Return true if everything that can be done was applied
  60648. };
  60649. }
  60650. return SceneOptimization;
  60651. }());
  60652. BABYLON.SceneOptimization = SceneOptimization;
  60653. var TextureOptimization = (function (_super) {
  60654. __extends(TextureOptimization, _super);
  60655. function TextureOptimization(priority, maximumSize) {
  60656. if (priority === void 0) { priority = 0; }
  60657. if (maximumSize === void 0) { maximumSize = 1024; }
  60658. var _this = _super.call(this, priority) || this;
  60659. _this.priority = priority;
  60660. _this.maximumSize = maximumSize;
  60661. _this.apply = function (scene) {
  60662. var allDone = true;
  60663. for (var index = 0; index < scene.textures.length; index++) {
  60664. var texture = scene.textures[index];
  60665. if (!texture.canRescale) {
  60666. continue;
  60667. }
  60668. var currentSize = texture.getSize();
  60669. var maxDimension = Math.max(currentSize.width, currentSize.height);
  60670. if (maxDimension > _this.maximumSize) {
  60671. texture.scale(0.5);
  60672. allDone = false;
  60673. }
  60674. }
  60675. return allDone;
  60676. };
  60677. return _this;
  60678. }
  60679. return TextureOptimization;
  60680. }(SceneOptimization));
  60681. BABYLON.TextureOptimization = TextureOptimization;
  60682. var HardwareScalingOptimization = (function (_super) {
  60683. __extends(HardwareScalingOptimization, _super);
  60684. function HardwareScalingOptimization(priority, maximumScale) {
  60685. if (priority === void 0) { priority = 0; }
  60686. if (maximumScale === void 0) { maximumScale = 2; }
  60687. var _this = _super.call(this, priority) || this;
  60688. _this.priority = priority;
  60689. _this.maximumScale = maximumScale;
  60690. _this._currentScale = 1;
  60691. _this.apply = function (scene) {
  60692. _this._currentScale++;
  60693. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  60694. return _this._currentScale >= _this.maximumScale;
  60695. };
  60696. return _this;
  60697. }
  60698. return HardwareScalingOptimization;
  60699. }(SceneOptimization));
  60700. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  60701. var ShadowsOptimization = (function (_super) {
  60702. __extends(ShadowsOptimization, _super);
  60703. function ShadowsOptimization() {
  60704. var _this = _super !== null && _super.apply(this, arguments) || this;
  60705. _this.apply = function (scene) {
  60706. scene.shadowsEnabled = false;
  60707. return true;
  60708. };
  60709. return _this;
  60710. }
  60711. return ShadowsOptimization;
  60712. }(SceneOptimization));
  60713. BABYLON.ShadowsOptimization = ShadowsOptimization;
  60714. var PostProcessesOptimization = (function (_super) {
  60715. __extends(PostProcessesOptimization, _super);
  60716. function PostProcessesOptimization() {
  60717. var _this = _super !== null && _super.apply(this, arguments) || this;
  60718. _this.apply = function (scene) {
  60719. scene.postProcessesEnabled = false;
  60720. return true;
  60721. };
  60722. return _this;
  60723. }
  60724. return PostProcessesOptimization;
  60725. }(SceneOptimization));
  60726. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  60727. var LensFlaresOptimization = (function (_super) {
  60728. __extends(LensFlaresOptimization, _super);
  60729. function LensFlaresOptimization() {
  60730. var _this = _super !== null && _super.apply(this, arguments) || this;
  60731. _this.apply = function (scene) {
  60732. scene.lensFlaresEnabled = false;
  60733. return true;
  60734. };
  60735. return _this;
  60736. }
  60737. return LensFlaresOptimization;
  60738. }(SceneOptimization));
  60739. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  60740. var ParticlesOptimization = (function (_super) {
  60741. __extends(ParticlesOptimization, _super);
  60742. function ParticlesOptimization() {
  60743. var _this = _super !== null && _super.apply(this, arguments) || this;
  60744. _this.apply = function (scene) {
  60745. scene.particlesEnabled = false;
  60746. return true;
  60747. };
  60748. return _this;
  60749. }
  60750. return ParticlesOptimization;
  60751. }(SceneOptimization));
  60752. BABYLON.ParticlesOptimization = ParticlesOptimization;
  60753. var RenderTargetsOptimization = (function (_super) {
  60754. __extends(RenderTargetsOptimization, _super);
  60755. function RenderTargetsOptimization() {
  60756. var _this = _super !== null && _super.apply(this, arguments) || this;
  60757. _this.apply = function (scene) {
  60758. scene.renderTargetsEnabled = false;
  60759. return true;
  60760. };
  60761. return _this;
  60762. }
  60763. return RenderTargetsOptimization;
  60764. }(SceneOptimization));
  60765. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  60766. var MergeMeshesOptimization = (function (_super) {
  60767. __extends(MergeMeshesOptimization, _super);
  60768. function MergeMeshesOptimization() {
  60769. var _this = _super !== null && _super.apply(this, arguments) || this;
  60770. _this._canBeMerged = function (abstractMesh) {
  60771. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  60772. return false;
  60773. }
  60774. var mesh = abstractMesh;
  60775. if (!mesh.isVisible || !mesh.isEnabled()) {
  60776. return false;
  60777. }
  60778. if (mesh.instances.length > 0) {
  60779. return false;
  60780. }
  60781. if (mesh.skeleton || mesh.hasLODLevels) {
  60782. return false;
  60783. }
  60784. if (mesh.parent) {
  60785. return false;
  60786. }
  60787. return true;
  60788. };
  60789. _this.apply = function (scene, updateSelectionTree) {
  60790. var globalPool = scene.meshes.slice(0);
  60791. var globalLength = globalPool.length;
  60792. for (var index = 0; index < globalLength; index++) {
  60793. var currentPool = new Array();
  60794. var current = globalPool[index];
  60795. // Checks
  60796. if (!_this._canBeMerged(current)) {
  60797. continue;
  60798. }
  60799. currentPool.push(current);
  60800. // Find compatible meshes
  60801. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  60802. var otherMesh = globalPool[subIndex];
  60803. if (!_this._canBeMerged(otherMesh)) {
  60804. continue;
  60805. }
  60806. if (otherMesh.material !== current.material) {
  60807. continue;
  60808. }
  60809. if (otherMesh.checkCollisions !== current.checkCollisions) {
  60810. continue;
  60811. }
  60812. currentPool.push(otherMesh);
  60813. globalLength--;
  60814. globalPool.splice(subIndex, 1);
  60815. subIndex--;
  60816. }
  60817. if (currentPool.length < 2) {
  60818. continue;
  60819. }
  60820. // Merge meshes
  60821. BABYLON.Mesh.MergeMeshes(currentPool);
  60822. }
  60823. if (updateSelectionTree != undefined) {
  60824. if (updateSelectionTree) {
  60825. scene.createOrUpdateSelectionOctree();
  60826. }
  60827. }
  60828. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  60829. scene.createOrUpdateSelectionOctree();
  60830. }
  60831. return true;
  60832. };
  60833. return _this;
  60834. }
  60835. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  60836. get: function () {
  60837. return MergeMeshesOptimization._UpdateSelectionTree;
  60838. },
  60839. set: function (value) {
  60840. MergeMeshesOptimization._UpdateSelectionTree = value;
  60841. },
  60842. enumerable: true,
  60843. configurable: true
  60844. });
  60845. return MergeMeshesOptimization;
  60846. }(SceneOptimization));
  60847. MergeMeshesOptimization._UpdateSelectionTree = false;
  60848. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  60849. // Options
  60850. var SceneOptimizerOptions = (function () {
  60851. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  60852. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  60853. if (trackerDuration === void 0) { trackerDuration = 2000; }
  60854. this.targetFrameRate = targetFrameRate;
  60855. this.trackerDuration = trackerDuration;
  60856. this.optimizations = new Array();
  60857. }
  60858. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  60859. var result = new SceneOptimizerOptions(targetFrameRate);
  60860. var priority = 0;
  60861. result.optimizations.push(new MergeMeshesOptimization(priority));
  60862. result.optimizations.push(new ShadowsOptimization(priority));
  60863. result.optimizations.push(new LensFlaresOptimization(priority));
  60864. // Next priority
  60865. priority++;
  60866. result.optimizations.push(new PostProcessesOptimization(priority));
  60867. result.optimizations.push(new ParticlesOptimization(priority));
  60868. // Next priority
  60869. priority++;
  60870. result.optimizations.push(new TextureOptimization(priority, 1024));
  60871. return result;
  60872. };
  60873. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  60874. var result = new SceneOptimizerOptions(targetFrameRate);
  60875. var priority = 0;
  60876. result.optimizations.push(new MergeMeshesOptimization(priority));
  60877. result.optimizations.push(new ShadowsOptimization(priority));
  60878. result.optimizations.push(new LensFlaresOptimization(priority));
  60879. // Next priority
  60880. priority++;
  60881. result.optimizations.push(new PostProcessesOptimization(priority));
  60882. result.optimizations.push(new ParticlesOptimization(priority));
  60883. // Next priority
  60884. priority++;
  60885. result.optimizations.push(new TextureOptimization(priority, 512));
  60886. // Next priority
  60887. priority++;
  60888. result.optimizations.push(new RenderTargetsOptimization(priority));
  60889. // Next priority
  60890. priority++;
  60891. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  60892. return result;
  60893. };
  60894. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  60895. var result = new SceneOptimizerOptions(targetFrameRate);
  60896. var priority = 0;
  60897. result.optimizations.push(new MergeMeshesOptimization(priority));
  60898. result.optimizations.push(new ShadowsOptimization(priority));
  60899. result.optimizations.push(new LensFlaresOptimization(priority));
  60900. // Next priority
  60901. priority++;
  60902. result.optimizations.push(new PostProcessesOptimization(priority));
  60903. result.optimizations.push(new ParticlesOptimization(priority));
  60904. // Next priority
  60905. priority++;
  60906. result.optimizations.push(new TextureOptimization(priority, 256));
  60907. // Next priority
  60908. priority++;
  60909. result.optimizations.push(new RenderTargetsOptimization(priority));
  60910. // Next priority
  60911. priority++;
  60912. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  60913. return result;
  60914. };
  60915. return SceneOptimizerOptions;
  60916. }());
  60917. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  60918. // Scene optimizer tool
  60919. var SceneOptimizer = (function () {
  60920. function SceneOptimizer() {
  60921. }
  60922. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  60923. // TODO: add an epsilon
  60924. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  60925. if (onSuccess) {
  60926. onSuccess();
  60927. }
  60928. return;
  60929. }
  60930. // Apply current level of optimizations
  60931. var allDone = true;
  60932. var noOptimizationApplied = true;
  60933. for (var index = 0; index < options.optimizations.length; index++) {
  60934. var optimization = options.optimizations[index];
  60935. if (optimization.priority === currentPriorityLevel) {
  60936. noOptimizationApplied = false;
  60937. allDone = allDone && optimization.apply(scene);
  60938. }
  60939. }
  60940. // If no optimization was applied, this is a failure :(
  60941. if (noOptimizationApplied) {
  60942. if (onFailure) {
  60943. onFailure();
  60944. }
  60945. return;
  60946. }
  60947. // If all optimizations were done, move to next level
  60948. if (allDone) {
  60949. currentPriorityLevel++;
  60950. }
  60951. // Let's the system running for a specific amount of time before checking FPS
  60952. scene.executeWhenReady(function () {
  60953. setTimeout(function () {
  60954. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  60955. }, options.trackerDuration);
  60956. });
  60957. };
  60958. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  60959. if (!options) {
  60960. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  60961. }
  60962. // Let's the system running for a specific amount of time before checking FPS
  60963. scene.executeWhenReady(function () {
  60964. setTimeout(function () {
  60965. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  60966. }, options.trackerDuration);
  60967. });
  60968. };
  60969. return SceneOptimizer;
  60970. }());
  60971. BABYLON.SceneOptimizer = SceneOptimizer;
  60972. })(BABYLON || (BABYLON = {}));
  60973. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  60974. var BABYLON;
  60975. (function (BABYLON) {
  60976. var OutlineRenderer = (function () {
  60977. function OutlineRenderer(scene) {
  60978. this._scene = scene;
  60979. }
  60980. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  60981. var _this = this;
  60982. if (useOverlay === void 0) { useOverlay = false; }
  60983. var scene = this._scene;
  60984. var engine = this._scene.getEngine();
  60985. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  60986. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  60987. return;
  60988. }
  60989. var mesh = subMesh.getRenderingMesh();
  60990. var material = subMesh.getMaterial();
  60991. engine.enableEffect(this._effect);
  60992. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  60993. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  60994. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  60995. // Bones
  60996. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  60997. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  60998. }
  60999. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  61000. // Alpha test
  61001. if (material && material.needAlphaTesting()) {
  61002. var alphaTexture = material.getAlphaTestTexture();
  61003. this._effect.setTexture("diffuseSampler", alphaTexture);
  61004. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  61005. }
  61006. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  61007. };
  61008. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  61009. var defines = [];
  61010. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  61011. var mesh = subMesh.getMesh();
  61012. var material = subMesh.getMaterial();
  61013. // Alpha test
  61014. if (material && material.needAlphaTesting()) {
  61015. defines.push("#define ALPHATEST");
  61016. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  61017. attribs.push(BABYLON.VertexBuffer.UVKind);
  61018. defines.push("#define UV1");
  61019. }
  61020. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  61021. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  61022. defines.push("#define UV2");
  61023. }
  61024. }
  61025. // Bones
  61026. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  61027. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  61028. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  61029. if (mesh.numBoneInfluencers > 4) {
  61030. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  61031. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  61032. }
  61033. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  61034. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  61035. }
  61036. else {
  61037. defines.push("#define NUM_BONE_INFLUENCERS 0");
  61038. }
  61039. // Instances
  61040. if (useInstances) {
  61041. defines.push("#define INSTANCES");
  61042. attribs.push("world0");
  61043. attribs.push("world1");
  61044. attribs.push("world2");
  61045. attribs.push("world3");
  61046. }
  61047. // Get correct effect
  61048. var join = defines.join("\n");
  61049. if (this._cachedDefines !== join) {
  61050. this._cachedDefines = join;
  61051. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  61052. }
  61053. return this._effect.isReady();
  61054. };
  61055. return OutlineRenderer;
  61056. }());
  61057. BABYLON.OutlineRenderer = OutlineRenderer;
  61058. })(BABYLON || (BABYLON = {}));
  61059. //# sourceMappingURL=babylon.outlineRenderer.js.map
  61060. var BABYLON;
  61061. (function (BABYLON) {
  61062. var FaceAdjacencies = (function () {
  61063. function FaceAdjacencies() {
  61064. this.edges = new Array();
  61065. this.edgesConnectedCount = 0;
  61066. }
  61067. return FaceAdjacencies;
  61068. }());
  61069. var EdgesRenderer = (function () {
  61070. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  61071. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  61072. if (epsilon === void 0) { epsilon = 0.95; }
  61073. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  61074. this.edgesWidthScalerForOrthographic = 1000.0;
  61075. this.edgesWidthScalerForPerspective = 50.0;
  61076. this._linesPositions = new Array();
  61077. this._linesNormals = new Array();
  61078. this._linesIndices = new Array();
  61079. this._buffers = {};
  61080. this._checkVerticesInsteadOfIndices = false;
  61081. this._source = source;
  61082. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  61083. this._epsilon = epsilon;
  61084. this._prepareRessources();
  61085. this._generateEdgesLines();
  61086. }
  61087. EdgesRenderer.prototype._prepareRessources = function () {
  61088. if (this._lineShader) {
  61089. return;
  61090. }
  61091. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  61092. attributes: ["position", "normal"],
  61093. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  61094. });
  61095. this._lineShader.disableDepthWrite = true;
  61096. this._lineShader.backFaceCulling = false;
  61097. };
  61098. EdgesRenderer.prototype.dispose = function () {
  61099. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  61100. if (buffer) {
  61101. buffer.dispose();
  61102. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  61103. }
  61104. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  61105. if (buffer) {
  61106. buffer.dispose();
  61107. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  61108. }
  61109. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  61110. this._lineShader.dispose();
  61111. };
  61112. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  61113. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  61114. return 0;
  61115. }
  61116. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  61117. return 1;
  61118. }
  61119. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  61120. return 2;
  61121. }
  61122. return -1;
  61123. };
  61124. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  61125. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  61126. return 0;
  61127. }
  61128. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  61129. return 1;
  61130. }
  61131. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  61132. return 2;
  61133. }
  61134. return -1;
  61135. };
  61136. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  61137. var needToCreateLine;
  61138. if (edge === undefined) {
  61139. needToCreateLine = true;
  61140. }
  61141. else {
  61142. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  61143. needToCreateLine = dotProduct < this._epsilon;
  61144. }
  61145. if (needToCreateLine) {
  61146. var offset = this._linesPositions.length / 3;
  61147. var normal = p0.subtract(p1);
  61148. normal.normalize();
  61149. // Positions
  61150. this._linesPositions.push(p0.x);
  61151. this._linesPositions.push(p0.y);
  61152. this._linesPositions.push(p0.z);
  61153. this._linesPositions.push(p0.x);
  61154. this._linesPositions.push(p0.y);
  61155. this._linesPositions.push(p0.z);
  61156. this._linesPositions.push(p1.x);
  61157. this._linesPositions.push(p1.y);
  61158. this._linesPositions.push(p1.z);
  61159. this._linesPositions.push(p1.x);
  61160. this._linesPositions.push(p1.y);
  61161. this._linesPositions.push(p1.z);
  61162. // Normals
  61163. this._linesNormals.push(p1.x);
  61164. this._linesNormals.push(p1.y);
  61165. this._linesNormals.push(p1.z);
  61166. this._linesNormals.push(-1);
  61167. this._linesNormals.push(p1.x);
  61168. this._linesNormals.push(p1.y);
  61169. this._linesNormals.push(p1.z);
  61170. this._linesNormals.push(1);
  61171. this._linesNormals.push(p0.x);
  61172. this._linesNormals.push(p0.y);
  61173. this._linesNormals.push(p0.z);
  61174. this._linesNormals.push(-1);
  61175. this._linesNormals.push(p0.x);
  61176. this._linesNormals.push(p0.y);
  61177. this._linesNormals.push(p0.z);
  61178. this._linesNormals.push(1);
  61179. // Indices
  61180. this._linesIndices.push(offset);
  61181. this._linesIndices.push(offset + 1);
  61182. this._linesIndices.push(offset + 2);
  61183. this._linesIndices.push(offset);
  61184. this._linesIndices.push(offset + 2);
  61185. this._linesIndices.push(offset + 3);
  61186. }
  61187. };
  61188. EdgesRenderer.prototype._generateEdgesLines = function () {
  61189. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61190. var indices = this._source.getIndices();
  61191. // First let's find adjacencies
  61192. var adjacencies = new Array();
  61193. var faceNormals = new Array();
  61194. var index;
  61195. var faceAdjacencies;
  61196. // Prepare faces
  61197. for (index = 0; index < indices.length; index += 3) {
  61198. faceAdjacencies = new FaceAdjacencies();
  61199. var p0Index = indices[index];
  61200. var p1Index = indices[index + 1];
  61201. var p2Index = indices[index + 2];
  61202. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  61203. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  61204. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  61205. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  61206. faceNormal.normalize();
  61207. faceNormals.push(faceNormal);
  61208. adjacencies.push(faceAdjacencies);
  61209. }
  61210. // Scan
  61211. for (index = 0; index < adjacencies.length; index++) {
  61212. faceAdjacencies = adjacencies[index];
  61213. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  61214. var otherFaceAdjacencies = adjacencies[otherIndex];
  61215. if (faceAdjacencies.edgesConnectedCount === 3) {
  61216. break;
  61217. }
  61218. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  61219. continue;
  61220. }
  61221. var otherP0 = indices[otherIndex * 3];
  61222. var otherP1 = indices[otherIndex * 3 + 1];
  61223. var otherP2 = indices[otherIndex * 3 + 2];
  61224. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  61225. var otherEdgeIndex;
  61226. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  61227. continue;
  61228. }
  61229. switch (edgeIndex) {
  61230. case 0:
  61231. if (this._checkVerticesInsteadOfIndices) {
  61232. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  61233. }
  61234. else {
  61235. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  61236. }
  61237. break;
  61238. case 1:
  61239. if (this._checkVerticesInsteadOfIndices) {
  61240. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  61241. }
  61242. else {
  61243. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  61244. }
  61245. break;
  61246. case 2:
  61247. if (this._checkVerticesInsteadOfIndices) {
  61248. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  61249. }
  61250. else {
  61251. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  61252. }
  61253. break;
  61254. }
  61255. if (otherEdgeIndex === -1) {
  61256. continue;
  61257. }
  61258. faceAdjacencies.edges[edgeIndex] = otherIndex;
  61259. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  61260. faceAdjacencies.edgesConnectedCount++;
  61261. otherFaceAdjacencies.edgesConnectedCount++;
  61262. if (faceAdjacencies.edgesConnectedCount === 3) {
  61263. break;
  61264. }
  61265. }
  61266. }
  61267. }
  61268. // Create lines
  61269. for (index = 0; index < adjacencies.length; index++) {
  61270. // 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
  61271. var current = adjacencies[index];
  61272. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  61273. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  61274. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  61275. }
  61276. // Merge into a single mesh
  61277. var engine = this._source.getScene().getEngine();
  61278. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  61279. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  61280. this._ib = engine.createIndexBuffer(this._linesIndices);
  61281. this._indicesCount = this._linesIndices.length;
  61282. };
  61283. EdgesRenderer.prototype.render = function () {
  61284. if (!this._lineShader.isReady()) {
  61285. return;
  61286. }
  61287. var scene = this._source.getScene();
  61288. var engine = scene.getEngine();
  61289. this._lineShader._preBind();
  61290. // VBOs
  61291. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  61292. scene.resetCachedMaterial();
  61293. this._lineShader.setColor4("color", this._source.edgesColor);
  61294. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  61295. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  61296. }
  61297. else {
  61298. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  61299. }
  61300. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  61301. this._lineShader.bind(this._source.getWorldMatrix());
  61302. // Draw order
  61303. engine.draw(true, 0, this._indicesCount);
  61304. this._lineShader.unbind();
  61305. engine.setDepthWrite(true);
  61306. };
  61307. return EdgesRenderer;
  61308. }());
  61309. BABYLON.EdgesRenderer = EdgesRenderer;
  61310. })(BABYLON || (BABYLON = {}));
  61311. //# sourceMappingURL=babylon.edgesRenderer.js.map
  61312. /// <reference path="..\PostProcess\babylon.postProcess.ts" />
  61313. /// <reference path="..\Math\babylon.math.ts" />
  61314. var BABYLON;
  61315. (function (BABYLON) {
  61316. /**
  61317. * Special Glow Blur post process only blurring the alpha channel
  61318. * It enforces keeping the most luminous color in the color channel.
  61319. */
  61320. var GlowBlurPostProcess = (function (_super) {
  61321. __extends(GlowBlurPostProcess, _super);
  61322. function GlowBlurPostProcess(name, direction, blurWidth, options, camera, samplingMode, engine, reusable) {
  61323. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  61324. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  61325. _this.direction = direction;
  61326. _this.blurWidth = blurWidth;
  61327. _this.onApplyObservable.add(function (effect) {
  61328. effect.setFloat2("screenSize", _this.width, _this.height);
  61329. effect.setVector2("direction", _this.direction);
  61330. effect.setFloat("blurWidth", _this.blurWidth);
  61331. });
  61332. return _this;
  61333. }
  61334. return GlowBlurPostProcess;
  61335. }(BABYLON.PostProcess));
  61336. /**
  61337. * The highlight layer Helps adding a glow effect around a mesh.
  61338. *
  61339. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  61340. * glowy meshes to your scene.
  61341. *
  61342. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  61343. */
  61344. var HighlightLayer = (function () {
  61345. /**
  61346. * Instantiates a new highlight Layer and references it to the scene..
  61347. * @param name The name of the layer
  61348. * @param scene The scene to use the layer in
  61349. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  61350. */
  61351. function HighlightLayer(name, scene, options) {
  61352. this.name = name;
  61353. this._vertexBuffers = {};
  61354. this._mainTextureDesiredSize = { width: 0, height: 0 };
  61355. this._meshes = {};
  61356. this._maxSize = 0;
  61357. this._shouldRender = false;
  61358. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  61359. this._excludedMeshes = {};
  61360. /**
  61361. * Specifies whether or not the inner glow is ACTIVE in the layer.
  61362. */
  61363. this.innerGlow = true;
  61364. /**
  61365. * Specifies whether or not the outer glow is ACTIVE in the layer.
  61366. */
  61367. this.outerGlow = true;
  61368. /**
  61369. * Specifies wether the highlight layer is enabled or not.
  61370. */
  61371. this.isEnabled = true;
  61372. /**
  61373. * An event triggered when the highlight layer has been disposed.
  61374. * @type {BABYLON.Observable}
  61375. */
  61376. this.onDisposeObservable = new BABYLON.Observable();
  61377. /**
  61378. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  61379. * @type {BABYLON.Observable}
  61380. */
  61381. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  61382. /**
  61383. * An event triggered when the highlight layer is being blurred.
  61384. * @type {BABYLON.Observable}
  61385. */
  61386. this.onBeforeBlurObservable = new BABYLON.Observable();
  61387. /**
  61388. * An event triggered when the highlight layer has been blurred.
  61389. * @type {BABYLON.Observable}
  61390. */
  61391. this.onAfterBlurObservable = new BABYLON.Observable();
  61392. /**
  61393. * An event triggered when the glowing blurred texture is being merged in the scene.
  61394. * @type {BABYLON.Observable}
  61395. */
  61396. this.onBeforeComposeObservable = new BABYLON.Observable();
  61397. /**
  61398. * An event triggered when the glowing blurred texture has been merged in the scene.
  61399. * @type {BABYLON.Observable}
  61400. */
  61401. this.onAfterComposeObservable = new BABYLON.Observable();
  61402. /**
  61403. * An event triggered when the highlight layer changes its size.
  61404. * @type {BABYLON.Observable}
  61405. */
  61406. this.onSizeChangedObservable = new BABYLON.Observable();
  61407. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  61408. var engine = scene.getEngine();
  61409. this._engine = engine;
  61410. this._maxSize = this._engine.getCaps().maxTextureSize;
  61411. this._scene.highlightLayers.push(this);
  61412. // Warn on stencil.
  61413. if (!this._engine.isStencilEnable) {
  61414. 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 }");
  61415. }
  61416. // Adapt options
  61417. this._options = options || {
  61418. mainTextureRatio: 0.25,
  61419. blurTextureSizeRatio: 0.5,
  61420. blurHorizontalSize: 1,
  61421. blurVerticalSize: 1,
  61422. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE
  61423. };
  61424. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.25;
  61425. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 0.5;
  61426. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  61427. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  61428. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  61429. // VBO
  61430. var vertices = [];
  61431. vertices.push(1, 1);
  61432. vertices.push(-1, 1);
  61433. vertices.push(-1, -1);
  61434. vertices.push(1, -1);
  61435. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  61436. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  61437. // Indices
  61438. var indices = [];
  61439. indices.push(0);
  61440. indices.push(1);
  61441. indices.push(2);
  61442. indices.push(0);
  61443. indices.push(2);
  61444. indices.push(3);
  61445. this._indexBuffer = engine.createIndexBuffer(indices);
  61446. // Effect
  61447. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], "");
  61448. // Render target
  61449. this.setMainTextureSize();
  61450. // Create Textures and post processes
  61451. this.createTextureAndPostProcesses();
  61452. }
  61453. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  61454. /**
  61455. * Gets the horizontal size of the blur.
  61456. */
  61457. get: function () {
  61458. return this._horizontalBlurPostprocess.blurWidth;
  61459. },
  61460. /**
  61461. * Specifies the horizontal size of the blur.
  61462. */
  61463. set: function (value) {
  61464. this._horizontalBlurPostprocess.blurWidth = value;
  61465. },
  61466. enumerable: true,
  61467. configurable: true
  61468. });
  61469. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  61470. /**
  61471. * Gets the vertical size of the blur.
  61472. */
  61473. get: function () {
  61474. return this._verticalBlurPostprocess.blurWidth;
  61475. },
  61476. /**
  61477. * Specifies the vertical size of the blur.
  61478. */
  61479. set: function (value) {
  61480. this._verticalBlurPostprocess.blurWidth = value;
  61481. },
  61482. enumerable: true,
  61483. configurable: true
  61484. });
  61485. Object.defineProperty(HighlightLayer.prototype, "camera", {
  61486. /**
  61487. * Gets the camera attached to the layer.
  61488. */
  61489. get: function () {
  61490. return this._options.camera;
  61491. },
  61492. enumerable: true,
  61493. configurable: true
  61494. });
  61495. /**
  61496. * Creates the render target textures and post processes used in the highlight layer.
  61497. */
  61498. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  61499. var _this = this;
  61500. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  61501. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  61502. blurTextureWidth = BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize);
  61503. blurTextureHeight = BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize);
  61504. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  61505. width: this._mainTextureDesiredSize.width,
  61506. height: this._mainTextureDesiredSize.height
  61507. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  61508. this._mainTexture.activeCamera = this._options.camera;
  61509. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61510. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61511. this._mainTexture.anisotropicFilteringLevel = 1;
  61512. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  61513. this._mainTexture.renderParticles = false;
  61514. this._mainTexture.renderList = null;
  61515. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  61516. width: blurTextureWidth,
  61517. height: blurTextureHeight
  61518. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  61519. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61520. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61521. this._blurTexture.anisotropicFilteringLevel = 16;
  61522. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  61523. this._blurTexture.renderParticles = false;
  61524. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  61525. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  61526. effect.setTexture("textureSampler", _this._mainTexture);
  61527. });
  61528. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  61529. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  61530. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  61531. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  61532. });
  61533. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  61534. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  61535. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  61536. });
  61537. }
  61538. else {
  61539. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  61540. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  61541. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  61542. });
  61543. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  61544. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  61545. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  61546. });
  61547. }
  61548. this._mainTexture.onAfterUnbindObservable.add(function () {
  61549. _this.onBeforeBlurObservable.notifyObservers(_this);
  61550. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], _this._blurTexture.getInternalTexture());
  61551. _this.onAfterBlurObservable.notifyObservers(_this);
  61552. });
  61553. // Custom render function
  61554. var renderSubMesh = function (subMesh) {
  61555. var mesh = subMesh.getRenderingMesh();
  61556. var scene = _this._scene;
  61557. var engine = scene.getEngine();
  61558. // Culling
  61559. engine.setState(subMesh.getMaterial().backFaceCulling);
  61560. // Managing instances
  61561. var batch = mesh._getInstancesRenderList(subMesh._id);
  61562. if (batch.mustReturn) {
  61563. return;
  61564. }
  61565. // Excluded Mesh
  61566. if (_this._excludedMeshes[mesh.uniqueId]) {
  61567. return;
  61568. }
  61569. ;
  61570. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  61571. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  61572. var material = subMesh.getMaterial();
  61573. var emissiveTexture = null;
  61574. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  61575. emissiveTexture = material.emissiveTexture;
  61576. }
  61577. if (_this.isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  61578. engine.enableEffect(_this._glowMapGenerationEffect);
  61579. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  61580. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  61581. if (highlightLayerMesh) {
  61582. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  61583. }
  61584. else {
  61585. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  61586. }
  61587. // Alpha test
  61588. if (material && material.needAlphaTesting()) {
  61589. var alphaTexture = material.getAlphaTestTexture();
  61590. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  61591. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  61592. }
  61593. // Glow emissive only
  61594. if (emissiveTexture) {
  61595. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  61596. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  61597. }
  61598. // Bones
  61599. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  61600. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  61601. }
  61602. // Draw
  61603. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  61604. }
  61605. else {
  61606. // Need to reset refresh rate of the shadowMap
  61607. _this._mainTexture.resetRefreshCounter();
  61608. }
  61609. };
  61610. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  61611. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  61612. var index;
  61613. for (index = 0; index < opaqueSubMeshes.length; index++) {
  61614. renderSubMesh(opaqueSubMeshes.data[index]);
  61615. }
  61616. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  61617. renderSubMesh(alphaTestSubMeshes.data[index]);
  61618. }
  61619. for (index = 0; index < transparentSubMeshes.length; index++) {
  61620. renderSubMesh(transparentSubMeshes.data[index]);
  61621. }
  61622. };
  61623. this._mainTexture.onClearObservable.add(function (engine) {
  61624. engine.clear(HighlightLayer.neutralColor, true, true, true);
  61625. });
  61626. };
  61627. /**
  61628. * Checks for the readiness of the element composing the layer.
  61629. * @param subMesh the mesh to check for
  61630. * @param useInstances specify wether or not to use instances to render the mesh
  61631. * @param emissiveTexture the associated emissive texture used to generate the glow
  61632. * @return true if ready otherwise, false
  61633. */
  61634. HighlightLayer.prototype.isReady = function (subMesh, useInstances, emissiveTexture) {
  61635. if (!subMesh.getMaterial().isReady(subMesh.getMesh(), useInstances)) {
  61636. return false;
  61637. }
  61638. var defines = [];
  61639. var attribs = [BABYLON.VertexBuffer.PositionKind];
  61640. var mesh = subMesh.getMesh();
  61641. var material = subMesh.getMaterial();
  61642. var uv1 = false;
  61643. var uv2 = false;
  61644. // Alpha test
  61645. if (material && material.needAlphaTesting()) {
  61646. var alphaTexture = material.getAlphaTestTexture();
  61647. if (alphaTexture) {
  61648. defines.push("#define ALPHATEST");
  61649. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  61650. alphaTexture.coordinatesIndex === 1) {
  61651. defines.push("#define DIFFUSEUV2");
  61652. uv2 = true;
  61653. }
  61654. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  61655. defines.push("#define DIFFUSEUV1");
  61656. uv1 = true;
  61657. }
  61658. }
  61659. }
  61660. // Emissive
  61661. if (emissiveTexture) {
  61662. defines.push("#define EMISSIVE");
  61663. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  61664. emissiveTexture.coordinatesIndex === 1) {
  61665. defines.push("#define EMISSIVEUV2");
  61666. uv2 = true;
  61667. }
  61668. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  61669. defines.push("#define EMISSIVEUV1");
  61670. uv1 = true;
  61671. }
  61672. }
  61673. if (uv1) {
  61674. attribs.push(BABYLON.VertexBuffer.UVKind);
  61675. defines.push("#define UV1");
  61676. }
  61677. if (uv2) {
  61678. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  61679. defines.push("#define UV2");
  61680. }
  61681. // Bones
  61682. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  61683. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  61684. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  61685. if (mesh.numBoneInfluencers > 4) {
  61686. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  61687. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  61688. }
  61689. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  61690. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  61691. }
  61692. else {
  61693. defines.push("#define NUM_BONE_INFLUENCERS 0");
  61694. }
  61695. // Instances
  61696. if (useInstances) {
  61697. defines.push("#define INSTANCES");
  61698. attribs.push("world0");
  61699. attribs.push("world1");
  61700. attribs.push("world2");
  61701. attribs.push("world3");
  61702. }
  61703. // Get correct effect
  61704. var join = defines.join("\n");
  61705. if (this._cachedDefines !== join) {
  61706. this._cachedDefines = join;
  61707. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  61708. }
  61709. return this._glowMapGenerationEffect.isReady();
  61710. };
  61711. /**
  61712. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  61713. */
  61714. HighlightLayer.prototype.render = function () {
  61715. var currentEffect = this._glowMapMergeEffect;
  61716. // Check
  61717. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  61718. return;
  61719. var engine = this._scene.getEngine();
  61720. this.onBeforeComposeObservable.notifyObservers(this);
  61721. // Render
  61722. engine.enableEffect(currentEffect);
  61723. engine.setState(false);
  61724. // Cache
  61725. var previousStencilBuffer = engine.getStencilBuffer();
  61726. var previousStencilFunction = engine.getStencilFunction();
  61727. var previousStencilMask = engine.getStencilMask();
  61728. var previousAlphaMode = engine.getAlphaMode();
  61729. // Texture
  61730. currentEffect.setTexture("textureSampler", this._blurTexture);
  61731. // VBOs
  61732. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  61733. // Draw order
  61734. engine.setAlphaMode(this._options.alphaBlendingMode);
  61735. engine.setStencilMask(0x00);
  61736. engine.setStencilBuffer(true);
  61737. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  61738. if (this.outerGlow) {
  61739. currentEffect.setFloat("offset", 0);
  61740. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  61741. engine.draw(true, 0, 6);
  61742. }
  61743. if (this.innerGlow) {
  61744. currentEffect.setFloat("offset", 1);
  61745. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  61746. engine.draw(true, 0, 6);
  61747. }
  61748. // Restore Cache
  61749. engine.setStencilFunction(previousStencilFunction);
  61750. engine.setStencilMask(previousStencilMask);
  61751. engine.setAlphaMode(previousAlphaMode);
  61752. engine.setStencilBuffer(previousStencilBuffer);
  61753. this.onAfterComposeObservable.notifyObservers(this);
  61754. // Handle size changes.
  61755. var size = this._mainTexture.getSize();
  61756. this.setMainTextureSize();
  61757. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  61758. // Recreate RTT and post processes on size change.
  61759. this.onSizeChangedObservable.notifyObservers(this);
  61760. this.disposeTextureAndPostProcesses();
  61761. this.createTextureAndPostProcesses();
  61762. }
  61763. };
  61764. /**
  61765. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  61766. * @param mesh The mesh to exclude from the highlight layer
  61767. */
  61768. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  61769. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  61770. if (!meshExcluded) {
  61771. this._excludedMeshes[mesh.uniqueId] = {
  61772. mesh: mesh,
  61773. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  61774. mesh.getEngine().setStencilBuffer(false);
  61775. }),
  61776. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  61777. mesh.getEngine().setStencilBuffer(true);
  61778. }),
  61779. };
  61780. }
  61781. };
  61782. /**
  61783. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  61784. * @param mesh The mesh to highlight
  61785. */
  61786. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  61787. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  61788. if (meshExcluded) {
  61789. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  61790. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  61791. }
  61792. this._excludedMeshes[mesh.uniqueId] = undefined;
  61793. };
  61794. /**
  61795. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  61796. * @param mesh The mesh to highlight
  61797. * @param color The color of the highlight
  61798. * @param glowEmissiveOnly Extract the glow from the emissive texture
  61799. */
  61800. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  61801. var _this = this;
  61802. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  61803. var meshHighlight = this._meshes[mesh.uniqueId];
  61804. if (meshHighlight) {
  61805. meshHighlight.color = color;
  61806. }
  61807. else {
  61808. this._meshes[mesh.uniqueId] = {
  61809. mesh: mesh,
  61810. color: color,
  61811. // Lambda required for capture due to Observable this context
  61812. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  61813. if (_this._excludedMeshes[mesh.uniqueId]) {
  61814. _this.defaultStencilReference(mesh);
  61815. }
  61816. else {
  61817. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  61818. }
  61819. }),
  61820. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  61821. glowEmissiveOnly: glowEmissiveOnly
  61822. };
  61823. }
  61824. this._shouldRender = true;
  61825. };
  61826. /**
  61827. * Remove a mesh from the highlight layer in order to make it stop glowing.
  61828. * @param mesh The mesh to highlight
  61829. */
  61830. HighlightLayer.prototype.removeMesh = function (mesh) {
  61831. var meshHighlight = this._meshes[mesh.uniqueId];
  61832. if (meshHighlight) {
  61833. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  61834. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  61835. }
  61836. this._meshes[mesh.uniqueId] = undefined;
  61837. this._shouldRender = false;
  61838. for (var meshHighlightToCheck in this._meshes) {
  61839. if (meshHighlightToCheck) {
  61840. this._shouldRender = true;
  61841. break;
  61842. }
  61843. }
  61844. };
  61845. /**
  61846. * Returns true if the layer contains information to display, otherwise false.
  61847. */
  61848. HighlightLayer.prototype.shouldRender = function () {
  61849. return this.isEnabled && this._shouldRender;
  61850. };
  61851. /**
  61852. * Sets the main texture desired size which is the closest power of two
  61853. * of the engine canvas size.
  61854. */
  61855. HighlightLayer.prototype.setMainTextureSize = function () {
  61856. if (this._options.mainTextureFixedSize) {
  61857. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  61858. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  61859. }
  61860. else {
  61861. this._mainTextureDesiredSize.width = this._engine.getRenderingCanvas().width * this._options.mainTextureRatio;
  61862. this._mainTextureDesiredSize.height = this._engine.getRenderingCanvas().height * this._options.mainTextureRatio;
  61863. this._mainTextureDesiredSize.width = BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize);
  61864. this._mainTextureDesiredSize.height = BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize);
  61865. }
  61866. };
  61867. /**
  61868. * Force the stencil to the normal expected value for none glowing parts
  61869. */
  61870. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  61871. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  61872. };
  61873. /**
  61874. * Dispose only the render target textures and post process.
  61875. */
  61876. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  61877. this._blurTexture.dispose();
  61878. this._mainTexture.dispose();
  61879. this._downSamplePostprocess.dispose();
  61880. this._horizontalBlurPostprocess.dispose();
  61881. this._verticalBlurPostprocess.dispose();
  61882. };
  61883. /**
  61884. * Dispose the highlight layer and free resources.
  61885. */
  61886. HighlightLayer.prototype.dispose = function () {
  61887. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  61888. if (vertexBuffer) {
  61889. vertexBuffer.dispose();
  61890. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  61891. }
  61892. if (this._indexBuffer) {
  61893. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  61894. this._indexBuffer = null;
  61895. }
  61896. // Clean textures and post processes
  61897. this.disposeTextureAndPostProcesses();
  61898. // Clean mesh references
  61899. for (var id in this._meshes) {
  61900. var meshHighlight = this._meshes[id];
  61901. if (meshHighlight && meshHighlight.mesh) {
  61902. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  61903. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  61904. }
  61905. }
  61906. this._meshes = null;
  61907. for (var id in this._excludedMeshes) {
  61908. var meshHighlight = this._excludedMeshes[id];
  61909. if (meshHighlight) {
  61910. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  61911. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  61912. }
  61913. }
  61914. this._excludedMeshes = null;
  61915. // Remove from scene
  61916. var index = this._scene.highlightLayers.indexOf(this, 0);
  61917. if (index > -1) {
  61918. this._scene.highlightLayers.splice(index, 1);
  61919. }
  61920. // Callback
  61921. this.onDisposeObservable.notifyObservers(this);
  61922. this.onDisposeObservable.clear();
  61923. this.onBeforeRenderMainTextureObservable.clear();
  61924. this.onBeforeBlurObservable.clear();
  61925. this.onBeforeComposeObservable.clear();
  61926. this.onAfterComposeObservable.clear();
  61927. this.onSizeChangedObservable.clear();
  61928. };
  61929. return HighlightLayer;
  61930. }());
  61931. /**
  61932. * The neutral color used during the preparation of the glow effect.
  61933. * This is black by default as the blend operation is a blend operation.
  61934. */
  61935. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  61936. /**
  61937. * Stencil value used for glowing meshes.
  61938. */
  61939. HighlightLayer.glowingMeshStencilReference = 0x02;
  61940. /**
  61941. * Stencil value used for the other meshes in the scene.
  61942. */
  61943. HighlightLayer.normalMeshStencilReference = 0x01;
  61944. BABYLON.HighlightLayer = HighlightLayer;
  61945. })(BABYLON || (BABYLON = {}));
  61946. //# sourceMappingURL=babylon.highlightlayer.js.map
  61947. var BABYLON;
  61948. (function (BABYLON) {
  61949. var MeshAssetTask = (function () {
  61950. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  61951. this.name = name;
  61952. this.meshesNames = meshesNames;
  61953. this.rootUrl = rootUrl;
  61954. this.sceneFilename = sceneFilename;
  61955. this.isCompleted = false;
  61956. }
  61957. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  61958. var _this = this;
  61959. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  61960. _this.loadedMeshes = meshes;
  61961. _this.loadedParticleSystems = particleSystems;
  61962. _this.loadedSkeletons = skeletons;
  61963. _this.isCompleted = true;
  61964. if (_this.onSuccess) {
  61965. _this.onSuccess(_this);
  61966. }
  61967. onSuccess();
  61968. }, null, function () {
  61969. if (_this.onError) {
  61970. _this.onError(_this);
  61971. }
  61972. onError();
  61973. });
  61974. };
  61975. return MeshAssetTask;
  61976. }());
  61977. BABYLON.MeshAssetTask = MeshAssetTask;
  61978. var TextFileAssetTask = (function () {
  61979. function TextFileAssetTask(name, url) {
  61980. this.name = name;
  61981. this.url = url;
  61982. this.isCompleted = false;
  61983. }
  61984. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  61985. var _this = this;
  61986. BABYLON.Tools.LoadFile(this.url, function (data) {
  61987. _this.text = data;
  61988. _this.isCompleted = true;
  61989. if (_this.onSuccess) {
  61990. _this.onSuccess(_this);
  61991. }
  61992. onSuccess();
  61993. }, null, scene.database, false, function () {
  61994. if (_this.onError) {
  61995. _this.onError(_this);
  61996. }
  61997. onError();
  61998. });
  61999. };
  62000. return TextFileAssetTask;
  62001. }());
  62002. BABYLON.TextFileAssetTask = TextFileAssetTask;
  62003. var BinaryFileAssetTask = (function () {
  62004. function BinaryFileAssetTask(name, url) {
  62005. this.name = name;
  62006. this.url = url;
  62007. this.isCompleted = false;
  62008. }
  62009. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  62010. var _this = this;
  62011. BABYLON.Tools.LoadFile(this.url, function (data) {
  62012. _this.data = data;
  62013. _this.isCompleted = true;
  62014. if (_this.onSuccess) {
  62015. _this.onSuccess(_this);
  62016. }
  62017. onSuccess();
  62018. }, null, scene.database, true, function () {
  62019. if (_this.onError) {
  62020. _this.onError(_this);
  62021. }
  62022. onError();
  62023. });
  62024. };
  62025. return BinaryFileAssetTask;
  62026. }());
  62027. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  62028. var ImageAssetTask = (function () {
  62029. function ImageAssetTask(name, url) {
  62030. this.name = name;
  62031. this.url = url;
  62032. this.isCompleted = false;
  62033. }
  62034. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  62035. var _this = this;
  62036. var img = new Image();
  62037. BABYLON.Tools.SetCorsBehavior(this.url, img);
  62038. img.onload = function () {
  62039. _this.image = img;
  62040. _this.isCompleted = true;
  62041. if (_this.onSuccess) {
  62042. _this.onSuccess(_this);
  62043. }
  62044. onSuccess();
  62045. };
  62046. img.onerror = function () {
  62047. if (_this.onError) {
  62048. _this.onError(_this);
  62049. }
  62050. onError();
  62051. };
  62052. img.src = this.url;
  62053. };
  62054. return ImageAssetTask;
  62055. }());
  62056. BABYLON.ImageAssetTask = ImageAssetTask;
  62057. var TextureAssetTask = (function () {
  62058. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  62059. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  62060. this.name = name;
  62061. this.url = url;
  62062. this.noMipmap = noMipmap;
  62063. this.invertY = invertY;
  62064. this.samplingMode = samplingMode;
  62065. this.isCompleted = false;
  62066. }
  62067. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  62068. var _this = this;
  62069. var onload = function () {
  62070. _this.isCompleted = true;
  62071. if (_this.onSuccess) {
  62072. _this.onSuccess(_this);
  62073. }
  62074. onSuccess();
  62075. };
  62076. var onerror = function () {
  62077. if (_this.onError) {
  62078. _this.onError(_this);
  62079. }
  62080. onError();
  62081. };
  62082. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  62083. };
  62084. return TextureAssetTask;
  62085. }());
  62086. BABYLON.TextureAssetTask = TextureAssetTask;
  62087. var CubeTextureAssetTask = (function () {
  62088. function CubeTextureAssetTask(name, url, extensions, noMipmap, files) {
  62089. this.name = name;
  62090. this.url = url;
  62091. this.extensions = extensions;
  62092. this.noMipmap = noMipmap;
  62093. this.files = files;
  62094. this.isCompleted = false;
  62095. }
  62096. CubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  62097. var _this = this;
  62098. var onload = function () {
  62099. _this.isCompleted = true;
  62100. if (_this.onSuccess) {
  62101. _this.onSuccess(_this);
  62102. }
  62103. onSuccess();
  62104. };
  62105. var onerror = function () {
  62106. if (_this.onError) {
  62107. _this.onError(_this);
  62108. }
  62109. onError();
  62110. };
  62111. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  62112. };
  62113. return CubeTextureAssetTask;
  62114. }());
  62115. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  62116. var HDRCubeTextureAssetTask = (function () {
  62117. function HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  62118. if (noMipmap === void 0) { noMipmap = false; }
  62119. if (generateHarmonics === void 0) { generateHarmonics = true; }
  62120. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  62121. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  62122. this.name = name;
  62123. this.url = url;
  62124. this.size = size;
  62125. this.noMipmap = noMipmap;
  62126. this.generateHarmonics = generateHarmonics;
  62127. this.useInGammaSpace = useInGammaSpace;
  62128. this.usePMREMGenerator = usePMREMGenerator;
  62129. this.isCompleted = false;
  62130. }
  62131. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  62132. var _this = this;
  62133. var onload = function () {
  62134. _this.isCompleted = true;
  62135. if (_this.onSuccess) {
  62136. _this.onSuccess(_this);
  62137. }
  62138. onSuccess();
  62139. };
  62140. var onerror = function () {
  62141. if (_this.onError) {
  62142. _this.onError(_this);
  62143. }
  62144. onError();
  62145. };
  62146. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  62147. };
  62148. return HDRCubeTextureAssetTask;
  62149. }());
  62150. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  62151. var AssetsManager = (function () {
  62152. function AssetsManager(scene) {
  62153. this.tasks = new Array();
  62154. this.waitingTasksCount = 0;
  62155. this.useDefaultLoadingScreen = true;
  62156. this._scene = scene;
  62157. }
  62158. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  62159. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  62160. this.tasks.push(task);
  62161. return task;
  62162. };
  62163. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  62164. var task = new TextFileAssetTask(taskName, url);
  62165. this.tasks.push(task);
  62166. return task;
  62167. };
  62168. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  62169. var task = new BinaryFileAssetTask(taskName, url);
  62170. this.tasks.push(task);
  62171. return task;
  62172. };
  62173. AssetsManager.prototype.addImageTask = function (taskName, url) {
  62174. var task = new ImageAssetTask(taskName, url);
  62175. this.tasks.push(task);
  62176. return task;
  62177. };
  62178. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  62179. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  62180. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  62181. this.tasks.push(task);
  62182. return task;
  62183. };
  62184. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  62185. this.waitingTasksCount--;
  62186. if (this.waitingTasksCount === 0) {
  62187. if (this.onFinish) {
  62188. this.onFinish(this.tasks);
  62189. }
  62190. this._scene.getEngine().hideLoadingUI();
  62191. }
  62192. };
  62193. AssetsManager.prototype._runTask = function (task) {
  62194. var _this = this;
  62195. task.run(this._scene, function () {
  62196. if (_this.onTaskSuccess) {
  62197. _this.onTaskSuccess(task);
  62198. }
  62199. _this._decreaseWaitingTasksCount();
  62200. }, function () {
  62201. if (_this.onTaskError) {
  62202. _this.onTaskError(task);
  62203. }
  62204. _this._decreaseWaitingTasksCount();
  62205. });
  62206. };
  62207. AssetsManager.prototype.reset = function () {
  62208. this.tasks = new Array();
  62209. return this;
  62210. };
  62211. AssetsManager.prototype.load = function () {
  62212. this.waitingTasksCount = this.tasks.length;
  62213. if (this.waitingTasksCount === 0) {
  62214. if (this.onFinish) {
  62215. this.onFinish(this.tasks);
  62216. }
  62217. return this;
  62218. }
  62219. if (this.useDefaultLoadingScreen) {
  62220. this._scene.getEngine().displayLoadingUI();
  62221. }
  62222. for (var index = 0; index < this.tasks.length; index++) {
  62223. var task = this.tasks[index];
  62224. this._runTask(task);
  62225. }
  62226. return this;
  62227. };
  62228. return AssetsManager;
  62229. }());
  62230. BABYLON.AssetsManager = AssetsManager;
  62231. })(BABYLON || (BABYLON = {}));
  62232. //# sourceMappingURL=babylon.assetsManager.js.map
  62233. var BABYLON;
  62234. (function (BABYLON) {
  62235. var MapTexture = (function (_super) {
  62236. __extends(MapTexture, _super);
  62237. function MapTexture(name, scene, size, samplingMode, useMipMap, margin) {
  62238. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  62239. if (useMipMap === void 0) { useMipMap = false; }
  62240. if (margin === void 0) { margin = 0; }
  62241. var _this = _super.call(this, null, scene, !useMipMap, false, samplingMode) || this;
  62242. _this.name = name;
  62243. _this._size = size;
  62244. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62245. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62246. // Create the rectPackMap that will allocate portion of the texture
  62247. _this._rectPackingMap = new BABYLON.RectPackingMap(new BABYLON.Size(size.width, size.height), margin);
  62248. // Create the texture that will store the content
  62249. _this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: !_this.noMipmap, type: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT });
  62250. return _this;
  62251. }
  62252. /**
  62253. * Allocate a rectangle of a given size in the texture map
  62254. * @param size the size of the rectangle to allocation
  62255. * @return the PackedRect instance corresponding to the allocated rect or null is there was not enough space to allocate it.
  62256. */
  62257. MapTexture.prototype.allocateRect = function (size) {
  62258. return this._rectPackingMap.addRect(size);
  62259. };
  62260. /**
  62261. * Free a given rectangle from the texture map
  62262. * @param rectInfo the instance corresponding to the rect to free.
  62263. */
  62264. MapTexture.prototype.freeRect = function (rectInfo) {
  62265. if (rectInfo) {
  62266. rectInfo.freeContent();
  62267. }
  62268. };
  62269. Object.defineProperty(MapTexture.prototype, "freeSpace", {
  62270. /**
  62271. * Return the available space in the range of [O;1]. 0 being not space left at all, 1 being an empty texture map.
  62272. * This is the cumulated space, not the biggest available surface. Due to fragmentation you may not allocate a rect corresponding to this surface.
  62273. * @returns {}
  62274. */
  62275. get: function () {
  62276. return this._rectPackingMap.freeSpace;
  62277. },
  62278. enumerable: true,
  62279. configurable: true
  62280. });
  62281. /**
  62282. * Bind the texture to the rendering engine to render in the zone of a given rectangle.
  62283. * 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.
  62284. * Don't forget to call unbindTexture when you're done rendering
  62285. * @param rect the zone to render to
  62286. * @param clear true to clear the portion's color/depth data
  62287. */
  62288. MapTexture.prototype.bindTextureForRect = function (rect, clear) {
  62289. return this.bindTextureForPosSize(rect.pos, rect.contentSize, clear);
  62290. };
  62291. /**
  62292. * Bind the texture to the rendering engine to render in the zone of the given size at the given position.
  62293. * 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.
  62294. * Don't forget to call unbindTexture when you're done rendering
  62295. * @param pos the position into the texture
  62296. * @param size the portion to fit the clip space to
  62297. * @param clear true to clear the portion's color/depth data
  62298. */
  62299. MapTexture.prototype.bindTextureForPosSize = function (pos, size, clear) {
  62300. var engine = this.getScene().getEngine();
  62301. engine.bindFramebuffer(this._texture);
  62302. this._replacedViewport = engine.setDirectViewport(pos.x, pos.y, size.width, size.height);
  62303. if (clear) {
  62304. // We only want to clear the part of the texture we're binding to, only the scissor can help us to achieve that
  62305. engine.scissorClear(pos.x, pos.y, size.width, size.height, new BABYLON.Color4(0, 0, 0, 0));
  62306. }
  62307. };
  62308. /**
  62309. * Unbind the texture map from the rendering engine.
  62310. * Call this method when you're done rendering. A previous call to bindTextureForRect has to be made.
  62311. * @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.
  62312. */
  62313. MapTexture.prototype.unbindTexture = function (dumpForDebug) {
  62314. // Dump ?
  62315. if (dumpForDebug) {
  62316. BABYLON.Tools.DumpFramebuffer(this._size.width, this._size.height, this.getScene().getEngine());
  62317. }
  62318. var engine = this.getScene().getEngine();
  62319. if (this._replacedViewport) {
  62320. engine.setViewport(this._replacedViewport);
  62321. this._replacedViewport = null;
  62322. }
  62323. engine.unBindFramebuffer(this._texture);
  62324. };
  62325. Object.defineProperty(MapTexture.prototype, "canRescale", {
  62326. get: function () {
  62327. return false;
  62328. },
  62329. enumerable: true,
  62330. configurable: true
  62331. });
  62332. // Note, I don't know what behavior this method should have: clone the underlying texture/rectPackingMap or just reference them?
  62333. // Anyway, there's not much point to use this method for this kind of texture I guess
  62334. MapTexture.prototype.clone = function () {
  62335. return null;
  62336. };
  62337. return MapTexture;
  62338. }(BABYLON.Texture));
  62339. BABYLON.MapTexture = MapTexture;
  62340. })(BABYLON || (BABYLON = {}));
  62341. //# sourceMappingURL=babylon.mapTexture.js.map
  62342. var BABYLON;
  62343. (function (BABYLON) {
  62344. /**
  62345. * This class describe a rectangle that were added to the map.
  62346. * You have access to its coordinates either in pixel or normalized (UV)
  62347. */
  62348. var PackedRect = (function () {
  62349. function PackedRect(root, parent, pos, size) {
  62350. this._pos = pos;
  62351. this._size = size;
  62352. this._root = root;
  62353. this._parent = parent;
  62354. this._contentSize = null;
  62355. this._bottomNode = null;
  62356. this._leftNode = null;
  62357. this._initialSize = null;
  62358. this._rightNode = null;
  62359. }
  62360. Object.defineProperty(PackedRect.prototype, "pos", {
  62361. /**
  62362. * @returns the position of this node into the map
  62363. */
  62364. get: function () {
  62365. return this._pos;
  62366. },
  62367. enumerable: true,
  62368. configurable: true
  62369. });
  62370. Object.defineProperty(PackedRect.prototype, "contentSize", {
  62371. /**
  62372. * @returns the size of the rectangle this node handles
  62373. */
  62374. get: function () {
  62375. return this._contentSize;
  62376. },
  62377. enumerable: true,
  62378. configurable: true
  62379. });
  62380. /**
  62381. * Retrieve the inner position (considering the margin) and stores it into the res object
  62382. * @param res must be a valid Vector2 that will contain the inner position after this call
  62383. */
  62384. PackedRect.prototype.getInnerPosToRef = function (res) {
  62385. var m = this._root._margin;
  62386. res.x = this._pos.x + m;
  62387. res.y = this._pos.y + m;
  62388. };
  62389. /**
  62390. * Retrieve the inner size (considering the margin) and stores it into the res object
  62391. * @param res must be a valid Size that will contain the inner size after this call
  62392. */
  62393. PackedRect.prototype.getInnerSizeToRef = function (res) {
  62394. var m = this._root._margin;
  62395. res.width = this._contentSize.width - (m * 2);
  62396. res.height = this._contentSize.height - (m * 2);
  62397. };
  62398. Object.defineProperty(PackedRect.prototype, "UVs", {
  62399. /**
  62400. * Compute the UV of the top/left, top/right, bottom/right, bottom/left points of the rectangle this node handles into the map
  62401. * @returns And array of 4 Vector2, containing UV coordinates for the four corners of the Rectangle into the map
  62402. */
  62403. get: function () {
  62404. if (!this._contentSize) {
  62405. throw new Error("Can't compute UVs for this object because it's nor allocated");
  62406. }
  62407. return this.getUVsForCustomSize(this._contentSize);
  62408. },
  62409. enumerable: true,
  62410. configurable: true
  62411. });
  62412. /**
  62413. * You may have allocated the PackedRect using over-provisioning (you allocated more than you need in order to prevent frequent deallocations/reallocations)
  62414. * and then using only a part of the PackRect.
  62415. * This method will return the UVs for this part by given the custom size of what you really use
  62416. * @param customSize must be less/equal to the allocated size, UV will be compute from this
  62417. */
  62418. PackedRect.prototype.getUVsForCustomSize = function (customSize) {
  62419. var mainWidth = this._root._size.width;
  62420. var mainHeight = this._root._size.height;
  62421. var margin = this._root._margin;
  62422. var topLeft = new BABYLON.Vector2((this._pos.x + margin) / mainWidth, (this._pos.y + margin) / mainHeight);
  62423. var rightBottom = new BABYLON.Vector2((this._pos.x + customSize.width + margin - 1) / mainWidth, (this._pos.y + customSize.height + margin - 1) / mainHeight);
  62424. var uvs = new Array();
  62425. uvs.push(topLeft);
  62426. uvs.push(new BABYLON.Vector2(rightBottom.x, topLeft.y));
  62427. uvs.push(rightBottom);
  62428. uvs.push(new BABYLON.Vector2(topLeft.x, rightBottom.y));
  62429. return uvs;
  62430. };
  62431. /**
  62432. * Free this rectangle from the map.
  62433. * Call this method when you no longer need the rectangle to be in the map.
  62434. */
  62435. PackedRect.prototype.freeContent = function () {
  62436. if (!this.contentSize) {
  62437. return;
  62438. }
  62439. this._contentSize = null;
  62440. // If everything below is also free, reset the whole node, and attempt to reset parents if they also become free
  62441. this.attemptDefrag();
  62442. };
  62443. Object.defineProperty(PackedRect.prototype, "isUsed", {
  62444. get: function () {
  62445. return this._contentSize != null || this._leftNode != null;
  62446. },
  62447. enumerable: true,
  62448. configurable: true
  62449. });
  62450. PackedRect.prototype.findAndSplitNode = function (contentSize) {
  62451. var node = this.findNode(contentSize);
  62452. // Not enough space...
  62453. if (!node) {
  62454. return null;
  62455. }
  62456. node.splitNode(contentSize);
  62457. return node;
  62458. };
  62459. PackedRect.prototype.findNode = function (size) {
  62460. var resNode = null;
  62461. var margin = this._root._margin * 2;
  62462. // If this node is used, recurse to each of his subNodes to find an available one in its branch
  62463. if (this.isUsed) {
  62464. if (this._leftNode) {
  62465. resNode = this._leftNode.findNode(size);
  62466. }
  62467. if (!resNode && this._rightNode) {
  62468. resNode = this._rightNode.findNode(size);
  62469. }
  62470. if (!resNode && this._bottomNode) {
  62471. resNode = this._bottomNode.findNode(size);
  62472. }
  62473. }
  62474. else if (this._initialSize) {
  62475. if (((size.width + margin) <= this._initialSize.width) && ((size.height + margin) <= this._initialSize.height)) {
  62476. resNode = this;
  62477. }
  62478. else {
  62479. return null;
  62480. }
  62481. }
  62482. else if (((size.width + margin) <= this._size.width) && ((size.height + margin) <= this._size.height)) {
  62483. resNode = this;
  62484. }
  62485. return resNode;
  62486. };
  62487. PackedRect.prototype.splitNode = function (contentSize) {
  62488. var cs = PackedRect.TpsSize;
  62489. var margin = this._root._margin * 2;
  62490. cs.copyFrom(contentSize);
  62491. cs.width += margin;
  62492. cs.height += margin;
  62493. // 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)
  62494. if (!this._contentSize && this._initialSize) {
  62495. this._contentSize = cs.clone();
  62496. 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));
  62497. return this._leftNode.splitNode(contentSize);
  62498. }
  62499. else {
  62500. this._contentSize = cs.clone();
  62501. this._initialSize = cs.clone();
  62502. if (cs.width !== this._size.width) {
  62503. 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));
  62504. }
  62505. if (cs.height !== this._size.height) {
  62506. 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));
  62507. }
  62508. return this;
  62509. }
  62510. };
  62511. PackedRect.prototype.attemptDefrag = function () {
  62512. if (!this.isUsed && this.isRecursiveFree) {
  62513. this.clearNode();
  62514. if (this._parent) {
  62515. this._parent.attemptDefrag();
  62516. }
  62517. }
  62518. };
  62519. PackedRect.prototype.clearNode = function () {
  62520. this._initialSize = null;
  62521. this._rightNode = null;
  62522. this._bottomNode = null;
  62523. };
  62524. Object.defineProperty(PackedRect.prototype, "isRecursiveFree", {
  62525. get: function () {
  62526. return !this.contentSize && (!this._leftNode || this._leftNode.isRecursiveFree) && (!this._rightNode || this._rightNode.isRecursiveFree) && (!this._bottomNode || this._bottomNode.isRecursiveFree);
  62527. },
  62528. enumerable: true,
  62529. configurable: true
  62530. });
  62531. PackedRect.prototype.evalFreeSize = function (size) {
  62532. var levelSize = 0;
  62533. if (!this.isUsed) {
  62534. var margin = this._root._margin;
  62535. var is = this._initialSize;
  62536. if (is) {
  62537. levelSize = is.surface - (is.width * margin) - (is.height * margin);
  62538. }
  62539. else {
  62540. var size_1 = this._size;
  62541. levelSize = size_1.surface - (size_1.width * margin) - (size_1.height * margin);
  62542. }
  62543. }
  62544. if (this._rightNode) {
  62545. levelSize += this._rightNode.evalFreeSize(0);
  62546. }
  62547. if (this._bottomNode) {
  62548. levelSize += this._bottomNode.evalFreeSize(0);
  62549. }
  62550. return levelSize + size;
  62551. };
  62552. return PackedRect;
  62553. }());
  62554. PackedRect.TpsSize = BABYLON.Size.Zero();
  62555. BABYLON.PackedRect = PackedRect;
  62556. /**
  62557. * The purpose of this class is to pack several Rectangles into a big map, while trying to fit everything as optimally as possible.
  62558. * This class is typically used to build lightmaps, sprite map or to pack several little textures into a big one.
  62559. * 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.
  62560. * In case you need a margin around the allocated rect, specify the amount in the margin argument during construction.
  62561. * In such case you will have to rely on innerPositionToRef and innerSizeToRef calls to get the proper size
  62562. */
  62563. var RectPackingMap = (function (_super) {
  62564. __extends(RectPackingMap, _super);
  62565. /**
  62566. * Create an instance of the object with a dimension using the given size
  62567. * @param size The dimension of the rectangle that will contain all the sub ones.
  62568. * @param margin The margin (empty space) created (in pixels) around the allocated Rectangles
  62569. */
  62570. function RectPackingMap(size, margin) {
  62571. if (margin === void 0) { margin = 0; }
  62572. var _this = _super.call(this, null, null, BABYLON.Vector2.Zero(), size) || this;
  62573. _this._margin = margin;
  62574. _this._root = _this;
  62575. return _this;
  62576. }
  62577. /**
  62578. * Add a rectangle, finding the best location to store it into the map
  62579. * @param size the dimension of the rectangle to store
  62580. * @return the Node containing the rectangle information, or null if we couldn't find a free spot
  62581. */
  62582. RectPackingMap.prototype.addRect = function (size) {
  62583. var node = this.findAndSplitNode(size);
  62584. return node;
  62585. };
  62586. Object.defineProperty(RectPackingMap.prototype, "freeSpace", {
  62587. /**
  62588. * Return the current space free normalized between [0;1]
  62589. * @returns {}
  62590. */
  62591. get: function () {
  62592. var freeSize = 0;
  62593. freeSize = this.evalFreeSize(freeSize);
  62594. return freeSize / (this._size.width * this._size.height);
  62595. },
  62596. enumerable: true,
  62597. configurable: true
  62598. });
  62599. return RectPackingMap;
  62600. }(PackedRect));
  62601. BABYLON.RectPackingMap = RectPackingMap;
  62602. })(BABYLON || (BABYLON = {}));
  62603. //# sourceMappingURL=babylon.rectPackingMap.js.map
  62604. var BABYLON;
  62605. (function (BABYLON) {
  62606. var serializedGeometries = [];
  62607. var serializeGeometry = function (geometry, serializationGeometries) {
  62608. if (serializedGeometries[geometry.id]) {
  62609. return;
  62610. }
  62611. if (geometry.doNotSerialize) {
  62612. return;
  62613. }
  62614. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  62615. serializationGeometries.boxes.push(geometry.serialize());
  62616. }
  62617. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  62618. serializationGeometries.spheres.push(geometry.serialize());
  62619. }
  62620. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  62621. serializationGeometries.cylinders.push(geometry.serialize());
  62622. }
  62623. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  62624. serializationGeometries.toruses.push(geometry.serialize());
  62625. }
  62626. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  62627. serializationGeometries.grounds.push(geometry.serialize());
  62628. }
  62629. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  62630. serializationGeometries.planes.push(geometry.serialize());
  62631. }
  62632. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  62633. serializationGeometries.torusKnots.push(geometry.serialize());
  62634. }
  62635. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  62636. throw new Error("Unknown primitive type");
  62637. }
  62638. else {
  62639. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  62640. }
  62641. serializedGeometries[geometry.id] = true;
  62642. };
  62643. var serializeMesh = function (mesh, serializationScene) {
  62644. var serializationObject = {};
  62645. // Geometry
  62646. var geometry = mesh._geometry;
  62647. if (geometry) {
  62648. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  62649. // 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
  62650. serializeGeometry(geometry, serializationScene.geometries);
  62651. }
  62652. }
  62653. // Custom
  62654. if (mesh.serialize) {
  62655. mesh.serialize(serializationObject);
  62656. }
  62657. return serializationObject;
  62658. };
  62659. var finalizeSingleMesh = function (mesh, serializationObject) {
  62660. //only works if the mesh is already loaded
  62661. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  62662. //serialize material
  62663. if (mesh.material) {
  62664. if (mesh.material instanceof BABYLON.StandardMaterial) {
  62665. serializationObject.materials = serializationObject.materials || [];
  62666. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  62667. serializationObject.materials.push(mesh.material.serialize());
  62668. }
  62669. }
  62670. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  62671. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  62672. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  62673. serializationObject.multiMaterials.push(mesh.material.serialize());
  62674. }
  62675. }
  62676. }
  62677. //serialize geometry
  62678. var geometry = mesh._geometry;
  62679. if (geometry) {
  62680. if (!serializationObject.geometries) {
  62681. serializationObject.geometries = {};
  62682. serializationObject.geometries.boxes = [];
  62683. serializationObject.geometries.spheres = [];
  62684. serializationObject.geometries.cylinders = [];
  62685. serializationObject.geometries.toruses = [];
  62686. serializationObject.geometries.grounds = [];
  62687. serializationObject.geometries.planes = [];
  62688. serializationObject.geometries.torusKnots = [];
  62689. serializationObject.geometries.vertexData = [];
  62690. }
  62691. serializeGeometry(geometry, serializationObject.geometries);
  62692. }
  62693. // Skeletons
  62694. if (mesh.skeleton) {
  62695. serializationObject.skeletons = serializationObject.skeletons || [];
  62696. serializationObject.skeletons.push(mesh.skeleton.serialize());
  62697. }
  62698. //serialize the actual mesh
  62699. serializationObject.meshes = serializationObject.meshes || [];
  62700. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  62701. }
  62702. };
  62703. var SceneSerializer = (function () {
  62704. function SceneSerializer() {
  62705. }
  62706. SceneSerializer.ClearCache = function () {
  62707. serializedGeometries = [];
  62708. };
  62709. SceneSerializer.Serialize = function (scene) {
  62710. var serializationObject = {};
  62711. SceneSerializer.ClearCache();
  62712. // Scene
  62713. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  62714. serializationObject.autoClear = scene.autoClear;
  62715. serializationObject.clearColor = scene.clearColor.asArray();
  62716. serializationObject.ambientColor = scene.ambientColor.asArray();
  62717. serializationObject.gravity = scene.gravity.asArray();
  62718. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  62719. serializationObject.workerCollisions = scene.workerCollisions;
  62720. // Fog
  62721. if (scene.fogMode && scene.fogMode !== 0) {
  62722. serializationObject.fogMode = scene.fogMode;
  62723. serializationObject.fogColor = scene.fogColor.asArray();
  62724. serializationObject.fogStart = scene.fogStart;
  62725. serializationObject.fogEnd = scene.fogEnd;
  62726. serializationObject.fogDensity = scene.fogDensity;
  62727. }
  62728. //Physics
  62729. if (scene.isPhysicsEnabled()) {
  62730. serializationObject.physicsEnabled = true;
  62731. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  62732. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  62733. }
  62734. // Metadata
  62735. if (scene.metadata) {
  62736. serializationObject.metadata = scene.metadata;
  62737. }
  62738. // Morph targets
  62739. serializationObject.morphTargetManagers = [];
  62740. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  62741. var abstractMesh = _a[_i];
  62742. var manager = abstractMesh.morphTargetManager;
  62743. if (manager) {
  62744. serializationObject.morphTargetManagers.push(manager.serialize());
  62745. }
  62746. }
  62747. // Lights
  62748. serializationObject.lights = [];
  62749. var index;
  62750. var light;
  62751. for (index = 0; index < scene.lights.length; index++) {
  62752. light = scene.lights[index];
  62753. if (!light.doNotSerialize) {
  62754. serializationObject.lights.push(light.serialize());
  62755. }
  62756. }
  62757. // Cameras
  62758. serializationObject.cameras = [];
  62759. for (index = 0; index < scene.cameras.length; index++) {
  62760. var camera = scene.cameras[index];
  62761. if (!camera.doNotSerialize) {
  62762. serializationObject.cameras.push(camera.serialize());
  62763. }
  62764. }
  62765. if (scene.activeCamera) {
  62766. serializationObject.activeCameraID = scene.activeCamera.id;
  62767. }
  62768. // Animations
  62769. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  62770. // Materials
  62771. serializationObject.materials = [];
  62772. serializationObject.multiMaterials = [];
  62773. var material;
  62774. for (index = 0; index < scene.materials.length; index++) {
  62775. material = scene.materials[index];
  62776. if (!material.doNotSerialize) {
  62777. serializationObject.materials.push(material.serialize());
  62778. }
  62779. }
  62780. // MultiMaterials
  62781. serializationObject.multiMaterials = [];
  62782. for (index = 0; index < scene.multiMaterials.length; index++) {
  62783. var multiMaterial = scene.multiMaterials[index];
  62784. serializationObject.multiMaterials.push(multiMaterial.serialize());
  62785. }
  62786. // Skeletons
  62787. serializationObject.skeletons = [];
  62788. for (index = 0; index < scene.skeletons.length; index++) {
  62789. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  62790. }
  62791. // Geometries
  62792. serializationObject.geometries = {};
  62793. serializationObject.geometries.boxes = [];
  62794. serializationObject.geometries.spheres = [];
  62795. serializationObject.geometries.cylinders = [];
  62796. serializationObject.geometries.toruses = [];
  62797. serializationObject.geometries.grounds = [];
  62798. serializationObject.geometries.planes = [];
  62799. serializationObject.geometries.torusKnots = [];
  62800. serializationObject.geometries.vertexData = [];
  62801. serializedGeometries = [];
  62802. var geometries = scene.getGeometries();
  62803. for (index = 0; index < geometries.length; index++) {
  62804. var geometry = geometries[index];
  62805. if (geometry.isReady()) {
  62806. serializeGeometry(geometry, serializationObject.geometries);
  62807. }
  62808. }
  62809. // Meshes
  62810. serializationObject.meshes = [];
  62811. for (index = 0; index < scene.meshes.length; index++) {
  62812. var abstractMesh = scene.meshes[index];
  62813. if (abstractMesh instanceof BABYLON.Mesh) {
  62814. var mesh = abstractMesh;
  62815. if (!mesh.doNotSerialize) {
  62816. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  62817. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  62818. }
  62819. }
  62820. }
  62821. }
  62822. // Particles Systems
  62823. serializationObject.particleSystems = [];
  62824. for (index = 0; index < scene.particleSystems.length; index++) {
  62825. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  62826. }
  62827. // Lens flares
  62828. serializationObject.lensFlareSystems = [];
  62829. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  62830. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  62831. }
  62832. // Shadows
  62833. serializationObject.shadowGenerators = [];
  62834. for (index = 0; index < scene.lights.length; index++) {
  62835. light = scene.lights[index];
  62836. var shadowGenerator = light.getShadowGenerator();
  62837. // Only support serialization for official generator so far.
  62838. if (shadowGenerator && shadowGenerator instanceof BABYLON.ShadowGenerator) {
  62839. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  62840. }
  62841. }
  62842. // Action Manager
  62843. if (scene.actionManager) {
  62844. serializationObject.actions = scene.actionManager.serialize("scene");
  62845. }
  62846. // Audio
  62847. serializationObject.sounds = [];
  62848. for (index = 0; index < scene.soundTracks.length; index++) {
  62849. var soundtrack = scene.soundTracks[index];
  62850. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  62851. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  62852. }
  62853. }
  62854. return serializationObject;
  62855. };
  62856. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  62857. if (withParents === void 0) { withParents = false; }
  62858. if (withChildren === void 0) { withChildren = false; }
  62859. var serializationObject = {};
  62860. SceneSerializer.ClearCache();
  62861. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  62862. if (withParents || withChildren) {
  62863. //deliberate for loop! not for each, appended should be processed as well.
  62864. for (var i = 0; i < toSerialize.length; ++i) {
  62865. if (withChildren) {
  62866. toSerialize[i].getDescendants().forEach(function (node) {
  62867. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  62868. toSerialize.push(node);
  62869. }
  62870. });
  62871. }
  62872. //make sure the array doesn't contain the object already
  62873. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  62874. toSerialize.push(toSerialize[i].parent);
  62875. }
  62876. }
  62877. }
  62878. toSerialize.forEach(function (mesh) {
  62879. finalizeSingleMesh(mesh, serializationObject);
  62880. });
  62881. return serializationObject;
  62882. };
  62883. return SceneSerializer;
  62884. }());
  62885. BABYLON.SceneSerializer = SceneSerializer;
  62886. })(BABYLON || (BABYLON = {}));
  62887. //# sourceMappingURL=babylon.sceneSerializer.js.map
  62888. var BABYLON;
  62889. (function (BABYLON) {
  62890. var ReflectionProbe = (function () {
  62891. function ReflectionProbe(name, size, scene, generateMipMaps) {
  62892. if (generateMipMaps === void 0) { generateMipMaps = true; }
  62893. var _this = this;
  62894. this.name = name;
  62895. this._viewMatrix = BABYLON.Matrix.Identity();
  62896. this._target = BABYLON.Vector3.Zero();
  62897. this._add = BABYLON.Vector3.Zero();
  62898. this.invertYAxis = false;
  62899. this.position = BABYLON.Vector3.Zero();
  62900. this._scene = scene;
  62901. this._scene.reflectionProbes.push(this);
  62902. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  62903. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  62904. switch (faceIndex) {
  62905. case 0:
  62906. _this._add.copyFromFloats(1, 0, 0);
  62907. break;
  62908. case 1:
  62909. _this._add.copyFromFloats(-1, 0, 0);
  62910. break;
  62911. case 2:
  62912. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  62913. break;
  62914. case 3:
  62915. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  62916. break;
  62917. case 4:
  62918. _this._add.copyFromFloats(0, 0, 1);
  62919. break;
  62920. case 5:
  62921. _this._add.copyFromFloats(0, 0, -1);
  62922. break;
  62923. }
  62924. if (_this._attachedMesh) {
  62925. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  62926. }
  62927. _this.position.addToRef(_this._add, _this._target);
  62928. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  62929. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  62930. });
  62931. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  62932. scene.updateTransformMatrix(true);
  62933. });
  62934. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  62935. }
  62936. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  62937. get: function () {
  62938. return this._renderTargetTexture.samples;
  62939. },
  62940. set: function (value) {
  62941. this._renderTargetTexture.samples = value;
  62942. },
  62943. enumerable: true,
  62944. configurable: true
  62945. });
  62946. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  62947. get: function () {
  62948. return this._renderTargetTexture.refreshRate;
  62949. },
  62950. set: function (value) {
  62951. this._renderTargetTexture.refreshRate = value;
  62952. },
  62953. enumerable: true,
  62954. configurable: true
  62955. });
  62956. ReflectionProbe.prototype.getScene = function () {
  62957. return this._scene;
  62958. };
  62959. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  62960. get: function () {
  62961. return this._renderTargetTexture;
  62962. },
  62963. enumerable: true,
  62964. configurable: true
  62965. });
  62966. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  62967. get: function () {
  62968. return this._renderTargetTexture.renderList;
  62969. },
  62970. enumerable: true,
  62971. configurable: true
  62972. });
  62973. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  62974. this._attachedMesh = mesh;
  62975. };
  62976. ReflectionProbe.prototype.dispose = function () {
  62977. var index = this._scene.reflectionProbes.indexOf(this);
  62978. if (index !== -1) {
  62979. // Remove from the scene if found
  62980. this._scene.reflectionProbes.splice(index, 1);
  62981. }
  62982. if (this._renderTargetTexture) {
  62983. this._renderTargetTexture.dispose();
  62984. this._renderTargetTexture = null;
  62985. }
  62986. };
  62987. return ReflectionProbe;
  62988. }());
  62989. BABYLON.ReflectionProbe = ReflectionProbe;
  62990. })(BABYLON || (BABYLON = {}));
  62991. //# sourceMappingURL=babylon.reflectionProbe.js.map
  62992. var BABYLON;
  62993. (function (BABYLON) {
  62994. var Layer = (function () {
  62995. function Layer(name, imgUrl, scene, isBackground, color) {
  62996. this.name = name;
  62997. this.scale = new BABYLON.Vector2(1, 1);
  62998. this.offset = new BABYLON.Vector2(0, 0);
  62999. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  63000. this._vertexBuffers = {};
  63001. // Events
  63002. /**
  63003. * An event triggered when the layer is disposed.
  63004. * @type {BABYLON.Observable}
  63005. */
  63006. this.onDisposeObservable = new BABYLON.Observable();
  63007. /**
  63008. * An event triggered before rendering the scene
  63009. * @type {BABYLON.Observable}
  63010. */
  63011. this.onBeforeRenderObservable = new BABYLON.Observable();
  63012. /**
  63013. * An event triggered after rendering the scene
  63014. * @type {BABYLON.Observable}
  63015. */
  63016. this.onAfterRenderObservable = new BABYLON.Observable();
  63017. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  63018. this.isBackground = isBackground === undefined ? true : isBackground;
  63019. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  63020. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  63021. this._scene.layers.push(this);
  63022. var engine = this._scene.getEngine();
  63023. // VBO
  63024. var vertices = [];
  63025. vertices.push(1, 1);
  63026. vertices.push(-1, 1);
  63027. vertices.push(-1, -1);
  63028. vertices.push(1, -1);
  63029. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  63030. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  63031. // Indices
  63032. var indices = [];
  63033. indices.push(0);
  63034. indices.push(1);
  63035. indices.push(2);
  63036. indices.push(0);
  63037. indices.push(2);
  63038. indices.push(3);
  63039. this._indexBuffer = engine.createIndexBuffer(indices);
  63040. // Effects
  63041. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  63042. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  63043. }
  63044. Object.defineProperty(Layer.prototype, "onDispose", {
  63045. set: function (callback) {
  63046. if (this._onDisposeObserver) {
  63047. this.onDisposeObservable.remove(this._onDisposeObserver);
  63048. }
  63049. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  63050. },
  63051. enumerable: true,
  63052. configurable: true
  63053. });
  63054. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  63055. set: function (callback) {
  63056. if (this._onBeforeRenderObserver) {
  63057. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  63058. }
  63059. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  63060. },
  63061. enumerable: true,
  63062. configurable: true
  63063. });
  63064. Object.defineProperty(Layer.prototype, "onAfterRender", {
  63065. set: function (callback) {
  63066. if (this._onAfterRenderObserver) {
  63067. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  63068. }
  63069. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  63070. },
  63071. enumerable: true,
  63072. configurable: true
  63073. });
  63074. Layer.prototype.render = function () {
  63075. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  63076. // Check
  63077. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  63078. return;
  63079. var engine = this._scene.getEngine();
  63080. this.onBeforeRenderObservable.notifyObservers(this);
  63081. // Render
  63082. engine.enableEffect(currentEffect);
  63083. engine.setState(false);
  63084. // Texture
  63085. currentEffect.setTexture("textureSampler", this.texture);
  63086. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  63087. // Color
  63088. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  63089. // Scale / offset
  63090. currentEffect.setVector2("offset", this.offset);
  63091. currentEffect.setVector2("scale", this.scale);
  63092. // VBOs
  63093. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  63094. // Draw order
  63095. if (!this.alphaTest) {
  63096. engine.setAlphaMode(this.alphaBlendingMode);
  63097. engine.draw(true, 0, 6);
  63098. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  63099. }
  63100. else {
  63101. engine.draw(true, 0, 6);
  63102. }
  63103. this.onAfterRenderObservable.notifyObservers(this);
  63104. };
  63105. Layer.prototype.dispose = function () {
  63106. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  63107. if (vertexBuffer) {
  63108. vertexBuffer.dispose();
  63109. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  63110. }
  63111. if (this._indexBuffer) {
  63112. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  63113. this._indexBuffer = null;
  63114. }
  63115. if (this.texture) {
  63116. this.texture.dispose();
  63117. this.texture = null;
  63118. }
  63119. // Remove from scene
  63120. var index = this._scene.layers.indexOf(this);
  63121. this._scene.layers.splice(index, 1);
  63122. // Callback
  63123. this.onDisposeObservable.notifyObservers(this);
  63124. this.onDisposeObservable.clear();
  63125. this.onAfterRenderObservable.clear();
  63126. this.onBeforeRenderObservable.clear();
  63127. };
  63128. return Layer;
  63129. }());
  63130. BABYLON.Layer = Layer;
  63131. })(BABYLON || (BABYLON = {}));
  63132. //# sourceMappingURL=babylon.layer.js.map
  63133. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normalUpdated,0.0)));\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef LIGHTMAP\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n}","defaultPixelShader":"#include<__decl__defaultFragment>\n#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef CAMERACOLORGRADING\n#include<colorGradingDefinition> \n#include<colorGrading>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurvesDefinition>\n#include<colorCurves>\n#endif\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb*vRefractionInfos.x;\n#endif\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#include<logDepthFragment>\n#include<fogFragment>\n#ifdef CAMERACOLORGRADING\ncolor=colorGrades(color);\n#endif\n#ifdef CAMERACOLORCURVES\ncolor.rgb=applyColorCurves(color.rgb);\n#endif\ngl_FragColor=color;\n}","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) || defined(METALLICWORKFLOW) \nvarying vec2 vReflectivityUV;\n#endif\n#ifdef MICROSURFACEMAP\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normalUpdated,0.0)));\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef ALBEDO\nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef LIGHTMAP\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) || defined(METALLICWORKFLOW) \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef MICROSURFACEMAP\nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP)|| !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform sampler2D lightmapSampler;\n#endif\n#if defined(REFLECTIVITY) || defined(METALLICWORKFLOW) \nvarying vec2 vReflectivityUV;\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\nvarying vec2 vMicroSurfaceSamplerUV;\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef CAMERACOLORGRADING\n#include<colorGradingDefinition>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurvesDefinition>\n#endif\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#ifdef CAMERACOLORGRADING\n#include<colorGrading>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurves>\n#endif\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<helperFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\nvec4 surfaceAlbedo=vec4(1.,1.,1.,1.);\nvec3 surfaceAlbedoContribution=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nsurfaceAlbedo=texture2D(albedoSampler,vAlbedoUV+uvOffset);\nsurfaceAlbedo=vec4(toLinearSpace(surfaceAlbedo.rgb),surfaceAlbedo.a);\n#ifndef LINKREFRACTIONTOTRANSPARENCY\n#ifdef ALPHATEST\nif (surfaceAlbedo.a<0.4)\ndiscard;\n#endif\n#endif\n#ifdef ALPHAFROMALBEDO\nalpha*=surfaceAlbedo.a;\n#endif\nsurfaceAlbedo.rgb*=vAlbedoInfos.y;\n#else\n\nsurfaceAlbedo.rgb=surfaceAlbedoContribution;\nsurfaceAlbedoContribution=vec3(1.,1.,1.);\n#endif\n#ifdef VERTEXCOLOR\nsurfaceAlbedo.rgb*=vColor.rgb;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceAlbedo.rgb=mix(surfaceAlbedo.rgb,vOverloadedAlbedo,vOverloadedIntensity.y);\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE \nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#ifdef OVERLOADEDVALUES\nambientOcclusionColor.rgb=mix(ambientOcclusionColor.rgb,vOverloadedAmbient,vOverloadedIntensity.x);\n#endif\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor=surfaceReflectivityColorMap.rgb;\nsurfaceReflectivityColor=toLinearSpace(surfaceReflectivityColor);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor=mix(surfaceReflectivityColor,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface=surfaceReflectivityColorMap.a*vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#endif\n#else\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor=mix(surfaceReflectivityColor,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#endif\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef METALLICMAP\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED \nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo.rgb;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo.rgb=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor=mix(surfaceReflectivityColor,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#else\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface=microSurfaceTexel.r;\n#endif\n#endif\n#ifdef OVERLOADEDVALUES\nmicroSurface=mix(microSurface,vOverloadedMicroSurface.x,vOverloadedMicroSurface.y);\n#endif\n\nfloat NdotV=max(0.00000000001,dot(normalW,viewDirectionW));\n\nmicroSurface=clamp(microSurface,0.,1.)*0.98;\n\nfloat roughness=clamp(1.-microSurface,0.000001,1.0);\n\nvec3 lightDiffuseContribution=vec3(0.,0.,0.);\n#ifdef OVERLOADEDSHADOWVALUES\nvec3 shadowedOnlyLightDiffuseContribution=vec3(1.,1.,1.);\n#endif\n#ifdef SPECULARTERM\nvec3 lightSpecularContribution=vec3(0.,0.,0.);\n#endif\nfloat notShadowLevel=1.; \n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\nfloat NdotL=-1.;\nlightingInfo info;\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\n\n\nfloat reflectance90=clamp(reflectance*25.0,0.0,1.0);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n#include<pbrLightFunctionsCall>[0..maxSimultaneousLights]\n#ifdef SPECULARTERM\nlightSpecularContribution*=vLightingIntensity.w;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 surfaceRefractionColor=vec3(0.,0.,0.);\n\n#ifdef LODBASEDMICROSFURACE\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#endif\n#ifdef REFRACTION\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFRACTION\nfloat lodRefraction=getMipMapIndexFromAverageSlopeWithPMREM(vMicrosurfaceTextureLods.y,alphaG);\n#else\nfloat lodRefraction=getMipMapIndexFromAverageSlope(vMicrosurfaceTextureLods.y,alphaG);\n#endif\n#else\nfloat biasRefraction=(vMicrosurfaceTextureLods.y+2.)*(1.0-microSurface);\n#endif\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFRACTION\n\nif ((vMicrosurfaceTextureLods.y-lodRefraction)>4.0)\n{\n\nfloat scaleRefraction=1.-exp2(lodRefraction)/exp2(vMicrosurfaceTextureLods.y); \nfloat maxRefraction=max(max(abs(refractionVector.x),abs(refractionVector.y)),abs(refractionVector.z));\nif (abs(refractionVector.x) != maxRefraction) refractionVector.x*=scaleRefraction;\nif (abs(refractionVector.y) != maxRefraction) refractionVector.y*=scaleRefraction;\nif (abs(refractionVector.z) != maxRefraction) refractionVector.z*=scaleRefraction;\n}\n#endif\nsurfaceRefractionColor=textureCubeLodEXT(refractionCubeSampler,refractionVector,lodRefraction).rgb*vRefractionInfos.x;\n#else\nsurfaceRefractionColor=textureCube(refractionCubeSampler,refractionVector,biasRefraction).rgb*vRefractionInfos.x;\n#endif\n}\n#ifndef REFRACTIONMAPINLINEARSPACE\nsurfaceRefractionColor=toLinearSpace(surfaceRefractionColor.rgb);\n#endif\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#ifdef LODBASEDMICROSFURACE\nsurfaceRefractionColor=texture2DLodEXT(refraction2DSampler,refractionCoords,lodRefraction).rgb*vRefractionInfos.x;\n#else\nsurfaceRefractionColor=texture2D(refraction2DSampler,refractionCoords,biasRefraction).rgb*vRefractionInfos.x;\n#endif \nsurfaceRefractionColor=toLinearSpace(surfaceRefractionColor.rgb);\n#endif\n#endif\n\nvec3 environmentRadiance=vReflectionColor.rgb;\nvec3 environmentIrradiance=vReflectionColor.rgb;\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFLECTION\nfloat lodReflection=getMipMapIndexFromAverageSlopeWithPMREM(vMicrosurfaceTextureLods.x,alphaG);\n#else\nfloat lodReflection=getMipMapIndexFromAverageSlope(vMicrosurfaceTextureLods.x,alphaG);\n#endif\n#else\nfloat biasReflection=(vMicrosurfaceTextureLods.x+2.)*(1.0-microSurface);\n#endif\n#ifdef REFLECTIONMAP_3D\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFLECTION\n\nif ((vMicrosurfaceTextureLods.y-lodReflection)>4.0)\n{\n\nfloat scaleReflection=1.-exp2(lodReflection)/exp2(vMicrosurfaceTextureLods.x); \nfloat maxReflection=max(max(abs(vReflectionUVW.x),abs(vReflectionUVW.y)),abs(vReflectionUVW.z));\nif (abs(vReflectionUVW.x) != maxReflection) vReflectionUVW.x*=scaleReflection;\nif (abs(vReflectionUVW.y) != maxReflection) vReflectionUVW.y*=scaleReflection;\nif (abs(vReflectionUVW.z) != maxReflection) vReflectionUVW.z*=scaleReflection;\n}\n#endif\nenvironmentRadiance=textureCubeLodEXT(reflectionCubeSampler,vReflectionUVW,lodReflection).rgb*vReflectionInfos.x;\n#else\nenvironmentRadiance=textureCube(reflectionCubeSampler,vReflectionUVW,biasReflection).rgb*vReflectionInfos.x;\n#endif\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#ifndef REFLECTIONMAP_SKYBOX\nvec3 normalEnvironmentSpace=(reflectionMatrix*vec4(normalW,1)).xyz;\nenvironmentIrradiance=EnvironmentIrradiance(normalEnvironmentSpace);\n#endif\n#else\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\nenvironmentIrradiance=textureCube(reflectionCubeSampler,normalW,20.).rgb*vReflectionInfos.x;\nenvironmentIrradiance=toLinearSpace(environmentIrradiance.rgb);\nenvironmentIrradiance*=0.2; \n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\n#ifdef LODBASEDMICROSFURACE\nenvironmentRadiance=texture2DLodEXT(reflection2DSampler,coords,lodReflection).rgb*vReflectionInfos.x;\n#else\nenvironmentRadiance=texture2D(reflection2DSampler,coords,biasReflection).rgb*vReflectionInfos.x;\n#endif\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\nenvironmentIrradiance=texture2D(reflection2DSampler,coords,20.).rgb*vReflectionInfos.x;\nenvironmentIrradiance=toLinearSpace(environmentIrradiance.rgb);\n#endif\n#endif\n#ifdef OVERLOADEDVALUES\nenvironmentIrradiance=mix(environmentIrradiance,vOverloadedReflection,vOverloadedMicroSurface.z);\nenvironmentRadiance=mix(environmentRadiance,vOverloadedReflection,vOverloadedMicroSurface.z);\n#endif\nenvironmentRadiance*=vLightingIntensity.z;\nenvironmentIrradiance*=vLightingIntensity.z;\n\nvec3 specularEnvironmentReflectance=FresnelSchlickEnvironmentGGX(clamp(NdotV,0.,1.),specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n\nvec3 refractance=vec3(0.0,0.0,0.0);\n#ifdef REFRACTION\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedoContribution.rgb*surfaceAlbedo.rgb;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedoContribution*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nsurfaceRefractionColor*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=surfaceRefractionColor*transmission;\n#endif\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\nrefractance*=vLightingIntensity.z;\nenvironmentRadiance*=specularEnvironmentReflectance;\n\nvec3 surfaceEmissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nsurfaceEmissiveColor=toLinearSpace(emissiveColorTex.rgb)*surfaceEmissiveColor*vEmissiveInfos.y;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceEmissiveColor=mix(surfaceEmissiveColor,vOverloadedEmissive,vOverloadedIntensity.w);\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nsurfaceEmissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=lightDiffuseContribution*surfaceAlbedoContribution;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution;\n#endif\n#else\n#ifdef LINKEMISSIVEWITHALBEDO\nvec3 finalDiffuse=(lightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=(shadowedOnlyLightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution;\n#endif\n#else\nvec3 finalDiffuse=lightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor;\n#endif\n#endif\n#endif\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution+=vAmbientColor;\nshadowedOnlyLightDiffuseContribution*=surfaceAlbedo.rgb;\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution,0.0);\nfinalDiffuse=mix(finalDiffuse,shadowedOnlyLightDiffuseContribution,(1.0-vOverloadedShadowIntensity.y));\n#endif\nfinalDiffuse=(finalDiffuse*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance)*ambientOcclusionColor;\n#ifdef SPECULARTERM\nvec3 finalSpecular=lightSpecularContribution*surfaceReflectivityColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+getLuminance(finalSpecular),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef RADIANCEOVERALPHA\nalpha=clamp(alpha+getLuminance(environmentRadiance),0.,1.);\n#endif\n\n\nvec4 finalColor=vec4(finalDiffuse+finalSpecular*vLightingIntensity.x+environmentRadiance+refractance,alpha);\n#ifdef EMISSIVEASILLUMINATION\nfinalColor.rgb+=(surfaceEmissiveColor*vLightingIntensity.y);\n#endif\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\nfinalColor=max(finalColor,0.0);\n#ifdef CAMERATONEMAP\nfinalColor.rgb=toneMaps(finalColor.rgb);\n#endif\nfinalColor.rgb=toGammaSpace(finalColor.rgb);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef CAMERACONTRAST\nfinalColor=contrasts(finalColor);\n#endif\nfinalColor.rgb=clamp(finalColor.rgb,0.,1.);\n#ifdef CAMERACOLORGRADING\nfinalColor=colorGrades(finalColor);\n#endif\n#ifdef CAMERACOLORCURVES\nfinalColor.rgb=applyColorCurves(finalColor.rgb);\n#endif\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ngl_FragColor=finalColor;\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\n\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\nvUV=offset;\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FULLFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying vec4 vPosition;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef CUBEMAP\nuniform vec3 lightPosition;\nuniform vec2 depthValues;\n#endif\nuniform vec2 biasAndScale;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#ifdef CUBEMAP\nvec3 directionToLight=vPosition.xyz-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\n#else\nfloat depth=vPosition.z/vPosition.w;\ndepth=depth*0.5+0.5; \n#endif\ndepth+=biasAndScale.x;\n#ifdef ESM\ndepth=exp(-min(87.,biasAndScale.y*depth));\n#endif\n#ifndef FULLFLOAT\ngl_FragColor=pack(depth);\n#else\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform float far;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=(gl_FragCoord.z/gl_FragCoord.w)/far;\ngl_FragColor=vec4(depth,depth*depth,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvoid main()\n{\nfloat texelsize=1.0/outSize;\nfloat compareDepth=texture2D(depthSampler,vUV).r;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=texture2D(depthSampler,samplePos).r;\nfloat weight=(1.0/(0.0001+abs(compareDepth-sampleDepth)));\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\nif (chromatic_aberration>0.0) {\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*radius*17.0/screen_width;\nfloat ref_shiftY=chromatic_aberration*radius*17.0/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\n}\ngl_FragColor=original;\n}","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(GAUSSIAN_BLUR_H) || defined(GAUSSIAN_BLUR_V)\nuniform float blurOffsets[9];\nuniform float blurWeights[9];\nuniform float blurWidth;\nvoid main(void)\n{\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfor (int i=0; i<9; i++) {\n#ifdef GAUSSIAN_BLUR_H\ncolor+=(texture2D(textureSampler,vUV+vec2(blurOffsets[i]*blurWidth,0.0))*blurWeights[i]);\ncolor+=(texture2D(textureSampler,vUV-vec2(blurOffsets[i]*blurWidth,0.0))*blurWeights[i]);\n#else\ncolor+=(texture2D(textureSampler,vUV+vec2(0.0,blurOffsets[i]*blurWidth))*blurWeights[i]);\ncolor+=(texture2D(textureSampler,vUV-vec2(0.0,blurOffsets[i]*blurWidth))*blurWeights[i]);\n#endif\n}\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","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}"};
  63134. 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#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\n","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec3 shadowsInfo;\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#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(REFLECTIVITY) || defined(METALLICWORKFLOW) \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\n#ifdef OVERLOADEDVALUES\nuniform vec4 vOverloadedIntensity;\nuniform vec3 vOverloadedAmbient;\nuniform vec3 vOverloadedAlbedo;\nuniform vec3 vOverloadedReflectivity;\nuniform vec3 vOverloadedEmissive;\nuniform vec3 vOverloadedReflection;\nuniform vec3 vOverloadedMicroSurface;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nuniform vec4 vOverloadedShadowIntensity;\n#endif\n#if defined(REFLECTION) || defined(REFRACTION)\nuniform vec2 vMicrosurfaceTextureLods;\n#endif\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#if defined(REFLECTIVITY) || defined(METALLICWORKFLOW) \nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifdef REFRACTIONMAP_3D\n#else\nuniform mat4 refractionMatrix;\n#endif\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec2 vMicrosurfaceTextureLods;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform vec4 opacityParts;\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\nuniform vec4 vOverloadedIntensity;\nuniform vec3 vOverloadedAmbient;\nuniform vec3 vOverloadedAlbedo;\nuniform vec3 vOverloadedReflectivity;\nuniform vec3 vOverloadedEmissive;\nuniform vec3 vOverloadedReflection;\nuniform vec3 vOverloadedMicroSurface;\nuniform vec4 vOverloadedShadowIntensity;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kPi=3.1415926535897932384626433832795;\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat Square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,vec3(0.2126,0.7152,0.0722)),0.,1.);\n}\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=Square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat getMipMapIndexFromAverageSlope(float maxMipLevel,float alpha)\n{\n\n\n\n\n\n\n\nfloat mip=kRougnhessToAlphaOffset+maxMipLevel+(maxMipLevel*kRougnhessToAlphaScale*log2(alpha));\nreturn clamp(mip,0.,maxMipLevel);\n}\nfloat getMipMapIndexFromAverageSlopeWithPMREM(float maxMipLevel,float alphaG)\n{\nfloat specularPower=clamp(2./alphaG-2.,0.000001,2048.);\n\nreturn clamp(- 0.5*log2(specularPower)+5.5,0.,maxMipLevel);\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=Square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(kPi*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 FresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 specularColor,vec3 reflectance90)\n{\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nvec3 fresnel=fresnelSchlickGGX(VdotH,specularColor,reflectance90);\nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nreturn fresnel*specTerm*kPi; \n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat diffuseFresnelTerm =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn diffuseFresnelTerm*NdotL;\n\n\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nfloat kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn vec3(pow(color.r,2.2),pow(color.g,2.2),pow(color.b,2.2));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn vec3(pow(color.r,1.0/2.2),pow(color.g,1.0/2.2),pow(color.b,1.0/2.2));\n}\n#ifdef CAMERATONEMAP\nvec3 toneMaps(vec3 color)\n{\ncolor=max(color,0.0);\n\ncolor.rgb=color.rgb*vCameraInfos.x;\nfloat tuning=1.5; \n\n\nvec3 tonemapped=1.0-exp2(-color.rgb*tuning); \ncolor.rgb=mix(color.rgb,tonemapped,1.0);\nreturn color;\n}\n#endif\n#ifdef CAMERACONTRAST\nvec4 contrasts(vec4 color)\n{\ncolor=clamp(color,0.0,1.0);\nvec3 resultHighContrast=color.rgb*color.rgb*(3.0-2.0*color.rgb);\nfloat contrast=vCameraInfos.y;\nif (contrast<1.0)\n{\n\ncolor.rgb=mix(vec3(0.5,0.5,0.5),color.rgb,contrast);\n}\nelse\n{\n\ncolor.rgb=mix(color.rgb,resultHighContrast,contrast-1.0);\n}\nreturn color;\n}\n#endif","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX;\nuniform vec3 vSphericalYY;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 EnvironmentIrradiance(vec3 normal)\n{\n\n\n\nvec3 result =\nvSphericalX*normal.x +\nvSphericalY*normal.y +\nvSphericalZ*normal.z +\nvSphericalXX*normal.x*normal.x +\nvSphericalYY*normal.y*normal.y +\nvSphericalZZ*normal.z*normal.z +\nvSphericalYZ*normal.y*normal.z +\nvSphericalZX*normal.z*normal.x +\nvSphericalXY*normal.x*normal.y;\nreturn result.rgb;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.0001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float lightAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat cosHalfAngle=cos(lightAngle*0.5);\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=lightAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=max(0.00000000001,dot(vNormal,lightDirection));\nfloat VdotH=clamp(0.00000000001,1.0,dot(viewDirectionW,H));\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor,reflectance90);\nresult.specular=specTerm*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=max(0.00000000001,dot(vNormal,directionToLightCenterW));\nfloat VdotH=clamp(dot(viewDirectionW,H),0.00000000001,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor,reflectance90);\nresult.specular=specTerm*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nNdotL=max(0.00000000001,NdotL);\nfloat VdotH=clamp(0.00000000001,1.0,dot(viewDirectionW,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor,reflectance90);\nresult.specular=specTerm;\n#endif\nreturn result;\n}","pbrLightFunctionsCall":"#ifdef LIGHT{X}\n#if defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X})\n\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR90,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR90,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR90,NdotL);\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWESM{X}\n#if defined(POINTLIGHT{X})\nnotShadowLevel=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z);\n#else\nnotShadowLevel=computeShadowWithESM(light{X}.vPositionFromLight,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z);\n#endif\n#else\n#ifdef SHADOWPCF{X}\n#if defined(POINTLIGHT{X})\nnotShadowLevel=computeShadowWithPCFCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x);\n#else\nnotShadowLevel=computeShadowWithPCF(vPositionFromLight{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x);\n#endif\n#else\n#if defined(POINTLIGHT{X})\nnotShadowLevel=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x);\n#else\nnotShadowLevel=computeShadow(vPositionFromLight{X},shadowSampler{X},light{X}.shadowsInfo.x);\n#endif\n#endif\n#endif\n#else\nnotShadowLevel=1.;\n#endif\n#if defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\nlightDiffuseContribution+=lightmapColor*notShadowLevel;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nlightSpecularContribution+=info.specular*notShadowLevel*lightmapColor;\n#endif\n#endif\n#else\nlightDiffuseContribution+=info.diffuse*notShadowLevel;\n#ifdef OVERLOADEDSHADOWVALUES\nif (NdotL<0.000000000011)\n{\nnotShadowLevel=1.;\n}\nshadowedOnlyLightDiffuseContribution*=notShadowLevel;\n#endif\n#ifdef SPECULARTERM\nlightSpecularContribution+=info.specular*notShadowLevel;\n#endif\n#endif\n#endif"};
  63135. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  63136. module.exports = BABYLON;
  63137. };